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.
147 require_once('include/crypto.php');
149 $res = new_keypair(4096);
151 $private_key = $res['prvkey'];
152 $public_key = $res['pubkey'];
154 // Save the private key. Send them the public key.
156 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
166 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
167 * site private key (person on the other end can decrypt it with our site public key).
168 * Then encrypt our profile URL with the other person's site public key. They can decrypt
169 * it with their site private key. If the decryption on the other end fails for either
170 * item, it indicates tampering or key failure on at least one site and we will not be
171 * able to provide a secure communication pathway.
173 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
174 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
175 * random key which is encrypted with their site public key.
179 $src_aes_key = random_string();
182 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
184 $params['dfrn_id'] = bin2hex($result);
185 $params['public_key'] = $public_key;
188 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
190 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
191 $params['source_url'] = bin2hex($params['source_url']);
193 if($aes_allow && function_exists('openssl_encrypt')) {
194 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
195 $params['aes_key'] = bin2hex($params['aes_key']);
196 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
199 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
201 $params['duplex'] = 1;
203 if($user[0]['page-flags'] == PAGE_COMMUNITY)
205 if($user[0]['page-flags'] == PAGE_PRVGROUP)
208 logger('dfrn_confirm: Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params,true), LOGGER_DATA);
212 * POST all this stuff to the other site.
213 * Temporarily raise the network timeout to 120 seconds because the default 60
214 * doesn't always give the other side quite enough time to decrypt everything.
218 $a->config['system']['curl_timeout'] = 120;
220 $res = post_url($dfrn_confirm,$params);
222 logger('dfrn_confirm: Confirm: received data: ' . $res, LOGGER_DATA);
224 // Now figure out what they responded. Try to be robust if the remote site is
225 // having difficulty and throwing up errors of some kind.
227 $leading_junk = substr($res,0,strpos($res,'<?xml'));
229 $res = substr($res,strpos($res,'<?xml'));
232 // No XML at all, this exchange is messed up really bad.
233 // We shouldn't proceed, because the xml parser might choke,
234 // and $status is going to be zero, which indicates success.
235 // We can hardly call this a success.
237 notice( t('Response from remote site was not understood.') . EOL);
241 if(strlen($leading_junk) && get_config('system','debugging')) {
243 // This might be more common. Mixed error text and some XML.
244 // If we're configured for debugging, show the text. Proceed in either case.
246 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
249 $xml = parse_xml_string($res);
250 $status = (int) $xml->status;
251 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
254 info( t("Confirmation completed successfully.") . EOL);
256 notice( t('Remote site reported: ') . $message . EOL);
259 // birthday paradox - generate new dfrn-id and fall through.
260 $new_dfrn_id = random_string();
261 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
268 notice( t("Temporary failure. Please wait and try again.") . EOL);
270 notice( t('Remote site reported: ') . $message . EOL);
275 notice( t("Introduction failed or was revoked.") . EOL);
277 notice( t('Remote site reported: ') . $message . EOL);
281 if(($status == 0) && ($intro_id)) {
283 // Success. Delete the notification.
285 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
299 * We have now established a relationship with the other site.
300 * Let's make our own personal copy of their profile photo so we don't have
301 * to always load it from their site.
303 * We will also update the contact record with the nature and scope of the relationship.
307 require_once('include/Photo.php');
309 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
311 logger('dfrn_confirm: confirm - imported photos');
313 if($network === NETWORK_DFRN) {
315 $new_relation = CONTACT_IS_FOLLOWER;
316 if(($relation == CONTACT_IS_SHARING) || ($duplex))
317 $new_relation = CONTACT_IS_FRIEND;
319 if(($relation == CONTACT_IS_SHARING) && ($duplex))
322 $r = q("UPDATE `contact` SET
329 `avatar-date` = '%s',
334 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
339 intval($new_relation),
340 dbesc(datetime_convert()),
341 dbesc(datetime_convert()),
342 dbesc(datetime_convert()),
350 // $network !== NETWORK_DFRN
352 $network = (($contact['network']) ? $contact['network'] : NETWORK_OSTATUS);
353 $notify = (($contact['notify']) ? $contact['notify'] : '');
354 $poll = (($contact['poll']) ? $contact['poll'] : '');
356 if((! $contact['notify']) || (! $contact['poll'])) {
357 $arr = lrdd($contact['url']);
359 foreach($arr as $link) {
360 if($link['@attributes']['rel'] === 'salmon')
361 $notify = $link['@attributes']['href'];
362 if($link['@attributes']['rel'] === NAMESPACE_FEED)
363 $poll = $link['@attributes']['href'];
368 $new_relation = $contact['rel'];
369 $writable = $contact['writable'];
371 if($network === NETWORK_DIASPORA) {
373 $new_relation = CONTACT_IS_FRIEND;
375 $new_relation = CONTACT_IS_SHARING;
377 if($new_relation != CONTACT_IS_FOLLOWER)
381 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
387 $r = q("UPDATE `contact` SET `photo` = '%s',
392 `avatar-date` = '%s',
401 WHERE `id` = %d LIMIT 1
406 dbesc(datetime_convert()),
407 dbesc(datetime_convert()),
408 dbesc(datetime_convert()),
414 intval($new_relation),
420 notice( t('Unable to set contact photo.') . EOL);
422 // reload contact info
424 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
433 if((isset($new_relation) && $new_relation == CONTACT_IS_FRIEND)) {
435 if(($contact) && ($contact['network'] === NETWORK_DIASPORA)) {
436 require_once('include/diaspora.php');
437 $ret = diaspora_share($user[0],$r[0]);
438 logger('mod_follow: diaspora_share returns: ' . $ret);
441 // Send a new friend post if we are allowed to...
443 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
447 if((count($r)) && ($r[0]['hide-friends'] == 0) && ($activity) && (! $hidden)) {
449 require_once('include/items.php');
451 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
458 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $uid);
460 $arr['contact-id'] = $self[0]['id'];
462 $arr['type'] = 'wall';
465 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
466 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
467 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
469 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
470 $APhoto = '[url=' . $self[0]['url'] . ']' . '[img]' . $self[0]['thumb'] . '[/img][/url]';
472 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
473 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
475 $arr['verb'] = ACTIVITY_FRIEND;
476 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
477 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$BPhoto;
479 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
480 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
481 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
482 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
483 $arr['object'] .= '</link></object>' . "\n";
485 $arr['last-child'] = 1;
487 $arr['allow_cid'] = $user[0]['allow_cid'];
488 $arr['allow_gid'] = $user[0]['allow_gid'];
489 $arr['deny_cid'] = $user[0]['deny_cid'];
490 $arr['deny_gid'] = $user[0]['deny_gid'];
492 $i = item_store($arr);
494 proc_run('php',"include/notifier.php","activity","$i");
500 $g = q("select def_gid from user where uid = %d limit 1",
503 if($contact && $g && intval($g[0]['def_gid'])) {
504 require_once('include/group.php');
505 group_add_member($uid,'',$contact['id'],$g[0]['def_gid']);
508 // Let's send our user to the contact editor in case they want to
509 // do anything special with this new friend.
511 if($handsfree === null)
512 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
521 * End of Scenario 1. [Local confirmation of remote friend request].
523 * Begin Scenario 2. This is the remote response to the above scenario.
524 * This will take place on the site that originally initiated the friend request.
525 * In the section above where the confirming party makes a POST and
526 * retrieves xml status information, they are communicating with the following code.
530 if(x($_POST,'source_url')) {
532 // We are processing an external confirmation to an introduction created by our user.
534 $public_key = ((x($_POST,'public_key')) ? $_POST['public_key'] : '');
535 $dfrn_id = ((x($_POST,'dfrn_id')) ? hex2bin($_POST['dfrn_id']) : '');
536 $source_url = ((x($_POST,'source_url')) ? hex2bin($_POST['source_url']) : '');
537 $aes_key = ((x($_POST,'aes_key')) ? $_POST['aes_key'] : '');
538 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
539 $page = ((x($_POST,'page')) ? intval($_POST['page']) : 0 );
540 $version_id = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
542 $forum = (($page == 1) ? 1 : 0);
543 $prv = (($page == 2) ? 1 : 0);
545 logger('dfrn_confirm: requestee contacted: ' . $node);
547 logger('dfrn_confirm: request: POST=' . print_r($_POST,true), LOGGER_DATA);
549 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
552 $aes_key = hex2bin($aes_key);
553 $public_key = hex2bin($public_key);
556 // Find our user's account
558 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
562 $message = sprintf(t('No user record found for \'%s\' '), $node);
563 xml_status(3,$message); // failure
567 $my_prvkey = $r[0]['prvkey'];
568 $local_uid = $r[0]['uid'];
571 if(! strstr($my_prvkey,'PRIVATE KEY')) {
572 $message = t('Our site encryption key is apparently messed up.');
573 xml_status(3,$message);
578 $decrypted_source_url = "";
579 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
582 if(! strlen($decrypted_source_url)) {
583 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
584 xml_status(3,$message);
588 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
589 dbesc($decrypted_source_url),
593 if(strstr($decrypted_source_url,'http:'))
594 $newurl = str_replace('http:','https:',$decrypted_source_url);
596 $newurl = str_replace('https:','http:',$decrypted_source_url);
598 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
603 // this is either a bogus confirmation (?) or we deleted the original introduction.
604 $message = t('Contact record was not found for you on our site.');
605 xml_status(3,$message);
606 return; // NOTREACHED
610 $relation = $ret[0]['rel'];
612 // Decrypt all this stuff we just received
614 $foreign_pubkey = $ret[0]['site-pubkey'];
615 $dfrn_record = $ret[0]['id'];
617 if(! $foreign_pubkey) {
618 $message = sprintf( t('Site public key not available in contact record for URL %s.'), $newurl);
619 xml_status(3,$message);
622 $decrypted_dfrn_id = "";
623 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
625 if(strlen($aes_key)) {
626 $decrypted_aes_key = "";
627 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
628 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
631 $dfrn_pubkey = $public_key;
634 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
635 dbesc($decrypted_dfrn_id)
638 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
639 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
643 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
644 dbesc($decrypted_dfrn_id),
649 $message = t('Unable to set your contact credentials on our system.');
650 xml_status(3,$message);
653 // It's possible that the other person also requested friendship.
654 // If it is a duplex relationship, ditch the issued-id if one exists.
657 $r = q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d LIMIT 1",
662 // We're good but now we have to scrape the profile photo and send notifications.
666 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
667 intval($dfrn_record));
670 $photo = $r[0]['photo'];
672 $photo = $a->get_baseurl() . '/images/person-175.jpg';
674 require_once("Photo.php");
676 $photos = import_profile_photo($photo,$local_uid,$dfrn_record);
678 logger('dfrn_confirm: request - photos imported');
680 $new_relation = CONTACT_IS_SHARING;
681 if(($relation == CONTACT_IS_FOLLOWER) || ($duplex))
682 $new_relation = CONTACT_IS_FRIEND;
684 if(($relation == CONTACT_IS_FOLLOWER) && ($duplex))
687 $r = q("UPDATE `contact` SET
694 `avatar-date` = '%s',
700 `network` = '%s' WHERE `id` = %d LIMIT 1
705 intval($new_relation),
706 dbesc(datetime_convert()),
707 dbesc(datetime_convert()),
708 dbesc(datetime_convert()),
715 if($r === false) { // indicates schema is messed up or total db failure
716 $message = t('Unable to update your contact profile details on our system');
717 xml_status(3,$message);
720 // Otherwise everything seems to have worked and we are almost done. Yay!
721 // Send an email notification
723 logger('dfrn_confirm: request: info updated');
725 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
726 WHERE `contact`.`id` = %d LIMIT 1",
733 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
735 push_lang($r[0]['language']);
736 $tpl = (($new_relation == CONTACT_IS_FRIEND)
737 ? get_intltext_template('friend_complete_eml.tpl')
738 : get_intltext_template('intro_complete_eml.tpl'));
740 $email_tpl = replace_macros($tpl, array(
741 '$sitename' => $a->config['sitename'],
742 '$siteurl' => $a->get_baseurl(),
743 '$username' => $r[0]['username'],
744 '$email' => $r[0]['email'],
745 '$fn' => $r[0]['name'],
746 '$dfrn_url' => $r[0]['url'],
750 $res = mail($r[0]['email'], sprintf( t("Connection accepted at %s") , $a->config['sitename']),
752 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
753 . 'Content-type: text/plain; charset=UTF-8' . "\n"
754 . 'Content-transfer-encoding: 8bit' );
757 // pointless throwing an error here and confusing the person at the other end of the wire.
762 // Send a new friend post if we are allowed to...
764 if($page && intval(get_pconfig($local_uid,'system','post_joingroup'))) {
765 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
769 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
771 require_once('include/items.php');
773 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
780 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid);
781 $arr['uid'] = $local_uid;
782 $arr['contact-id'] = $self[0]['id'];
784 $arr['type'] = 'wall';
787 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
788 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
789 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
791 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
792 $APhoto = '[url=' . $self[0]['url'] . ']' . '[img]' . $self[0]['thumb'] . '[/img][/url]';
794 $B = '[url=' . $combined['url'] . ']' . $combined['name'] . '[/url]';
795 $BPhoto = '[url=' . $combined['url'] . ']' . '[img]' . $combined['thumb'] . '[/img][/url]';
797 $arr['verb'] = ACTIVITY_JOIN;
798 $arr['object-type'] = ACTIVITY_OBJ_GROUP;
799 $arr['body'] = sprintf( t('%1$s has joined %2$s'), $A, $B)."\n\n\n" .$BPhoto;
800 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_GROUP . '</type><title>' . $combined['name'] . '</title>'
801 . '<id>' . $combined['url'] . '/' . $combined['name'] . '</id>';
802 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $combined['url'] . '" />' . "\n");
803 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $combined['thumb'] . '" />' . "\n");
804 $arr['object'] .= '</link></object>' . "\n";
806 $arr['last-child'] = 1;
808 $arr['allow_cid'] = $user[0]['allow_cid'];
809 $arr['allow_gid'] = $user[0]['allow_gid'];
810 $arr['deny_cid'] = $user[0]['deny_cid'];
811 $arr['deny_gid'] = $user[0]['deny_gid'];
813 $i = item_store($arr);
815 proc_run('php',"include/notifier.php","activity","$i");
820 xml_status(0); // Success
821 return; // NOTREACHED
823 ////////////////////// End of this scenario ///////////////////////////////////////////////
826 // somebody arrived here by mistake or they are fishing. Send them to the homepage.