3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 *Handles communication associated with the issuance of friend requests.
22 * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/stable/spec/dfrn2.pdf
23 * You also find a graphic which describes the confirmation process at
24 * https://github.com/friendica/friendica/blob/stable/spec/dfrn2_contact_request.png
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Search;
32 use Friendica\Core\Session;
33 use Friendica\Core\System;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Contact;
37 use Friendica\Model\Group;
38 use Friendica\Model\Notify;
39 use Friendica\Model\Notify\Type;
40 use Friendica\Model\Profile;
41 use Friendica\Model\User;
42 use Friendica\Module\Security\Login;
43 use Friendica\Network\Probe;
44 use Friendica\Protocol\Activity;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Network;
47 use Friendica\Util\Strings;
49 function dfrn_request_init(App $a)
53 Profile::load($a, $which);
60 * Function: dfrn_request_post
63 * Handles multiple scenarios.
66 * Clicking 'submit' on a friend request page.
69 * Following Scenario 1, we are brought back to our home site
70 * in order to link our friend request with our own server cell.
71 * After logging in, we click 'submit' to approve the linkage.
74 * @throws ImagickException
75 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
77 function dfrn_request_post(App $a)
79 if ($a->argc != 2 || empty($a->profile)) {
80 Logger::log('Wrong count of argc or profiles: argc=' . $a->argc . ', profile()=' . count($a->profile ?? []));
84 if (!empty($_POST['cancel'])) {
85 DI::baseUrl()->redirect();
89 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
90 * to confirm the request, and then we've clicked submit (perhaps after logging in).
91 * That brings us here:
93 if (!empty($_POST['localconfirm']) && ($_POST['localconfirm'] == 1)) {
94 // Ensure this is a valid request
95 if (local_user() && ($a->user['nickname'] == $a->argv[1]) && !empty($_POST['dfrn_url'])) {
96 $dfrn_url = Strings::escapeTags(trim($_POST['dfrn_url']));
97 $aes_allow = !empty($_POST['aes_allow']);
98 $confirm_key = $_POST['confirm_key'] ?? '';
99 $hidden = (!empty($_POST['hidden-contact']) ? intval($_POST['hidden-contact']) : 0);
100 $contact_record = null;
104 if (!empty($dfrn_url)) {
105 // Lookup the contact based on their URL (which is the only unique thing we have at the moment)
106 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
107 intval(local_user()),
108 DBA::escape(Strings::normaliseLink($dfrn_url))
111 if (DBA::isResult($r)) {
112 if (strlen($r[0]['dfrn-id'])) {
113 // We don't need to be here. It has already happened.
114 notice(DI::l10n()->t("This introduction has already been accepted."));
117 $contact_record = $r[0];
121 if (is_array($contact_record)) {
122 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
125 intval($contact_record['id'])
128 // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
129 $parms = Probe::profile($dfrn_url);
131 if (!count($parms)) {
132 notice(DI::l10n()->t('Profile location is not valid or does not contain profile information.'));
135 if (empty($parms['fn'])) {
136 notice(DI::l10n()->t('Warning: profile location has no identifiable owner name.'));
138 if (empty($parms['photo'])) {
139 notice(DI::l10n()->t('Warning: profile location has no profile photo.'));
141 $invalid = Probe::validDfrn($parms);
143 notice(DI::l10n()->tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid));
148 $dfrn_request = $parms['dfrn-request'];
150 $photo = $parms["photo"];
152 // Escape the entire array
153 DBA::escapeArray($parms);
155 // Create a contact record on our site for the other person
156 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
157 `request`, `confirm`, `notify`, `poll`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
158 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
159 intval(local_user()),
160 DateTimeFormat::utcNow(),
161 DBA::escape($dfrn_url),
162 DBA::escape(Strings::normaliseLink($dfrn_url)),
168 $parms['dfrn-request'],
169 $parms['dfrn-confirm'],
170 $parms['dfrn-notify'],
172 DBA::escape(Protocol::DFRN),
181 info(DI::l10n()->t("Introduction complete."));
184 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
185 intval(local_user()),
186 DBA::escape($dfrn_url),
187 $parms['key'] ?? '' // Potentially missing
189 if (DBA::isResult($r)) {
190 Group::addMember(User::getDefaultGroup(local_user(), $r[0]["network"]), $r[0]['id']);
193 Contact::updateAvatar($r[0]["id"], $photo, true);
196 $forward_path = "contact/" . $r[0]['id'];
198 $forward_path = "contact";
201 // Allow the blocked remote notification to complete
202 if (is_array($contact_record)) {
203 $dfrn_request = $contact_record['request'];
206 if (!empty($dfrn_request) && strlen($confirm_key)) {
207 DI::httpRequest()->fetch($dfrn_request . '?confirm_key=' . $confirm_key);
210 // (ignore reply, nothing we can do it failed)
211 DI::baseUrl()->redirect($forward_path);
212 return; // NOTREACHED
216 // invalid/bogus request
217 notice(DI::l10n()->t('Unrecoverable protocol error.'));
218 DI::baseUrl()->redirect();
219 return; // NOTREACHED
226 * We are the requestee. A person from a remote cell has made an introduction
227 * on our profile web page and clicked submit. We will use their DFRN-URL to
228 * figure out how to contact their cell.
230 * Scrape the originating DFRN-URL for everything we need. Create a contact record
231 * and an introduction to show our user next time he/she logs in.
232 * Finally redirect back to the requestor so that their site can record the request.
233 * If our user (the requestee) later confirms this request, a record of it will need
234 * to exist on the requestor's cell in order for the confirmation process to complete..
236 * It's possible that neither the requestor or the requestee are logged in at the moment,
237 * and the requestor does not yet have any credentials to the requestee profile.
239 * Who is the requestee? We've already loaded their profile which means their nickname should be
240 * in $a->argv[1] and we should have their complete info in $a->profile.
243 if (empty($a->profile['uid'])) {
244 notice(DI::l10n()->t('Profile unavailable.'));
248 $nickname = $a->profile['nickname'];
249 $uid = $a->profile['uid'];
250 $maxreq = intval($a->profile['maxreq']);
251 $contact_record = null;
257 if (!empty($_POST['dfrn_url'])) {
258 // Block friend request spam
260 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
261 DBA::escape(DateTimeFormat::utc('now - 24 hours')),
264 if (DBA::isResult($r) && count($r) > $maxreq) {
265 notice(DI::l10n()->t('%s has received too many connection requests today.', $a->profile['name']));
266 notice(DI::l10n()->t('Spam protection measures have been invoked.'));
267 notice(DI::l10n()->t('Friends are advised to please try again in 24 hours.'));
272 /* Cleanup old introductions that remain blocked.
273 * Also remove the contact record, but only if there is no existing relationship
275 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
276 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
277 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
278 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
280 if (DBA::isResult($r)) {
281 foreach ($r as $rr) {
283 DBA::delete('contact', ['id' => $rr['cid'], 'self' => false]);
285 DBA::delete('intro', ['id' => $rr['iid']]);
289 $url = trim($_POST['dfrn_url']);
291 notice(DI::l10n()->t("Invalid locator"));
297 // Detect the network
298 $data = Contact::getByURL($url);
299 $network = $data["network"];
301 // Canonicalize email-style profile locator
302 $url = Probe::webfingerDfrn($data['url'], $hcard);
304 if (substr($url, 0, 5) === 'stat:') {
305 // Every time we detect the remote subscription we define this as OStatus.
306 // We do this even if it is not OStatus.
307 // we only need to pass this through another section of the code.
308 if ($network != Protocol::DIASPORA) {
309 $network = Protocol::OSTATUS;
312 $url = substr($url, 5);
314 $network = Protocol::DFRN;
317 Logger::log('dfrn_request: url: ' . $url . ',network=' . $network, Logger::DEBUG);
319 if ($network === Protocol::DFRN) {
320 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
325 if (DBA::isResult($ret)) {
326 if (strlen($ret[0]['issued-id'])) {
327 notice(DI::l10n()->t('You have already introduced yourself here.'));
329 } elseif ($ret[0]['rel'] == Contact::FRIEND) {
330 notice(DI::l10n()->t('Apparently you are already friends with %s.', $a->profile['name']));
333 $contact_record = $ret[0];
334 $parms = ['dfrn-request' => $ret[0]['request']];
338 $issued_id = Strings::getRandomHex();
340 if (is_array($contact_record)) {
341 // There is a contact record but no issued-id, so this
342 // is a reciprocal introduction from a known contact
343 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
344 DBA::escape($issued_id),
345 intval($contact_record['id'])
348 $url = Network::isUrlValid($url);
350 notice(DI::l10n()->t('Invalid profile URL.'));
351 DI::baseUrl()->redirect(DI::args()->getCommand());
352 return; // NOTREACHED
355 if (!Network::isUrlAllowed($url)) {
356 notice(DI::l10n()->t('Disallowed profile URL.'));
357 DI::baseUrl()->redirect(DI::args()->getCommand());
358 return; // NOTREACHED
361 if (Network::isUrlBlocked($url)) {
362 notice(DI::l10n()->t('Blocked domain'));
363 DI::baseUrl()->redirect(DI::args()->getCommand());
364 return; // NOTREACHED
367 $parms = Probe::profile(($hcard) ? $hcard : $url);
369 if (!count($parms)) {
370 notice(DI::l10n()->t('Profile location is not valid or does not contain profile information.'));
371 DI::baseUrl()->redirect(DI::args()->getCommand());
373 if (empty($parms['fn'])) {
374 notice(DI::l10n()->t('Warning: profile location has no identifiable owner name.'));
376 if (empty($parms['photo'])) {
377 notice(DI::l10n()->t('Warning: profile location has no profile photo.'));
379 $invalid = Probe::validDfrn($parms);
381 notice(DI::l10n()->tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid));
387 $parms['url'] = $url;
388 $parms['issued-id'] = $issued_id;
389 $photo = $parms["photo"];
391 DBA::escapeArray($parms);
392 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
393 `request`, `confirm`, `notify`, `poll`, `network`, `blocked`, `pending` )
394 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
396 DBA::escape(DateTimeFormat::utcNow()),
398 DBA::escape(Strings::normaliseLink($url)),
405 $parms['dfrn-request'],
406 $parms['dfrn-confirm'],
407 $parms['dfrn-notify'],
409 DBA::escape(Protocol::DFRN),
414 // find the contact record we just created
416 $r = q("SELECT `id` FROM `contact`
417 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
422 if (DBA::isResult($r)) {
423 $contact_record = $r[0];
424 Contact::updateAvatar($contact_record["id"], $photo, true);
429 notice(DI::l10n()->t('Failed to update contact record.'));
433 $hash = Strings::getRandomHex() . (string) time(); // Generate a confirm_key
435 if (is_array($contact_record)) {
436 q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
437 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
439 intval($contact_record['id']),
440 intval(!empty($_POST['knowyou'])),
441 DBA::escape(Strings::escapeTags(trim($_POST['dfrn-request-message'] ?? ''))),
443 DBA::escape(DateTimeFormat::utcNow())
447 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
449 info(DI::l10n()->t('Your introduction has been sent.'));
452 // "Homecoming" - send the requestor back to their site to record the introduction.
453 $dfrn_url = bin2hex(DI::baseUrl()->get() . '/profile/' . $nickname);
454 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
456 System::externalRedirect($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
457 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
458 . '&confirm_key=' . $hash
459 . (($aes_allow) ? "&aes_allow=1" : "")
462 // END $network === Protocol::DFRN
463 } elseif (($network != Protocol::PHANTOM) && ($url != "")) {
465 /* Substitute our user's feed URL into $url template
466 * Send the subscriber home to subscribe
468 // Diaspora needs the uri in the format user@domain.tld
469 // Diaspora will support the remote subscription in a future version
470 if ($network == Protocol::DIASPORA) {
471 $uri = urlencode($a->profile['addr']);
473 $uri = urlencode($a->profile['url']);
476 $url = str_replace('{uri}', $uri, $url);
477 System::externalRedirect($url);
479 // END $network != Protocol::PHANTOM
481 notice(DI::l10n()->t("Remote subscription can't be done for your network. Please subscribe directly on your system."));
487 function dfrn_request_content(App $a)
489 if ($a->argc != 2 || empty($a->profile)) {
493 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
494 // to send us to the post section to record the introduction.
495 if (!empty($_GET['dfrn_url'])) {
497 info(DI::l10n()->t("Please login to confirm introduction."));
498 /* setup the return URL to come back to this page if they use openid */
499 return Login::form();
502 // Edge case, but can easily happen in the wild. This person is authenticated,
503 // but not as the person who needs to deal with this request.
504 if ($a->user['nickname'] != $a->argv[1]) {
505 notice(DI::l10n()->t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile."));
506 return Login::form();
509 $dfrn_url = Strings::escapeTags(trim(hex2bin($_GET['dfrn_url'])));
510 $aes_allow = !empty($_GET['aes_allow']);
511 $confirm_key = $_GET['confirm_key'] ?? '';
513 // Checking fastlane for validity
514 if (!empty($_SESSION['fastlane']) && (Strings::normaliseLink($_SESSION["fastlane"]) == Strings::normaliseLink($dfrn_url))) {
515 $_POST["dfrn_url"] = $dfrn_url;
516 $_POST["confirm_key"] = $confirm_key;
517 $_POST["localconfirm"] = 1;
518 $_POST["hidden-contact"] = 0;
519 $_POST["submit"] = DI::l10n()->t('Confirm');
521 dfrn_request_post($a);
526 $tpl = Renderer::getMarkupTemplate("dfrn_req_confirm.tpl");
527 $o = Renderer::replaceMacros($tpl, [
528 '$dfrn_url' => $dfrn_url,
529 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
530 '$hidethem' => DI::l10n()->t('Hide this contact'),
531 '$confirm_key' => $confirm_key,
532 '$welcome' => DI::l10n()->t('Welcome home %s.', $a->user['username']),
533 '$please' => DI::l10n()->t('Please confirm your introduction/connection request to %s.', $dfrn_url),
534 '$submit' => DI::l10n()->t('Confirm'),
535 '$uid' => $_SESSION['uid'],
536 '$nickname' => $a->user['nickname'],
537 'dfrn_rawurl' => $_GET['dfrn_url']
540 } elseif (!empty($_GET['confirm_key'])) {
541 // we are the requestee and it is now safe to send our user their introduction,
542 // We could just unblock it, but first we have to jump through a few hoops to
543 // send an email, or even to find out if we need to send an email.
544 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
545 DBA::escape($_GET['confirm_key'])
548 if (DBA::isResult($intro)) {
549 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
550 WHERE `contact`.`id` = %d LIMIT 1",
551 intval($intro[0]['contact-id'])
554 $auto_confirm = false;
556 if (DBA::isResult($r)) {
557 if ($r[0]['page-flags'] != User::PAGE_FLAGS_NORMAL && $r[0]['page-flags'] != User::PAGE_FLAGS_PRVGROUP) {
558 $auto_confirm = true;
561 if (!$auto_confirm) {
563 'type' => Type::INTRO,
564 'otype' => Notify\ObjectType::INTRO,
565 'verb' => Activity::REQ_FRIEND,
566 'uid' => $r[0]['uid'],
567 'cid' => $r[0]['id'],
568 'link' => DI::baseUrl() . '/notifications/intros',
573 require_once 'mod/dfrn_confirm.php';
575 'uid' => $r[0]['uid'],
576 'node' => $r[0]['nickname'],
577 'dfrn_id' => $r[0]['issued-id'],
578 'intro_id' => $intro[0]['id'],
579 'duplex' => (($r[0]['page-flags'] == User::PAGE_FLAGS_FREELOVE) ? 1 : 0),
581 dfrn_confirm_post($a, $handsfree);
585 if (!$auto_confirm) {
587 // If we are auto_confirming, this record will have already been nuked
588 // in dfrn_confirm_post()
590 q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
591 DBA::escape($_GET['confirm_key'])
598 // Normal web request. Display our user's introduction form.
599 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
600 if (!DI::config()->get('system', 'local_block')) {
601 notice(DI::l10n()->t('Public access denied.'));
606 // Try to auto-fill the profile address
607 // At first look if an address was provided
608 // Otherwise take the local address
609 if (!empty($_GET['addr'])) {
610 $myaddr = hex2bin($_GET['addr']);
611 } elseif (!empty($_GET['address'])) {
612 $myaddr = $_GET['address'];
613 } elseif (local_user()) {
614 if (strlen(DI::baseUrl()->getUrlPath())) {
615 $myaddr = DI::baseUrl() . '/profile/' . $a->user['nickname'];
617 $myaddr = $a->user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
621 $myaddr = Profile::getMyURL();
624 $target_addr = $a->profile['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
626 /* The auto_request form only has the profile address
627 * because nobody is going to read the comments and
628 * it doesn't matter if they know you or not.
630 if ($a->profile['page-flags'] == User::PAGE_FLAGS_NORMAL) {
631 $tpl = Renderer::getMarkupTemplate('dfrn_request.tpl');
633 $tpl = Renderer::getMarkupTemplate('auto_request.tpl');
636 $o = Renderer::replaceMacros($tpl, [
637 '$header' => DI::l10n()->t('Friend/Connection Request'),
638 '$page_desc' => DI::l10n()->t('Enter your Webfinger address (user@domain.tld) or profile URL here. If this isn\'t supported by your system (for example it doesn\'t work with Diaspora), you have to subscribe to <strong>%s</strong> directly on your system', $target_addr),
639 '$invite_desc' => DI::l10n()->t('If you are not yet a member of the free social web, <a href="%s">follow this link to find a public Friendica node and join us today</a>.', Search::getGlobalDirectory() . '/servers'),
640 '$your_address' => DI::l10n()->t('Your Webfinger address or profile URL:'),
641 '$pls_answer' => DI::l10n()->t('Please answer the following:'),
642 '$submit' => DI::l10n()->t('Submit Request'),
643 '$cancel' => DI::l10n()->t('Cancel'),
645 '$request' => 'dfrn_request/' . $a->argv[1],
646 '$name' => $a->profile['name'],
647 '$myaddr' => $myaddr,
649 '$does_know_you' => ['knowyou', DI::l10n()->t('%s knows you', $a->profile['name'])],
650 '$addnote_field' => ['dfrn-request-message', DI::l10n()->t('Add a personal note:')],