3 * @file mod/dfrn_confirm.php
4 * @brief Module: dfrn_confirm
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.
15 * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
16 * You also find a graphic which describes the confirmation process at
17 * https://github.com/friendica/friendica/blob/master/spec/dfrn2_contact_confirmation.png
21 use Friendica\Core\Config;
22 use Friendica\Core\L10n;
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\Item;
30 use Friendica\Model\User;
31 use Friendica\Network\Probe;
32 use Friendica\Protocol\Diaspora;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Network;
36 use Friendica\Util\XML;
38 require_once 'include/enotify.php';
39 require_once 'include/items.php';
41 function dfrn_confirm_post(App $a, $handsfree = null)
44 if (is_array($handsfree)) {
46 * We were called directly from dfrn_request due to automatic friend acceptance.
47 * Any $_POST parameters we may require are supplied in the $handsfree array.
50 $node = $handsfree['node'];
51 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
52 } elseif ($a->argc > 1) {
57 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
58 * from another site) and clicked 'Approve'.
59 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
61 * We may also have been called directly from dfrn_request ($handsfree != null) due to
62 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
63 * since we are operating on behalf of our registered user to approve a friendship.
65 if (!x($_POST, 'source_url')) {
66 $uid = defaults($handsfree, 'uid', local_user());
68 notice(L10n::t('Permission denied.') . EOL);
72 $user = dba::selectFirst('user', [], ['uid' => $uid]);
73 if (!DBM::is_result($user)) {
74 notice(L10n::t('Profile not found.') . EOL);
78 // These data elements may come from either the friend request notification form or $handsfree array.
79 if (is_array($handsfree)) {
80 logger('Confirm in handsfree mode');
81 $dfrn_id = $handsfree['dfrn_id'];
82 $intro_id = $handsfree['intro_id'];
83 $duplex = $handsfree['duplex'];
85 $hidden = intval(defaults($handsfree, 'hidden' , 0));
86 $activity = intval(defaults($handsfree, 'activity', 0));
88 $dfrn_id = notags(trim(defaults($_POST, 'dfrn_id' , '')));
89 $intro_id = intval(defaults($_POST, 'intro_id' , 0));
90 $duplex = intval(defaults($_POST, 'duplex' , 0));
91 $cid = intval(defaults($_POST, 'contact_id', 0));
92 $hidden = intval(defaults($_POST, 'hidden' , 0));
93 $activity = intval(defaults($_POST, 'activity' , 0));
97 * Ensure that dfrn_id has precedence when we go to find the contact record.
98 * We only want to search based on contact id if there is no dfrn_id,
99 * e.g. for OStatus network followers.
101 if (strlen($dfrn_id)) {
105 logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
107 logger('Confirming follower with contact_id: ' . $cid);
111 * The other person will have been issued an ID when they first requested friendship.
112 * Locate their record. At this time, their record will have both pending and blocked set to 1.
113 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
118 (`issued-id` != '' AND `issued-id` = '%s')
120 (`id` = %d AND `id` != 0)
129 if (!DBM::is_result($r)) {
130 logger('Contact not found in DB.');
131 notice(L10n::t('Contact not found.') . EOL);
132 notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
138 $contact_id = $contact['id'];
139 $relation = $contact['rel'];
140 $site_pubkey = $contact['site-pubkey'];
141 $dfrn_confirm = $contact['confirm'];
142 $aes_allow = $contact['aes_allow'];
144 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
146 if ($contact['network']) {
147 $network = $contact['network'];
150 if ($network === NETWORK_DFRN) {
152 * Generate a key pair for all further communications with this person.
153 * We have a keypair for every contact, and a site key for unknown people.
154 * This provides a means to carry on relationships with other people if
155 * any single key is compromised. It is a robust key. We're much more
156 * worried about key leakage than anybody cracking it.
158 $res = Crypto::newKeypair(4096);
160 $private_key = $res['prvkey'];
161 $public_key = $res['pubkey'];
163 // Save the private key. Send them the public key.
164 q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
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.
185 $src_aes_key = openssl_random_pseudo_bytes(64);
188 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
190 $params['dfrn_id'] = bin2hex($result);
191 $params['public_key'] = $public_key;
193 $my_url = System::baseUrl() . '/profile/' . $user['nickname'];
195 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
196 $params['source_url'] = bin2hex($params['source_url']);
198 if ($aes_allow && function_exists('openssl_encrypt')) {
199 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
200 $params['aes_key'] = bin2hex($params['aes_key']);
201 $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
204 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
206 $params['duplex'] = 1;
209 if ($user['page-flags'] == PAGE_COMMUNITY) {
213 if ($user['page-flags'] == PAGE_PRVGROUP) {
217 logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), LOGGER_DATA);
221 * POST all this stuff to the other site.
222 * Temporarily raise the network timeout to 120 seconds because the default 60
223 * doesn't always give the other side quite enough time to decrypt everything.
227 $res = Network::post($dfrn_confirm, $params, null, $redirects, 120);
229 logger(' Confirm: received data: ' . $res, LOGGER_DATA);
231 // Now figure out what they responded. Try to be robust if the remote site is
232 // having difficulty and throwing up errors of some kind.
234 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
236 $res = substr($res, strpos($res, '<?xml'));
238 // No XML at all, this exchange is messed up really bad.
239 // We shouldn't proceed, because the xml parser might choke,
240 // and $status is going to be zero, which indicates success.
241 // We can hardly call this a success.
242 notice(L10n::t('Response from remote site was not understood.') . EOL);
246 if (strlen($leading_junk) && Config::get('system', 'debugging')) {
247 // This might be more common. Mixed error text and some XML.
248 // If we're configured for debugging, show the text. Proceed in either case.
249 notice(L10n::t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
252 if (stristr($res, "<status") === false) {
253 // wrong xml! stop here!
254 notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
258 $xml = XML::parseString($res);
259 $status = (int) $xml->status;
260 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
263 info(L10n::t("Confirmation completed successfully.") . EOL);
266 // birthday paradox - generate new dfrn-id and fall through.
267 $new_dfrn_id = random_string();
268 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
275 notice(L10n::t("Temporary failure. Please wait and try again.") . EOL);
278 notice(L10n::t("Introduction failed or was revoked.") . EOL);
282 if (strlen($message)) {
283 notice(L10n::t('Remote site reported: ') . $message . EOL);
286 if (($status == 0) && ($intro_id)) {
287 // Success. Delete the notification.
288 q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
300 * We have now established a relationship with the other site.
301 * Let's make our own personal copy of their profile photo so we don't have
302 * to always load it from their site.
304 * We will also update the contact record with the nature and scope of the relationship.
306 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
308 logger('dfrn_confirm: confirm - imported photos');
310 if ($network === NETWORK_DFRN) {
311 $new_relation = CONTACT_IS_FOLLOWER;
312 if (($relation == CONTACT_IS_SHARING) || ($duplex)) {
313 $new_relation = CONTACT_IS_FRIEND;
316 if (($relation == CONTACT_IS_SHARING) && ($duplex)) {
320 $r = q("UPDATE `contact` SET `rel` = %d,
327 `network` = '%s' WHERE `id` = %d
329 intval($new_relation),
330 dbesc(DateTimeFormat::utcNow()),
331 dbesc(DateTimeFormat::utcNow()),
338 // $network !== NETWORK_DFRN
339 $network = defaults($contact, 'network', NETWORK_OSTATUS);
341 $arr = Probe::uri($contact['url']);
343 $notify = defaults($contact, 'notify' , $arr['notify']);
344 $poll = defaults($contact, 'poll' , $arr['poll']);
346 $addr = $arr['addr'];
348 $new_relation = $contact['rel'];
349 $writable = $contact['writable'];
351 if ($network === NETWORK_DIASPORA) {
353 $new_relation = CONTACT_IS_FRIEND;
355 $new_relation = CONTACT_IS_FOLLOWER;
358 if ($new_relation != CONTACT_IS_FOLLOWER) {
363 q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
368 $r = q("UPDATE `contact` SET `name-date` = '%s',
381 dbesc(DateTimeFormat::utcNow()),
382 dbesc(DateTimeFormat::utcNow()),
389 intval($new_relation),
394 /// @TODO is DBM::is_result() working here?
395 if (!DBM::is_result($r)) {
396 notice(L10n::t('Unable to set contact photo.') . EOL);
399 // reload contact info
400 $contact = dba::selectFirst('contact', [], ['id' => $contact_id]);
401 if ((isset($new_relation) && $new_relation == CONTACT_IS_FRIEND)) {
402 if (DBM::is_result($contact) && ($contact['network'] === NETWORK_DIASPORA)) {
403 $ret = Diaspora::sendShare($user, $contact);
404 logger('share returns: ' . $ret);
407 // Send a new friend post if we are allowed to...
408 $profile = dba::selectFirst('profile', ['hide-friends'], ['is-default' => true, 'uid' => $uid]);
409 if (x($profile, 'hide-friends') === 0 && $activity && !$hidden) {
410 $self = dba::selectFirst('contact', [], ['self' => true, 'uid' => $uid]);
411 if (DBM::is_result($self)) {
413 $arr['guid'] = get_guid(32);
414 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $uid);
416 $arr['contact-id'] = $self['id'];
418 $arr['type'] = 'wall';
421 $arr['author-name'] = $arr['owner-name'] = $self['name'];
422 $arr['author-link'] = $arr['owner-link'] = $self['url'];
423 $arr['author-avatar'] = $arr['owner-avatar'] = $self['thumb'];
425 $A = '[url=' . $self['url'] . ']' . $self['name'] . '[/url]';
426 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
427 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
429 $arr['verb'] = ACTIVITY_FRIEND;
430 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
431 $arr['body'] = L10n::t('%1$s is now friends with %2$s', $A, $B) . "\n\n\n" . $BPhoto;
433 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
434 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
435 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
436 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
437 $arr['object'] .= '</link></object>' . "\n";
439 $arr['allow_cid'] = $user['allow_cid'];
440 $arr['allow_gid'] = $user['allow_gid'];
441 $arr['deny_cid'] = $user['deny_cid'];
442 $arr['deny_gid'] = $user['deny_gid'];
444 $i = Item::insert($arr);
446 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
452 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
454 // Let's send our user to the contact editor in case they want to
455 // do anything special with this new friend.
456 if ($handsfree === null) {
457 goaway(System::baseUrl() . '/contacts/' . intval($contact_id));
465 * End of Scenario 1. [Local confirmation of remote friend request].
467 * Begin Scenario 2. This is the remote response to the above scenario.
468 * This will take place on the site that originally initiated the friend request.
469 * In the section above where the confirming party makes a POST and
470 * retrieves xml status information, they are communicating with the following code.
472 if (x($_POST, 'source_url')) {
473 // We are processing an external confirmation to an introduction created by our user.
474 $public_key = defaults($_POST, 'public_key', '');
475 $dfrn_id = hex2bin(defaults($_POST, 'dfrn_id' , ''));
476 $source_url = hex2bin(defaults($_POST, 'source_url', ''));
477 $aes_key = defaults($_POST, 'aes_key' , '');
478 $duplex = intval(defaults($_POST, 'duplex' , 0));
479 $page = intval(defaults($_POST, 'page' , 0));
481 $forum = (($page == 1) ? 1 : 0);
482 $prv = (($page == 2) ? 1 : 0);
484 logger('dfrn_confirm: requestee contacted: ' . $node);
486 logger('dfrn_confirm: request: POST=' . print_r($_POST, true), LOGGER_DATA);
488 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
491 $aes_key = hex2bin($aes_key);
492 $public_key = hex2bin($public_key);
495 // Find our user's account
496 $user = dba::selectFirst('user', [], ['nickname' => $node]);
497 if (!DBM::is_result($user)) {
498 $message = L10n::t('No user record found for \'%s\' ', $node);
499 System::xmlExit(3, $message); // failure
503 $my_prvkey = $user['prvkey'];
504 $local_uid = $user['uid'];
507 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
508 $message = L10n::t('Our site encryption key is apparently messed up.');
509 System::xmlExit(3, $message);
514 $decrypted_source_url = "";
515 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
518 if (!strlen($decrypted_source_url)) {
519 $message = L10n::t('Empty site URL was provided or URL could not be decrypted by us.');
520 System::xmlExit(3, $message);
524 $contact = dba::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
525 if (!DBM::is_result($contact)) {
526 if (strstr($decrypted_source_url, 'http:')) {
527 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
529 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
532 $contact = dba::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
533 if (!DBM::is_result($contact)) {
534 // this is either a bogus confirmation (?) or we deleted the original introduction.
535 $message = L10n::t('Contact record was not found for you on our site.');
536 System::xmlExit(3, $message);
537 return; // NOTREACHED
541 $relation = $contact['rel'];
543 // Decrypt all this stuff we just received
545 $foreign_pubkey = $contact['site-pubkey'];
546 $dfrn_record = $contact['id'];
548 if (!$foreign_pubkey) {
549 $message = L10n::t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
550 System::xmlExit(3, $message);
553 $decrypted_dfrn_id = "";
554 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
556 if (strlen($aes_key)) {
557 $decrypted_aes_key = "";
558 openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
559 $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
561 $dfrn_pubkey = $public_key;
564 if (dba::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
565 $message = L10n::t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
566 System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
570 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
571 dbesc($decrypted_dfrn_id),
575 if (!DBM::is_result($r)) {
576 $message = L10n::t('Unable to set your contact credentials on our system.');
577 System::xmlExit(3, $message);
580 // It's possible that the other person also requested friendship.
581 // If it is a duplex relationship, ditch the issued-id if one exists.
584 q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
589 // We're good but now we have to scrape the profile photo and send notifications.
590 $contact = dba::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
591 if (DBM::is_result($contact)) {
592 $photo = $contact['photo'];
594 $photo = System::baseUrl() . '/images/person-175.jpg';
597 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
599 logger('dfrn_confirm: request - photos imported');
601 $new_relation = CONTACT_IS_SHARING;
602 if (($relation == CONTACT_IS_FOLLOWER) || ($duplex)) {
603 $new_relation = CONTACT_IS_FRIEND;
606 if (($relation == CONTACT_IS_FOLLOWER) && ($duplex)) {
610 $r = q("UPDATE `contact` SET
619 `network` = '%s' WHERE `id` = %d
621 intval($new_relation),
622 dbesc(DateTimeFormat::utcNow()),
623 dbesc(DateTimeFormat::utcNow()),
630 if (!DBM::is_result($r)) { // indicates schema is messed up or total db failure
631 $message = L10n::t('Unable to update your contact profile details on our system');
632 System::xmlExit(3, $message);
635 // Otherwise everything seems to have worked and we are almost done. Yay!
636 // Send an email notification
638 logger('dfrn_confirm: request: info updated');
641 $r = q("SELECT `contact`.*, `user`.*
643 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
644 WHERE `contact`.`id` = %d
648 if (DBM::is_result($r)) {
651 if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
652 $mutual = ($new_relation == CONTACT_IS_FRIEND);
654 'type' => NOTIFY_CONFIRM,
655 'notify_flags' => $combined['notify-flags'],
656 'language' => $combined['language'],
657 'to_name' => $combined['username'],
658 'to_email' => $combined['email'],
659 'uid' => $combined['uid'],
660 'link' => System::baseUrl() . '/contacts/' . $dfrn_record,
661 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : L10n::t('[Name Withheld]')),
662 'source_link' => $combined['url'],
663 'source_photo' => $combined['photo'],
664 'verb' => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
670 // Send a new friend post if we are allowed to...
671 if ($page && intval(PConfig::get($local_uid, 'system', 'post_joingroup'))) {
672 $profile = dba::selectFirst('profile', ['hide-friends'], ['is-default' => true, 'uid' => $local_uid]);
673 if (x($profile, 'hide-friends') === 0) {
674 $self = dba::selectFirst('contact', [], ['self' => true, 'uid' => $local_uid]);
675 if (DBM::is_result($self)) {
677 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid);
678 $arr['uid'] = $local_uid;
679 $arr['contact-id'] = $self['id'];
681 $arr['type'] = 'wall';
684 $arr['author-name'] = $arr['owner-name'] = $self['name'];
685 $arr['author-link'] = $arr['owner-link'] = $self['url'];
686 $arr['author-avatar'] = $arr['owner-avatar'] = $self['thumb'];
688 $A = '[url=' . $self['url'] . ']' . $self['name'] . '[/url]';
689 $B = '[url=' . $combined['url'] . ']' . $combined['name'] . '[/url]';
690 $BPhoto = '[url=' . $combined['url'] . ']' . '[img]' . $combined['thumb'] . '[/img][/url]';
692 $arr['verb'] = ACTIVITY_JOIN;
693 $arr['object-type'] = ACTIVITY_OBJ_GROUP;
694 $arr['body'] = L10n::t('%1$s has joined %2$s', $A, $B) . "\n\n\n" . $BPhoto;
695 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_GROUP . '</type><title>' . $combined['name'] . '</title>'
696 . '<id>' . $combined['url'] . '/' . $combined['name'] . '</id>';
697 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $combined['url'] . '" />' . "\n");
698 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $combined['thumb'] . '" />' . "\n");
699 $arr['object'] .= '</link></object>' . "\n";
701 $arr['allow_cid'] = $user['allow_cid'];
702 $arr['allow_gid'] = $user['allow_gid'];
703 $arr['deny_cid'] = $user['deny_cid'];
704 $arr['deny_gid'] = $user['deny_gid'];
706 $i = Item::insert($arr);
708 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
713 System::xmlExit(0); // Success
714 return; // NOTREACHED
715 ////////////////////// End of this scenario ///////////////////////////////////////////////
718 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
719 goaway(System::baseUrl());