4 * @file mod/dfrn_confirm.php
5 * @brief Module: dfrn_confirm
6 * Purpose: Friendship acceptance for DFRN contacts
8 * There are two possible entry points and three scenarios.
10 * 1. A form was submitted by our user approving a friendship that originated elsewhere.
11 * This may also be called from dfrn_request to automatically approve a friendship.
13 * 2. We may be the target or other side of the conversation to scenario 1, and will
14 * interact with that process on our own user's behalf.
16 * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
17 * You also find a graphic which describes the confirmation process at
18 * https://github.com/friendica/friendica/blob/master/spec/dfrn2_contact_confirmation.png
22 use Friendica\Core\Config;
23 use Friendica\Core\PConfig;
24 use Friendica\Core\System;
25 use Friendica\Core\Worker;
26 use Friendica\Database\DBM;
27 use Friendica\Model\Contact;
28 use Friendica\Model\Group;
29 use Friendica\Model\User;
30 use Friendica\Network\Probe;
31 use Friendica\Protocol\Diaspora;
32 use Friendica\Util\Crypto;
34 require_once 'include/enotify.php';
35 require_once 'include/items.php';
37 function dfrn_confirm_post(App $a, $handsfree = null)
40 if (is_array($handsfree)) {
42 * We were called directly from dfrn_request due to automatic friend acceptance.
43 * Any $_POST parameters we may require are supplied in the $handsfree array.
46 $node = $handsfree['node'];
47 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
48 } elseif ($a->argc > 1) {
53 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
54 * from another site) and clicked 'Approve'.
55 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
57 * We may also have been called directly from dfrn_request ($handsfree != null) due to
58 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
59 * since we are operating on behalf of our registered user to approve a friendship.
61 if (!x($_POST, 'source_url')) {
62 $uid = defaults($handsfree, 'uid', local_user());
64 notice(t('Permission denied.') . EOL);
68 $user = dba::selectFirst('user', [], ['uid' => $uid]);
69 if (!DBM::is_result($user)) {
70 notice(t('Profile not found.') . EOL);
74 // These data elements may come from either the friend request notification form or $handsfree array.
75 if (is_array($handsfree)) {
76 logger('Confirm in handsfree mode');
77 $dfrn_id = $handsfree['dfrn_id'];
78 $intro_id = $handsfree['intro_id'];
79 $duplex = $handsfree['duplex'];
81 $hidden = intval(defaults($handsfree, 'hidden' , 0));
82 $activity = intval(defaults($handsfree, 'activity', 0));
84 $dfrn_id = notags(trim(defaults($_POST, 'dfrn_id' , '')));
85 $intro_id = intval(defaults($_POST, 'intro_id' , 0));
86 $duplex = intval(defaults($_POST, 'duplex' , 0));
87 $cid = intval(defaults($_POST, 'contact_id', 0));
88 $hidden = intval(defaults($_POST, 'hidden' , 0));
89 $activity = intval(defaults($_POST, 'activity' , 0));
93 * Ensure that dfrn_id has precedence when we go to find the contact record.
94 * We only want to search based on contact id if there is no dfrn_id,
95 * e.g. for OStatus network followers.
97 if (strlen($dfrn_id)) {
101 logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
103 logger('Confirming follower with contact_id: ' . $cid);
107 * The other person will have been issued an ID when they first requested friendship.
108 * Locate their record. At this time, their record will have both pending and blocked set to 1.
109 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
114 (`issued-id` != '' AND `issued-id` = '%s')
116 (`id` = %d AND `id` != 0)
125 if (!DBM::is_result($r)) {
126 logger('Contact not found in DB.');
127 notice(t('Contact not found.') . EOL);
128 notice(t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
134 $contact_id = $contact['id'];
135 $relation = $contact['rel'];
136 $site_pubkey = $contact['site-pubkey'];
137 $dfrn_confirm = $contact['confirm'];
138 $aes_allow = $contact['aes_allow'];
140 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
142 if ($contact['network']) {
143 $network = $contact['network'];
146 if ($network === NETWORK_DFRN) {
148 * Generate a key pair for all further communications with this person.
149 * We have a keypair for every contact, and a site key for unknown people.
150 * This provides a means to carry on relationships with other people if
151 * any single key is compromised. It is a robust key. We're much more
152 * worried about key leakage than anybody cracking it.
154 $res = Crypto::newKeypair(4096);
156 $private_key = $res['prvkey'];
157 $public_key = $res['pubkey'];
159 // Save the private key. Send them the public key.
160 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.
181 $src_aes_key = openssl_random_pseudo_bytes(64);
184 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
186 $params['dfrn_id'] = bin2hex($result);
187 $params['public_key'] = $public_key;
189 $my_url = System::baseUrl() . '/profile/' . $user['nickname'];
191 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
192 $params['source_url'] = bin2hex($params['source_url']);
194 if ($aes_allow && function_exists('openssl_encrypt')) {
195 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
196 $params['aes_key'] = bin2hex($params['aes_key']);
197 $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
200 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
202 $params['duplex'] = 1;
205 if ($user['page-flags'] == PAGE_COMMUNITY) {
209 if ($user['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 $res = post_url($dfrn_confirm, $params, null, $redirects, 120);
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'));
234 // No XML at all, this exchange is messed up really bad.
235 // We shouldn't proceed, because the xml parser might choke,
236 // and $status is going to be zero, which indicates success.
237 // We can hardly call this a success.
238 notice(t('Response from remote site was not understood.') . EOL);
242 if (strlen($leading_junk) && Config::get('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.
245 notice(t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
248 if (stristr($res, "<status") === false) {
249 // wrong xml! stop here!
250 notice(t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . 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);
262 // birthday paradox - generate new dfrn-id and fall through.
263 $new_dfrn_id = random_string();
264 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
271 notice(t("Temporary failure. Please wait and try again.") . EOL);
274 notice(t("Introduction failed or was revoked.") . EOL);
278 if (strlen($message)) {
279 notice(t('Remote site reported: ') . $message . EOL);
282 if (($status == 0) && ($intro_id)) {
283 // Success. Delete the notification.
284 q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
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.
302 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
304 logger('dfrn_confirm: confirm - imported photos');
306 if ($network === NETWORK_DFRN) {
307 $new_relation = CONTACT_IS_FOLLOWER;
308 if (($relation == CONTACT_IS_SHARING) || ($duplex)) {
309 $new_relation = CONTACT_IS_FRIEND;
312 if (($relation == CONTACT_IS_SHARING) && ($duplex)) {
316 $r = q("UPDATE `contact` SET `rel` = %d,
323 `network` = '%s' WHERE `id` = %d
325 intval($new_relation),
326 dbesc(datetime_convert()),
327 dbesc(datetime_convert()),
334 // $network !== NETWORK_DFRN
335 $network = defaults($contact, 'network', NETWORK_OSTATUS);
337 $arr = Probe::uri($contact['url']);
339 $notify = defaults($contact, 'notify' , $arr['notify']);
340 $poll = defaults($contact, 'poll' , $arr['poll']);
342 $addr = $arr['addr'];
344 $new_relation = $contact['rel'];
345 $writable = $contact['writable'];
347 if ($network === NETWORK_DIASPORA) {
349 $new_relation = CONTACT_IS_FRIEND;
351 $new_relation = CONTACT_IS_FOLLOWER;
354 if ($new_relation != CONTACT_IS_FOLLOWER) {
359 q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
364 $r = q("UPDATE `contact` SET `name-date` = '%s',
377 dbesc(datetime_convert()),
378 dbesc(datetime_convert()),
385 intval($new_relation),
390 /// @TODO is DBM::is_result() working here?
391 if (!DBM::is_result($r)) {
392 notice(t('Unable to set contact photo.') . EOL);
395 // reload contact info
396 $contact = dba::selectFirst('contact', [], ['id' => $contact_id]);
397 if ((isset($new_relation) && $new_relation == CONTACT_IS_FRIEND)) {
398 if (DBM::is_result($contact) && ($contact['network'] === NETWORK_DIASPORA)) {
399 $ret = Diaspora::sendShare($user, $contact);
400 logger('share returns: ' . $ret);
403 // Send a new friend post if we are allowed to...
404 $profile = dba::selectFirst('profile', ['hide-friends'], ['is-default' => true, 'uid' => $uid]);
405 if (x($profile, 'hide-friends') === 0 && $activity && !$hidden) {
406 $self = dba::selectFirst('contact', [], ['self' => true, 'uid' => $uid]);
407 if (DBM::is_result($self)) {
409 $arr['guid'] = get_guid(32);
410 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $uid);
412 $arr['contact-id'] = $self['id'];
414 $arr['type'] = 'wall';
417 $arr['author-name'] = $arr['owner-name'] = $self['name'];
418 $arr['author-link'] = $arr['owner-link'] = $self['url'];
419 $arr['author-avatar'] = $arr['owner-avatar'] = $self['thumb'];
421 $A = '[url=' . $self['url'] . ']' . $self['name'] . '[/url]';
422 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
423 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
425 $arr['verb'] = ACTIVITY_FRIEND;
426 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
427 $arr['body'] = t('%1$s is now friends with %2$s', $A, $B) . "\n\n\n" . $BPhoto;
429 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
430 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
431 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
432 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
433 $arr['object'] .= '</link></object>' . "\n";
435 $arr['allow_cid'] = $user['allow_cid'];
436 $arr['allow_gid'] = $user['allow_gid'];
437 $arr['deny_cid'] = $user['deny_cid'];
438 $arr['deny_gid'] = $user['deny_gid'];
440 $i = item_store($arr);
442 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
448 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
450 // Let's send our user to the contact editor in case they want to
451 // do anything special with this new friend.
452 if ($handsfree === null) {
453 goaway(System::baseUrl() . '/contacts/' . intval($contact_id));
461 * End of Scenario 1. [Local confirmation of remote friend request].
463 * Begin Scenario 2. This is the remote response to the above scenario.
464 * This will take place on the site that originally initiated the friend request.
465 * In the section above where the confirming party makes a POST and
466 * retrieves xml status information, they are communicating with the following code.
468 if (x($_POST, 'source_url')) {
469 // We are processing an external confirmation to an introduction created by our user.
470 $public_key = defaults($_POST, 'public_key', '');
471 $dfrn_id = hex2bin(defaults($_POST, 'dfrn_id' , ''));
472 $source_url = hex2bin(defaults($_POST, 'source_url', ''));
473 $aes_key = defaults($_POST, 'aes_key' , '');
474 $duplex = intval(defaults($_POST, 'duplex' , 0));
475 $page = intval(defaults($_POST, 'page' , 0));
477 $forum = (($page == 1) ? 1 : 0);
478 $prv = (($page == 2) ? 1 : 0);
480 logger('dfrn_confirm: requestee contacted: ' . $node);
482 logger('dfrn_confirm: request: POST=' . print_r($_POST, true), LOGGER_DATA);
484 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
487 $aes_key = hex2bin($aes_key);
488 $public_key = hex2bin($public_key);
491 // Find our user's account
492 $user = dba::selectFirst('user', [], ['nickname' => $node]);
493 if (!DBM::is_result($user)) {
494 $message = t('No user record found for \'%s\' ', $node);
495 xml_status(3, $message); // failure
499 $my_prvkey = $user['prvkey'];
500 $local_uid = $user['uid'];
503 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
504 $message = t('Our site encryption key is apparently messed up.');
505 xml_status(3, $message);
510 $decrypted_source_url = "";
511 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
514 if (!strlen($decrypted_source_url)) {
515 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
516 xml_status(3, $message);
520 $contact = dba::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
521 if (!DBM::is_result($contact)) {
522 if (strstr($decrypted_source_url, 'http:')) {
523 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
525 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
528 $contact = dba::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
529 if (!DBM::is_result($contact)) {
530 // this is either a bogus confirmation (?) or we deleted the original introduction.
531 $message = t('Contact record was not found for you on our site.');
532 xml_status(3, $message);
533 return; // NOTREACHED
537 $relation = $contact['rel'];
539 // Decrypt all this stuff we just received
541 $foreign_pubkey = $contact['site-pubkey'];
542 $dfrn_record = $contact['id'];
544 if (!$foreign_pubkey) {
545 $message = t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
546 xml_status(3, $message);
549 $decrypted_dfrn_id = "";
550 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
552 if (strlen($aes_key)) {
553 $decrypted_aes_key = "";
554 openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
555 $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
557 $dfrn_pubkey = $public_key;
560 if (dba::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
561 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
562 xml_status(1, $message); // Birthday paradox - duplicate dfrn-id
566 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
567 dbesc($decrypted_dfrn_id),
571 if (!DBM::is_result($r)) {
572 $message = t('Unable to set your contact credentials on our system.');
573 xml_status(3, $message);
576 // It's possible that the other person also requested friendship.
577 // If it is a duplex relationship, ditch the issued-id if one exists.
580 q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
585 // We're good but now we have to scrape the profile photo and send notifications.
586 $contact = dba::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
587 if (DBM::is_result($contact)) {
588 $photo = $contact['photo'];
590 $photo = System::baseUrl() . '/images/person-175.jpg';
593 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
595 logger('dfrn_confirm: request - photos imported');
597 $new_relation = CONTACT_IS_SHARING;
598 if (($relation == CONTACT_IS_FOLLOWER) || ($duplex)) {
599 $new_relation = CONTACT_IS_FRIEND;
602 if (($relation == CONTACT_IS_FOLLOWER) && ($duplex)) {
606 $r = q("UPDATE `contact` SET
615 `network` = '%s' WHERE `id` = %d
617 intval($new_relation),
618 dbesc(datetime_convert()),
619 dbesc(datetime_convert()),
626 if (!DBM::is_result($r)) { // indicates schema is messed up or total db failure
627 $message = t('Unable to update your contact profile details on our system');
628 xml_status(3, $message);
631 // Otherwise everything seems to have worked and we are almost done. Yay!
632 // Send an email notification
634 logger('dfrn_confirm: request: info updated');
637 $r = q("SELECT `contact`.*, `user`.*
639 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
640 WHERE `contact`.`id` = %d
644 if (DBM::is_result($r)) {
647 if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
648 $mutual = ($new_relation == CONTACT_IS_FRIEND);
650 'type' => NOTIFY_CONFIRM,
651 'notify_flags' => $combined['notify-flags'],
652 'language' => $combined['language'],
653 'to_name' => $combined['username'],
654 'to_email' => $combined['email'],
655 'uid' => $combined['uid'],
656 'link' => System::baseUrl() . '/contacts/' . $dfrn_record,
657 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : t('[Name Withheld]')),
658 'source_link' => $combined['url'],
659 'source_photo' => $combined['photo'],
660 'verb' => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
666 // Send a new friend post if we are allowed to...
667 if ($page && intval(PConfig::get($local_uid, 'system', 'post_joingroup'))) {
668 $profile = dba::selectFirst('profile', ['hide-friends'], ['is-default' => true, 'uid' => $local_uid]);
669 if (x($profile, 'hide-friends') === 0) {
670 $self = dba::selectFirst('contact', [], ['self' => true, 'uid' => $local_uid]);
671 if (DBM::is_result($self)) {
673 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid);
674 $arr['uid'] = $local_uid;
675 $arr['contact-id'] = $self['id'];
677 $arr['type'] = 'wall';
680 $arr['author-name'] = $arr['owner-name'] = $self['name'];
681 $arr['author-link'] = $arr['owner-link'] = $self['url'];
682 $arr['author-avatar'] = $arr['owner-avatar'] = $self['thumb'];
684 $A = '[url=' . $self['url'] . ']' . $self['name'] . '[/url]';
685 $B = '[url=' . $combined['url'] . ']' . $combined['name'] . '[/url]';
686 $BPhoto = '[url=' . $combined['url'] . ']' . '[img]' . $combined['thumb'] . '[/img][/url]';
688 $arr['verb'] = ACTIVITY_JOIN;
689 $arr['object-type'] = ACTIVITY_OBJ_GROUP;
690 $arr['body'] = t('%1$s has joined %2$s', $A, $B) . "\n\n\n" . $BPhoto;
691 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_GROUP . '</type><title>' . $combined['name'] . '</title>'
692 . '<id>' . $combined['url'] . '/' . $combined['name'] . '</id>';
693 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $combined['url'] . '" />' . "\n");
694 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $combined['thumb'] . '" />' . "\n");
695 $arr['object'] .= '</link></object>' . "\n";
697 $arr['allow_cid'] = $user['allow_cid'];
698 $arr['allow_gid'] = $user['allow_gid'];
699 $arr['deny_cid'] = $user['deny_cid'];
700 $arr['deny_gid'] = $user['deny_gid'];
702 $i = item_store($arr);
704 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
709 xml_status(0); // Success
710 return; // NOTREACHED
711 ////////////////////// End of this scenario ///////////////////////////////////////////////
714 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
715 goaway(System::baseUrl());