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\Network;
35 use Friendica\Util\XML;
37 require_once 'include/enotify.php';
38 require_once 'include/items.php';
40 function dfrn_confirm_post(App $a, $handsfree = null)
43 if (is_array($handsfree)) {
45 * We were called directly from dfrn_request due to automatic friend acceptance.
46 * Any $_POST parameters we may require are supplied in the $handsfree array.
49 $node = $handsfree['node'];
50 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
51 } elseif ($a->argc > 1) {
56 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
57 * from another site) and clicked 'Approve'.
58 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
60 * We may also have been called directly from dfrn_request ($handsfree != null) due to
61 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
62 * since we are operating on behalf of our registered user to approve a friendship.
64 if (!x($_POST, 'source_url')) {
65 $uid = defaults($handsfree, 'uid', local_user());
67 notice(L10n::t('Permission denied.') . EOL);
71 $user = dba::selectFirst('user', [], ['uid' => $uid]);
72 if (!DBM::is_result($user)) {
73 notice(L10n::t('Profile not found.') . EOL);
77 // These data elements may come from either the friend request notification form or $handsfree array.
78 if (is_array($handsfree)) {
79 logger('Confirm in handsfree mode');
80 $dfrn_id = $handsfree['dfrn_id'];
81 $intro_id = $handsfree['intro_id'];
82 $duplex = $handsfree['duplex'];
84 $hidden = intval(defaults($handsfree, 'hidden' , 0));
85 $activity = intval(defaults($handsfree, 'activity', 0));
87 $dfrn_id = notags(trim(defaults($_POST, 'dfrn_id' , '')));
88 $intro_id = intval(defaults($_POST, 'intro_id' , 0));
89 $duplex = intval(defaults($_POST, 'duplex' , 0));
90 $cid = intval(defaults($_POST, 'contact_id', 0));
91 $hidden = intval(defaults($_POST, 'hidden' , 0));
92 $activity = intval(defaults($_POST, 'activity' , 0));
96 * Ensure that dfrn_id has precedence when we go to find the contact record.
97 * We only want to search based on contact id if there is no dfrn_id,
98 * e.g. for OStatus network followers.
100 if (strlen($dfrn_id)) {
104 logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
106 logger('Confirming follower with contact_id: ' . $cid);
110 * The other person will have been issued an ID when they first requested friendship.
111 * Locate their record. At this time, their record will have both pending and blocked set to 1.
112 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
117 (`issued-id` != '' AND `issued-id` = '%s')
119 (`id` = %d AND `id` != 0)
128 if (!DBM::is_result($r)) {
129 logger('Contact not found in DB.');
130 notice(L10n::t('Contact not found.') . EOL);
131 notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
137 $contact_id = $contact['id'];
138 $relation = $contact['rel'];
139 $site_pubkey = $contact['site-pubkey'];
140 $dfrn_confirm = $contact['confirm'];
141 $aes_allow = $contact['aes_allow'];
143 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
145 if ($contact['network']) {
146 $network = $contact['network'];
149 if ($network === NETWORK_DFRN) {
151 * Generate a key pair for all further communications with this person.
152 * We have a keypair for every contact, and a site key for unknown people.
153 * This provides a means to carry on relationships with other people if
154 * any single key is compromised. It is a robust key. We're much more
155 * worried about key leakage than anybody cracking it.
157 $res = Crypto::newKeypair(4096);
159 $private_key = $res['prvkey'];
160 $public_key = $res['pubkey'];
162 // Save the private key. Send them the public key.
163 q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
172 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
173 * site private key (person on the other end can decrypt it with our site public key).
174 * Then encrypt our profile URL with the other person's site public key. They can decrypt
175 * it with their site private key. If the decryption on the other end fails for either
176 * item, it indicates tampering or key failure on at least one site and we will not be
177 * able to provide a secure communication pathway.
179 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
180 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
181 * random key which is encrypted with their site public key.
184 $src_aes_key = openssl_random_pseudo_bytes(64);
187 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
189 $params['dfrn_id'] = bin2hex($result);
190 $params['public_key'] = $public_key;
192 $my_url = System::baseUrl() . '/profile/' . $user['nickname'];
194 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
195 $params['source_url'] = bin2hex($params['source_url']);
197 if ($aes_allow && function_exists('openssl_encrypt')) {
198 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
199 $params['aes_key'] = bin2hex($params['aes_key']);
200 $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
203 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
205 $params['duplex'] = 1;
208 if ($user['page-flags'] == PAGE_COMMUNITY) {
212 if ($user['page-flags'] == PAGE_PRVGROUP) {
216 logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), LOGGER_DATA);
220 * POST all this stuff to the other site.
221 * Temporarily raise the network timeout to 120 seconds because the default 60
222 * doesn't always give the other side quite enough time to decrypt everything.
226 $res = Network::post($dfrn_confirm, $params, null, $redirects, 120);
228 logger(' Confirm: received data: ' . $res, LOGGER_DATA);
230 // Now figure out what they responded. Try to be robust if the remote site is
231 // having difficulty and throwing up errors of some kind.
233 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
235 $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.
241 notice(L10n::t('Response from remote site was not understood.') . EOL);
245 if (strlen($leading_junk) && Config::get('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.
248 notice(L10n::t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
251 if (stristr($res, "<status") === false) {
252 // wrong xml! stop here!
253 notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
257 $xml = XML::parseString($res);
258 $status = (int) $xml->status;
259 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
262 info(L10n::t("Confirmation completed successfully.") . EOL);
265 // birthday paradox - generate new dfrn-id and fall through.
266 $new_dfrn_id = random_string();
267 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
274 notice(L10n::t("Temporary failure. Please wait and try again.") . EOL);
277 notice(L10n::t("Introduction failed or was revoked.") . EOL);
281 if (strlen($message)) {
282 notice(L10n::t('Remote site reported: ') . $message . EOL);
285 if (($status == 0) && ($intro_id)) {
286 // Success. Delete the notification.
287 q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
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.
305 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
307 logger('dfrn_confirm: confirm - imported photos');
309 if ($network === NETWORK_DFRN) {
310 $new_relation = CONTACT_IS_FOLLOWER;
311 if (($relation == CONTACT_IS_SHARING) || ($duplex)) {
312 $new_relation = CONTACT_IS_FRIEND;
315 if (($relation == CONTACT_IS_SHARING) && ($duplex)) {
319 $r = q("UPDATE `contact` SET `rel` = %d,
326 `network` = '%s' WHERE `id` = %d
328 intval($new_relation),
329 dbesc(datetime_convert()),
330 dbesc(datetime_convert()),
337 // $network !== NETWORK_DFRN
338 $network = defaults($contact, 'network', NETWORK_OSTATUS);
340 $arr = Probe::uri($contact['url']);
342 $notify = defaults($contact, 'notify' , $arr['notify']);
343 $poll = defaults($contact, 'poll' , $arr['poll']);
345 $addr = $arr['addr'];
347 $new_relation = $contact['rel'];
348 $writable = $contact['writable'];
350 if ($network === NETWORK_DIASPORA) {
352 $new_relation = CONTACT_IS_FRIEND;
354 $new_relation = CONTACT_IS_FOLLOWER;
357 if ($new_relation != CONTACT_IS_FOLLOWER) {
362 q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
367 $r = q("UPDATE `contact` SET `name-date` = '%s',
380 dbesc(datetime_convert()),
381 dbesc(datetime_convert()),
388 intval($new_relation),
393 /// @TODO is DBM::is_result() working here?
394 if (!DBM::is_result($r)) {
395 notice(L10n::t('Unable to set contact photo.') . EOL);
398 // reload contact info
399 $contact = dba::selectFirst('contact', [], ['id' => $contact_id]);
400 if ((isset($new_relation) && $new_relation == CONTACT_IS_FRIEND)) {
401 if (DBM::is_result($contact) && ($contact['network'] === NETWORK_DIASPORA)) {
402 $ret = Diaspora::sendShare($user, $contact);
403 logger('share returns: ' . $ret);
406 // Send a new friend post if we are allowed to...
407 $profile = dba::selectFirst('profile', ['hide-friends'], ['is-default' => true, 'uid' => $uid]);
408 if (x($profile, 'hide-friends') === 0 && $activity && !$hidden) {
409 $self = dba::selectFirst('contact', [], ['self' => true, 'uid' => $uid]);
410 if (DBM::is_result($self)) {
412 $arr['guid'] = get_guid(32);
413 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $uid);
415 $arr['contact-id'] = $self['id'];
417 $arr['type'] = 'wall';
420 $arr['author-name'] = $arr['owner-name'] = $self['name'];
421 $arr['author-link'] = $arr['owner-link'] = $self['url'];
422 $arr['author-avatar'] = $arr['owner-avatar'] = $self['thumb'];
424 $A = '[url=' . $self['url'] . ']' . $self['name'] . '[/url]';
425 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
426 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
428 $arr['verb'] = ACTIVITY_FRIEND;
429 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
430 $arr['body'] = L10n::t('%1$s is now friends with %2$s', $A, $B) . "\n\n\n" . $BPhoto;
432 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
433 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
434 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
435 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
436 $arr['object'] .= '</link></object>' . "\n";
438 $arr['allow_cid'] = $user['allow_cid'];
439 $arr['allow_gid'] = $user['allow_gid'];
440 $arr['deny_cid'] = $user['deny_cid'];
441 $arr['deny_gid'] = $user['deny_gid'];
443 $i = Item::insert($arr);
445 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
451 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
453 // Let's send our user to the contact editor in case they want to
454 // do anything special with this new friend.
455 if ($handsfree === null) {
456 goaway(System::baseUrl() . '/contacts/' . intval($contact_id));
464 * End of Scenario 1. [Local confirmation of remote friend request].
466 * Begin Scenario 2. This is the remote response to the above scenario.
467 * This will take place on the site that originally initiated the friend request.
468 * In the section above where the confirming party makes a POST and
469 * retrieves xml status information, they are communicating with the following code.
471 if (x($_POST, 'source_url')) {
472 // We are processing an external confirmation to an introduction created by our user.
473 $public_key = defaults($_POST, 'public_key', '');
474 $dfrn_id = hex2bin(defaults($_POST, 'dfrn_id' , ''));
475 $source_url = hex2bin(defaults($_POST, 'source_url', ''));
476 $aes_key = defaults($_POST, 'aes_key' , '');
477 $duplex = intval(defaults($_POST, 'duplex' , 0));
478 $page = intval(defaults($_POST, 'page' , 0));
480 $forum = (($page == 1) ? 1 : 0);
481 $prv = (($page == 2) ? 1 : 0);
483 logger('dfrn_confirm: requestee contacted: ' . $node);
485 logger('dfrn_confirm: request: POST=' . print_r($_POST, true), LOGGER_DATA);
487 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
490 $aes_key = hex2bin($aes_key);
491 $public_key = hex2bin($public_key);
494 // Find our user's account
495 $user = dba::selectFirst('user', [], ['nickname' => $node]);
496 if (!DBM::is_result($user)) {
497 $message = L10n::t('No user record found for \'%s\' ', $node);
498 System::xmlExit(3, $message); // failure
502 $my_prvkey = $user['prvkey'];
503 $local_uid = $user['uid'];
506 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
507 $message = L10n::t('Our site encryption key is apparently messed up.');
508 System::xmlExit(3, $message);
513 $decrypted_source_url = "";
514 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
517 if (!strlen($decrypted_source_url)) {
518 $message = L10n::t('Empty site URL was provided or URL could not be decrypted by us.');
519 System::xmlExit(3, $message);
523 $contact = dba::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
524 if (!DBM::is_result($contact)) {
525 if (strstr($decrypted_source_url, 'http:')) {
526 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
528 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
531 $contact = dba::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
532 if (!DBM::is_result($contact)) {
533 // this is either a bogus confirmation (?) or we deleted the original introduction.
534 $message = L10n::t('Contact record was not found for you on our site.');
535 System::xmlExit(3, $message);
536 return; // NOTREACHED
540 $relation = $contact['rel'];
542 // Decrypt all this stuff we just received
544 $foreign_pubkey = $contact['site-pubkey'];
545 $dfrn_record = $contact['id'];
547 if (!$foreign_pubkey) {
548 $message = L10n::t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
549 System::xmlExit(3, $message);
552 $decrypted_dfrn_id = "";
553 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
555 if (strlen($aes_key)) {
556 $decrypted_aes_key = "";
557 openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
558 $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
560 $dfrn_pubkey = $public_key;
563 if (dba::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
564 $message = L10n::t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
565 System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
569 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
570 dbesc($decrypted_dfrn_id),
574 if (!DBM::is_result($r)) {
575 $message = L10n::t('Unable to set your contact credentials on our system.');
576 System::xmlExit(3, $message);
579 // It's possible that the other person also requested friendship.
580 // If it is a duplex relationship, ditch the issued-id if one exists.
583 q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
588 // We're good but now we have to scrape the profile photo and send notifications.
589 $contact = dba::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
590 if (DBM::is_result($contact)) {
591 $photo = $contact['photo'];
593 $photo = System::baseUrl() . '/images/person-175.jpg';
596 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
598 logger('dfrn_confirm: request - photos imported');
600 $new_relation = CONTACT_IS_SHARING;
601 if (($relation == CONTACT_IS_FOLLOWER) || ($duplex)) {
602 $new_relation = CONTACT_IS_FRIEND;
605 if (($relation == CONTACT_IS_FOLLOWER) && ($duplex)) {
609 $r = q("UPDATE `contact` SET
618 `network` = '%s' WHERE `id` = %d
620 intval($new_relation),
621 dbesc(datetime_convert()),
622 dbesc(datetime_convert()),
629 if (!DBM::is_result($r)) { // indicates schema is messed up or total db failure
630 $message = L10n::t('Unable to update your contact profile details on our system');
631 System::xmlExit(3, $message);
634 // Otherwise everything seems to have worked and we are almost done. Yay!
635 // Send an email notification
637 logger('dfrn_confirm: request: info updated');
640 $r = q("SELECT `contact`.*, `user`.*
642 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
643 WHERE `contact`.`id` = %d
647 if (DBM::is_result($r)) {
650 if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
651 $mutual = ($new_relation == CONTACT_IS_FRIEND);
653 'type' => NOTIFY_CONFIRM,
654 'notify_flags' => $combined['notify-flags'],
655 'language' => $combined['language'],
656 'to_name' => $combined['username'],
657 'to_email' => $combined['email'],
658 'uid' => $combined['uid'],
659 'link' => System::baseUrl() . '/contacts/' . $dfrn_record,
660 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : L10n::t('[Name Withheld]')),
661 'source_link' => $combined['url'],
662 'source_photo' => $combined['photo'],
663 'verb' => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
669 // Send a new friend post if we are allowed to...
670 if ($page && intval(PConfig::get($local_uid, 'system', 'post_joingroup'))) {
671 $profile = dba::selectFirst('profile', ['hide-friends'], ['is-default' => true, 'uid' => $local_uid]);
672 if (x($profile, 'hide-friends') === 0) {
673 $self = dba::selectFirst('contact', [], ['self' => true, 'uid' => $local_uid]);
674 if (DBM::is_result($self)) {
676 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid);
677 $arr['uid'] = $local_uid;
678 $arr['contact-id'] = $self['id'];
680 $arr['type'] = 'wall';
683 $arr['author-name'] = $arr['owner-name'] = $self['name'];
684 $arr['author-link'] = $arr['owner-link'] = $self['url'];
685 $arr['author-avatar'] = $arr['owner-avatar'] = $self['thumb'];
687 $A = '[url=' . $self['url'] . ']' . $self['name'] . '[/url]';
688 $B = '[url=' . $combined['url'] . ']' . $combined['name'] . '[/url]';
689 $BPhoto = '[url=' . $combined['url'] . ']' . '[img]' . $combined['thumb'] . '[/img][/url]';
691 $arr['verb'] = ACTIVITY_JOIN;
692 $arr['object-type'] = ACTIVITY_OBJ_GROUP;
693 $arr['body'] = L10n::t('%1$s has joined %2$s', $A, $B) . "\n\n\n" . $BPhoto;
694 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_GROUP . '</type><title>' . $combined['name'] . '</title>'
695 . '<id>' . $combined['url'] . '/' . $combined['name'] . '</id>';
696 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $combined['url'] . '" />' . "\n");
697 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $combined['thumb'] . '" />' . "\n");
698 $arr['object'] .= '</link></object>' . "\n";
700 $arr['allow_cid'] = $user['allow_cid'];
701 $arr['allow_gid'] = $user['allow_gid'];
702 $arr['deny_cid'] = $user['deny_cid'];
703 $arr['deny_gid'] = $user['deny_gid'];
705 $i = Item::insert($arr);
707 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
712 System::xmlExit(0); // Success
713 return; // NOTREACHED
714 ////////////////////// End of this scenario ///////////////////////////////////////////////
717 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
718 goaway(System::baseUrl());