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');
19 function dfrn_confirm_post(&$a,$handsfree = null) {
21 if(is_array($handsfree)) {
24 * We were called directly from dfrn_request due to automatic friend acceptance.
25 * Any $_POST parameters we may require are supplied in the $handsfree array.
29 $node = $handsfree['node'];
30 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
40 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
41 * from another site) and clicked 'Approve'.
42 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
44 * We may also have been called directly from dfrn_request ($handsfree != null) due to
45 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
46 * since we are operating on behalf of our registered user to approve a friendship.
50 if(! x($_POST,'source_url')) {
52 $uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user());
55 notice( t('Permission denied.') . EOL );
59 $user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
64 notice( t('Profile not found.') . EOL );
69 // These data elements may come from either the friend request notification form or $handsfree array.
71 if(is_array($handsfree)) {
72 logger('Confirm in handsfree mode');
73 $dfrn_id = $handsfree['dfrn_id'];
74 $intro_id = $handsfree['intro_id'];
75 $duplex = $handsfree['duplex'];
76 $hidden = ((array_key_exists('hidden',$handsfree)) ? intval($handsfree['hidden']) : 0 );
77 $activity = ((array_key_exists('activity',$handsfree)) ? intval($handsfree['activity']) : 0 );
80 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
81 $intro_id = ((x($_POST,'intro_id')) ? intval($_POST['intro_id']) : 0 );
82 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
83 $cid = ((x($_POST,'contact_id')) ? intval($_POST['contact_id']) : 0 );
84 $hidden = ((x($_POST,'hidden')) ? intval($_POST['hidden']) : 0 );
85 $activity = ((x($_POST,'activity')) ? intval($_POST['activity']) : 0 );
90 * Ensure that dfrn_id has precedence when we go to find the contact record.
91 * We only want to search based on contact id if there is no dfrn_id,
92 * e.g. for OStatus network followers.
99 logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
101 logger('Confirming follower with contact_id: ' . $cid);
106 * The other person will have been issued an ID when they first requested friendship.
107 * Locate their record. At this time, their record will have both pending and blocked set to 1.
108 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
112 $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",
119 logger('Contact not found in DB.');
120 notice( t('Contact not found.') . EOL );
121 notice( t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL );
127 $contact_id = $contact['id'];
128 $relation = $contact['rel'];
129 $site_pubkey = $contact['site-pubkey'];
130 $dfrn_confirm = $contact['confirm'];
131 $aes_allow = $contact['aes_allow'];
133 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
135 if($contact['network'])
136 $network = $contact['network'];
138 if($network === NETWORK_DFRN) {
142 * Generate a key pair for all further communications with this person.
143 * We have a keypair for every contact, and a site key for unknown people.
144 * This provides a means to carry on relationships with other people if
145 * any single key is compromised. It is a robust key. We're much more
146 * worried about key leakage than anybody cracking it.
149 require_once('include/crypto.php');
151 $res = new_keypair(4096);
154 $private_key = $res['prvkey'];
155 $public_key = $res['pubkey'];
157 // Save the private key. Send them the public key.
159 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
169 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
170 * site private key (person on the other end can decrypt it with our site public key).
171 * Then encrypt our profile URL with the other person's site public key. They can decrypt
172 * it with their site private key. If the decryption on the other end fails for either
173 * item, it indicates tampering or key failure on at least one site and we will not be
174 * able to provide a secure communication pathway.
176 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
177 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
178 * random key which is encrypted with their site public key.
182 $src_aes_key = random_string();
185 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
187 $params['dfrn_id'] = bin2hex($result);
188 $params['public_key'] = $public_key;
191 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
193 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
194 $params['source_url'] = bin2hex($params['source_url']);
196 if($aes_allow && function_exists('openssl_encrypt')) {
197 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
198 $params['aes_key'] = bin2hex($params['aes_key']);
199 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
202 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
204 $params['duplex'] = 1;
206 if($user[0]['page-flags'] == PAGE_COMMUNITY)
208 if($user[0]['page-flags'] == PAGE_PRVGROUP)
211 logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params,true), LOGGER_DATA);
215 * POST all this stuff to the other site.
216 * Temporarily raise the network timeout to 120 seconds because the default 60
217 * doesn't always give the other side quite enough time to decrypt everything.
221 $a->config['system']['curl_timeout'] = 120;
223 $res = post_url($dfrn_confirm,$params);
225 logger(' Confirm: received data: ' . $res, LOGGER_DATA);
227 // Now figure out what they responded. Try to be robust if the remote site is
228 // having difficulty and throwing up errors of some kind.
230 $leading_junk = substr($res,0,strpos($res,'<?xml'));
232 $res = substr($res,strpos($res,'<?xml'));
235 // No XML at all, this exchange is messed up really bad.
236 // We shouldn't proceed, because the xml parser might choke,
237 // and $status is going to be zero, which indicates success.
238 // We can hardly call this a success.
240 notice( t('Response from remote site was not understood.') . EOL);
244 if(strlen($leading_junk) && get_config('system','debugging')) {
246 // This might be more common. Mixed error text and some XML.
247 // If we're configured for debugging, show the text. Proceed in either case.
249 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
252 if(stristr($res, "<status")===false) {
253 // wrong xml! stop here!
254 notice( t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL );
258 $xml = parse_xml_string($res);
259 $status = (int) $xml->status;
260 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
263 info( t("Confirmation completed successfully.") . EOL);
265 notice( t('Remote site reported: ') . $message . EOL);
268 // birthday paradox - generate new dfrn-id and fall through.
269 $new_dfrn_id = random_string();
270 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
277 notice( t("Temporary failure. Please wait and try again.") . EOL);
279 notice( t('Remote site reported: ') . $message . EOL);
284 notice( t("Introduction failed or was revoked.") . EOL);
286 notice( t('Remote site reported: ') . $message . EOL);
290 if(($status == 0) && ($intro_id)) {
292 // Success. Delete the notification.
294 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
308 * We have now established a relationship with the other site.
309 * Let's make our own personal copy of their profile photo so we don't have
310 * to always load it from their site.
312 * We will also update the contact record with the nature and scope of the relationship.
316 require_once('include/Photo.php');
318 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
320 logger('dfrn_confirm: confirm - imported photos');
322 if($network === NETWORK_DFRN) {
324 $new_relation = CONTACT_IS_FOLLOWER;
325 if(($relation == CONTACT_IS_SHARING) || ($duplex))
326 $new_relation = CONTACT_IS_FRIEND;
328 if(($relation == CONTACT_IS_SHARING) && ($duplex))
331 $r = q("UPDATE `contact` SET
338 `avatar-date` = '%s',
343 `network` = '%s' WHERE `id` = %d
348 intval($new_relation),
349 dbesc(datetime_convert()),
350 dbesc(datetime_convert()),
351 dbesc(datetime_convert()),
360 // $network !== NETWORK_DFRN
362 $network = (($contact['network']) ? $contact['network'] : NETWORK_OSTATUS);
363 $notify = (($contact['notify']) ? $contact['notify'] : '');
364 $poll = (($contact['poll']) ? $contact['poll'] : '');
366 if((! $contact['notify']) || (! $contact['poll'])) {
367 $arr = lrdd($contact['url']);
369 foreach($arr as $link) {
370 if($link['@attributes']['rel'] === 'salmon')
371 $notify = $link['@attributes']['href'];
372 if($link['@attributes']['rel'] === NAMESPACE_FEED)
373 $poll = $link['@attributes']['href'];
378 $new_relation = $contact['rel'];
379 $writable = $contact['writable'];
381 if($network === NETWORK_DIASPORA) {
383 $new_relation = CONTACT_IS_FRIEND;
385 $new_relation = CONTACT_IS_SHARING;
387 if($new_relation != CONTACT_IS_FOLLOWER)
391 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
397 $r = q("UPDATE `contact` SET `photo` = '%s',
402 `avatar-date` = '%s',
416 dbesc(datetime_convert()),
417 dbesc(datetime_convert()),
418 dbesc(datetime_convert()),
424 intval($new_relation),
430 notice( t('Unable to set contact photo.') . EOL);
432 // reload contact info
434 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
443 if((isset($new_relation) && $new_relation == CONTACT_IS_FRIEND)) {
445 if(($contact) && ($contact['network'] === NETWORK_DIASPORA)) {
446 require_once('include/diaspora.php');
447 $ret = diaspora_share($user[0],$r[0]);
448 logger('mod_follow: diaspora_share returns: ' . $ret);
451 // Send a new friend post if we are allowed to...
453 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
457 if((count($r)) && ($r[0]['hide-friends'] == 0) && ($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]';
485 $arr['verb'] = ACTIVITY_FRIEND;
486 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
487 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$BPhoto;
489 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
490 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
491 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
492 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
493 $arr['object'] .= '</link></object>' . "\n";
495 $arr['last-child'] = 1;
497 $arr['allow_cid'] = $user[0]['allow_cid'];
498 $arr['allow_gid'] = $user[0]['allow_gid'];
499 $arr['deny_cid'] = $user[0]['deny_cid'];
500 $arr['deny_gid'] = $user[0]['deny_gid'];
502 $i = item_store($arr);
504 proc_run('php',"include/notifier.php","activity","$i");
510 $g = q("select def_gid from user where uid = %d limit 1",
513 if($contact && $g && intval($g[0]['def_gid'])) {
514 require_once('include/group.php');
515 group_add_member($uid,'',$contact['id'],$g[0]['def_gid']);
518 // Let's send our user to the contact editor in case they want to
519 // do anything special with this new friend.
521 if($handsfree === null)
522 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
531 * End of Scenario 1. [Local confirmation of remote friend request].
533 * Begin Scenario 2. This is the remote response to the above scenario.
534 * This will take place on the site that originally initiated the friend request.
535 * In the section above where the confirming party makes a POST and
536 * retrieves xml status information, they are communicating with the following code.
540 if(x($_POST,'source_url')) {
542 // We are processing an external confirmation to an introduction created by our user.
544 $public_key = ((x($_POST,'public_key')) ? $_POST['public_key'] : '');
545 $dfrn_id = ((x($_POST,'dfrn_id')) ? hex2bin($_POST['dfrn_id']) : '');
546 $source_url = ((x($_POST,'source_url')) ? hex2bin($_POST['source_url']) : '');
547 $aes_key = ((x($_POST,'aes_key')) ? $_POST['aes_key'] : '');
548 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
549 $page = ((x($_POST,'page')) ? intval($_POST['page']) : 0 );
550 $version_id = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
552 $forum = (($page == 1) ? 1 : 0);
553 $prv = (($page == 2) ? 1 : 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",
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",
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("include/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',
710 `network` = '%s' WHERE `id` = %d
715 intval($new_relation),
716 dbesc(datetime_convert()),
717 dbesc(datetime_convert()),
718 dbesc(datetime_convert()),
725 if($r === false) { // indicates schema is messed up or total db failure
726 $message = t('Unable to update your contact profile details on our system');
727 xml_status(3,$message);
730 // Otherwise everything seems to have worked and we are almost done. Yay!
731 // Send an email notification
733 logger('dfrn_confirm: request: info updated');
735 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
736 WHERE `contact`.`id` = %d LIMIT 1",
743 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
744 $mutual = ($new_relation == CONTACT_IS_FRIEND);
746 'type' => NOTIFY_CONFIRM,
747 'notify_flags' => $r[0]['notify-flags'],
748 'language' => $r[0]['language'],
749 'to_name' => $r[0]['username'],
750 'to_email' => $r[0]['email'],
751 'uid' => $r[0]['uid'],
752 'link' => $a->get_baseurl() . '/contacts/' . $dfrn_record,
753 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
754 'source_link' => $r[0]['url'],
755 'source_photo' => $r[0]['photo'],
756 'verb' => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
761 // Send a new friend post if we are allowed to...
763 if($page && intval(get_pconfig($local_uid,'system','post_joingroup'))) {
764 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
768 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
770 require_once('include/items.php');
772 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
779 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid);
780 $arr['uid'] = $local_uid;
781 $arr['contact-id'] = $self[0]['id'];
783 $arr['type'] = 'wall';
786 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
787 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
788 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
790 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
791 $APhoto = '[url=' . $self[0]['url'] . ']' . '[img]' . $self[0]['thumb'] . '[/img][/url]';
793 $B = '[url=' . $combined['url'] . ']' . $combined['name'] . '[/url]';
794 $BPhoto = '[url=' . $combined['url'] . ']' . '[img]' . $combined['thumb'] . '[/img][/url]';
796 $arr['verb'] = ACTIVITY_JOIN;
797 $arr['object-type'] = ACTIVITY_OBJ_GROUP;
798 $arr['body'] = sprintf( t('%1$s has joined %2$s'), $A, $B)."\n\n\n" .$BPhoto;
799 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_GROUP . '</type><title>' . $combined['name'] . '</title>'
800 . '<id>' . $combined['url'] . '/' . $combined['name'] . '</id>';
801 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $combined['url'] . '" />' . "\n");
802 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $combined['thumb'] . '" />' . "\n");
803 $arr['object'] .= '</link></object>' . "\n";
805 $arr['last-child'] = 1;
807 $arr['allow_cid'] = $user[0]['allow_cid'];
808 $arr['allow_gid'] = $user[0]['allow_gid'];
809 $arr['deny_cid'] = $user[0]['deny_cid'];
810 $arr['deny_gid'] = $user[0]['deny_gid'];
812 $i = item_store($arr);
814 proc_run('php',"include/notifier.php","activity","$i");
819 xml_status(0); // Success
820 return; // NOTREACHED
822 ////////////////////// End of this scenario ///////////////////////////////////////////////
825 // somebody arrived here by mistake or they are fishing. Send them to the homepage.