4 * @file mod/dfrn_request.php
5 * @brief Module: dfrn_request
7 * Purpose: Handles communication associated with the issuance of
10 * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
11 * You also find a graphic which describes the confirmation process at
12 * https://github.com/friendica/friendica/blob/master/spec/dfrn2_contact_request.png
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\Protocol;
20 use Friendica\Core\Renderer;
21 use Friendica\Core\System;
22 use Friendica\Core\Session;
23 use Friendica\Database\DBA;
24 use Friendica\Model\Contact;
25 use Friendica\Model\Group;
26 use Friendica\Model\Profile;
27 use Friendica\Model\User;
28 use Friendica\Module\Login;
29 use Friendica\Network\Probe;
30 use Friendica\Protocol\Activity;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\Strings;
35 function dfrn_request_init(App $a)
39 Profile::load($a, $which);
46 * Function: dfrn_request_post
49 * Handles multiple scenarios.
52 * Clicking 'submit' on a friend request page.
55 * Following Scenario 1, we are brought back to our home site
56 * in order to link our friend request with our own server cell.
57 * After logging in, we click 'submit' to approve the linkage.
60 * @throws ImagickException
61 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
63 function dfrn_request_post(App $a)
65 if (($a->argc != 2) || (!count($a->profile))) {
66 Logger::log('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
70 if (!empty($_POST['cancel'])) {
71 $a->internalRedirect();
75 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
76 * to confirm the request, and then we've clicked submit (perhaps after logging in).
77 * That brings us here:
79 if (!empty($_POST['localconfirm']) && ($_POST['localconfirm'] == 1)) {
80 // Ensure this is a valid request
81 if (local_user() && ($a->user['nickname'] == $a->argv[1]) && !empty($_POST['dfrn_url'])) {
82 $dfrn_url = Strings::escapeTags(trim($_POST['dfrn_url']));
83 $aes_allow = !empty($_POST['aes_allow']);
84 $confirm_key = $_POST['confirm_key'] ?? '';
85 $hidden = (!empty($_POST['hidden-contact']) ? intval($_POST['hidden-contact']) : 0);
86 $contact_record = null;
90 if (!empty($dfrn_url)) {
91 // Lookup the contact based on their URL (which is the only unique thing we have at the moment)
92 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
94 DBA::escape(Strings::normaliseLink($dfrn_url))
97 if (DBA::isResult($r)) {
98 if (strlen($r[0]['dfrn-id'])) {
99 // We don't need to be here. It has already happened.
100 notice(L10n::t("This introduction has already been accepted.") . EOL);
103 $contact_record = $r[0];
107 if (is_array($contact_record)) {
108 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
111 intval($contact_record['id'])
114 // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
115 $parms = Probe::profile($dfrn_url);
117 if (!count($parms)) {
118 notice(L10n::t('Profile location is not valid or does not contain profile information.') . EOL);
121 if (empty($parms['fn'])) {
122 notice(L10n::t('Warning: profile location has no identifiable owner name.') . EOL);
124 if (empty($parms['photo'])) {
125 notice(L10n::t('Warning: profile location has no profile photo.') . EOL);
127 $invalid = Probe::validDfrn($parms);
129 notice(L10n::tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid) . EOL);
134 $dfrn_request = $parms['dfrn-request'];
136 $photo = $parms["photo"];
138 // Escape the entire array
139 DBA::escapeArray($parms);
141 // Create a contact record on our site for the other person
142 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
143 `request`, `confirm`, `notify`, `poll`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
144 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
145 intval(local_user()),
146 DateTimeFormat::utcNow(),
147 DBA::escape($dfrn_url),
148 DBA::escape(Strings::normaliseLink($dfrn_url)),
154 $parms['dfrn-request'],
155 $parms['dfrn-confirm'],
156 $parms['dfrn-notify'],
158 DBA::escape(Protocol::DFRN),
167 info(L10n::t("Introduction complete.") . EOL);
170 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
171 intval(local_user()),
172 DBA::escape($dfrn_url),
173 $parms['key'] ?? '' // Potentially missing
175 if (DBA::isResult($r)) {
176 Group::addMember(User::getDefaultGroup(local_user(), $r[0]["network"]), $r[0]['id']);
179 Contact::updateAvatar($photo, local_user(), $r[0]["id"], true);
182 $forward_path = "contact/" . $r[0]['id'];
184 $forward_path = "contact";
187 // Allow the blocked remote notification to complete
188 if (is_array($contact_record)) {
189 $dfrn_request = $contact_record['request'];
192 if (!empty($dfrn_request) && strlen($confirm_key)) {
193 Network::fetchUrl($dfrn_request . '?confirm_key=' . $confirm_key);
196 // (ignore reply, nothing we can do it failed)
197 $a->internalRedirect($forward_path);
198 return; // NOTREACHED
202 // invalid/bogus request
203 notice(L10n::t('Unrecoverable protocol error.') . EOL);
204 $a->internalRedirect();
205 return; // NOTREACHED
212 * We are the requestee. A person from a remote cell has made an introduction
213 * on our profile web page and clicked submit. We will use their DFRN-URL to
214 * figure out how to contact their cell.
216 * Scrape the originating DFRN-URL for everything we need. Create a contact record
217 * and an introduction to show our user next time he/she logs in.
218 * Finally redirect back to the requestor so that their site can record the request.
219 * If our user (the requestee) later confirms this request, a record of it will need
220 * to exist on the requestor's cell in order for the confirmation process to complete..
222 * It's possible that neither the requestor or the requestee are logged in at the moment,
223 * and the requestor does not yet have any credentials to the requestee profile.
225 * Who is the requestee? We've already loaded their profile which means their nickname should be
226 * in $a->argv[1] and we should have their complete info in $a->profile.
229 if (!(is_array($a->profile) && count($a->profile))) {
230 notice(L10n::t('Profile unavailable.') . EOL);
234 $nickname = $a->profile['nickname'];
235 $uid = $a->profile['uid'];
236 $maxreq = intval($a->profile['maxreq']);
237 $contact_record = null;
243 if (!empty($_POST['dfrn_url'])) {
244 // Block friend request spam
246 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
247 DBA::escape(DateTimeFormat::utc('now - 24 hours')),
250 if (DBA::isResult($r) && count($r) > $maxreq) {
251 notice(L10n::t('%s has received too many connection requests today.', $a->profile['name']) . EOL);
252 notice(L10n::t('Spam protection measures have been invoked.') . EOL);
253 notice(L10n::t('Friends are advised to please try again in 24 hours.') . EOL);
258 /* Cleanup old introductions that remain blocked.
259 * Also remove the contact record, but only if there is no existing relationship
261 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
262 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
263 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
264 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
266 if (DBA::isResult($r)) {
267 foreach ($r as $rr) {
269 DBA::delete('contact', ['id' => $rr['cid'], 'self' => false]);
271 DBA::delete('intro', ['id' => $rr['iid']]);
275 $url = trim($_POST['dfrn_url']);
277 notice(L10n::t("Invalid locator") . EOL);
283 // Detect the network
284 $data = Probe::uri($url);
285 $network = $data["network"];
287 // Canonicalise email-style profile locator
288 $url = Probe::webfingerDfrn($url, $hcard);
290 if (substr($url, 0, 5) === 'stat:') {
291 // Every time we detect the remote subscription we define this as OStatus.
292 // We do this even if it is not OStatus.
293 // we only need to pass this through another section of the code.
294 if ($network != Protocol::DIASPORA) {
295 $network = Protocol::OSTATUS;
298 $url = substr($url, 5);
300 $network = Protocol::DFRN;
303 Logger::log('dfrn_request: url: ' . $url . ',network=' . $network, Logger::DEBUG);
305 if ($network === Protocol::DFRN) {
306 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
311 if (DBA::isResult($ret)) {
312 if (strlen($ret[0]['issued-id'])) {
313 notice(L10n::t('You have already introduced yourself here.') . EOL);
315 } elseif ($ret[0]['rel'] == Contact::FRIEND) {
316 notice(L10n::t('Apparently you are already friends with %s.', $a->profile['name']) . EOL);
319 $contact_record = $ret[0];
320 $parms = ['dfrn-request' => $ret[0]['request']];
324 $issued_id = Strings::getRandomHex();
326 if (is_array($contact_record)) {
327 // There is a contact record but no issued-id, so this
328 // is a reciprocal introduction from a known contact
329 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
330 DBA::escape($issued_id),
331 intval($contact_record['id'])
334 $url = Network::isUrlValid($url);
336 notice(L10n::t('Invalid profile URL.') . EOL);
337 $a->internalRedirect($a->cmd);
338 return; // NOTREACHED
341 if (!Network::isUrlAllowed($url)) {
342 notice(L10n::t('Disallowed profile URL.') . EOL);
343 $a->internalRedirect($a->cmd);
344 return; // NOTREACHED
347 if (Network::isUrlBlocked($url)) {
348 notice(L10n::t('Blocked domain') . EOL);
349 $a->internalRedirect($a->cmd);
350 return; // NOTREACHED
353 $parms = Probe::profile(($hcard) ? $hcard : $url);
355 if (!count($parms)) {
356 notice(L10n::t('Profile location is not valid or does not contain profile information.') . EOL);
357 $a->internalRedirect($a->cmd);
359 if (empty($parms['fn'])) {
360 notice(L10n::t('Warning: profile location has no identifiable owner name.') . EOL);
362 if (empty($parms['photo'])) {
363 notice(L10n::t('Warning: profile location has no profile photo.') . EOL);
365 $invalid = Probe::validDfrn($parms);
367 notice(L10n::tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid) . EOL);
373 $parms['url'] = $url;
374 $parms['issued-id'] = $issued_id;
375 $photo = $parms["photo"];
377 DBA::escapeArray($parms);
378 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
379 `request`, `confirm`, `notify`, `poll`, `network`, `blocked`, `pending` )
380 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
382 DBA::escape(DateTimeFormat::utcNow()),
384 DBA::escape(Strings::normaliseLink($url)),
391 $parms['dfrn-request'],
392 $parms['dfrn-confirm'],
393 $parms['dfrn-notify'],
395 DBA::escape(Protocol::DFRN),
400 // find the contact record we just created
402 $r = q("SELECT `id` FROM `contact`
403 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
408 if (DBA::isResult($r)) {
409 $contact_record = $r[0];
410 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
415 notice(L10n::t('Failed to update contact record.') . EOL);
419 $hash = Strings::getRandomHex() . (string) time(); // Generate a confirm_key
421 if (is_array($contact_record)) {
422 q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
423 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
425 intval($contact_record['id']),
426 intval(!empty($_POST['knowyou'])),
427 DBA::escape(Strings::escapeTags(trim($_POST['dfrn-request-message'] ?? ''))),
429 DBA::escape(DateTimeFormat::utcNow())
433 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
435 info(L10n::t('Your introduction has been sent.') . EOL);
438 // "Homecoming" - send the requestor back to their site to record the introduction.
439 $dfrn_url = bin2hex($a->getBaseURL() . '/profile/' . $nickname);
440 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
442 System::externalRedirect($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
443 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
444 . '&confirm_key=' . $hash
445 . (($aes_allow) ? "&aes_allow=1" : "")
448 // END $network === Protocol::DFRN
449 } elseif (($network != Protocol::PHANTOM) && ($url != "")) {
451 /* Substitute our user's feed URL into $url template
452 * Send the subscriber home to subscribe
454 // Diaspora needs the uri in the format user@domain.tld
455 // Diaspora will support the remote subscription in a future version
456 if ($network == Protocol::DIASPORA) {
457 $uri = $nickname . '@' . $a->getHostName();
459 if ($a->getURLPath()) {
460 $uri .= '/' . $a->getURLPath();
463 $uri = urlencode($uri);
465 $uri = 'profile/' . $nickname;
468 $url = str_replace('{uri}', $uri, $url);
469 System::externalRedirect($url);
471 // END $network != Protocol::PHANTOM
473 notice(L10n::t("Remote subscription can't be done for your network. Please subscribe directly on your system.") . EOL);
479 function dfrn_request_content(App $a)
481 if ($a->argc != 2 || empty($a->profile)) {
485 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
486 // to send us to the post section to record the introduction.
487 if (!empty($_GET['dfrn_url'])) {
489 info(L10n::t("Please login to confirm introduction.") . EOL);
490 /* setup the return URL to come back to this page if they use openid */
491 return Login::form();
494 // Edge case, but can easily happen in the wild. This person is authenticated,
495 // but not as the person who needs to deal with this request.
496 if ($a->user['nickname'] != $a->argv[1]) {
497 notice(L10n::t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
498 return Login::form();
501 $dfrn_url = Strings::escapeTags(trim(hex2bin($_GET['dfrn_url'])));
502 $aes_allow = !empty($_GET['aes_allow']);
503 $confirm_key = $_GET['confirm_key'] ?? '';
505 // Checking fastlane for validity
506 if (!empty($_SESSION['fastlane']) && (Strings::normaliseLink($_SESSION["fastlane"]) == Strings::normaliseLink($dfrn_url))) {
507 $_POST["dfrn_url"] = $dfrn_url;
508 $_POST["confirm_key"] = $confirm_key;
509 $_POST["localconfirm"] = 1;
510 $_POST["hidden-contact"] = 0;
511 $_POST["submit"] = L10n::t('Confirm');
513 dfrn_request_post($a);
518 $tpl = Renderer::getMarkupTemplate("dfrn_req_confirm.tpl");
519 $o = Renderer::replaceMacros($tpl, [
520 '$dfrn_url' => $dfrn_url,
521 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
522 '$hidethem' => L10n::t('Hide this contact'),
523 '$confirm_key' => $confirm_key,
524 '$welcome' => L10n::t('Welcome home %s.', $a->user['username']),
525 '$please' => L10n::t('Please confirm your introduction/connection request to %s.', $dfrn_url),
526 '$submit' => L10n::t('Confirm'),
527 '$uid' => $_SESSION['uid'],
528 '$nickname' => $a->user['nickname'],
529 'dfrn_rawurl' => $_GET['dfrn_url']
532 } elseif (!empty($_GET['confirm_key'])) {
533 // we are the requestee and it is now safe to send our user their introduction,
534 // We could just unblock it, but first we have to jump through a few hoops to
535 // send an email, or even to find out if we need to send an email.
536 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
537 DBA::escape($_GET['confirm_key'])
540 if (DBA::isResult($intro)) {
541 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
542 WHERE `contact`.`id` = %d LIMIT 1",
543 intval($intro[0]['contact-id'])
546 $auto_confirm = false;
548 if (DBA::isResult($r)) {
549 if ($r[0]['page-flags'] != User::PAGE_FLAGS_NORMAL && $r[0]['page-flags'] != User::PAGE_FLAGS_PRVGROUP) {
550 $auto_confirm = true;
553 if (!$auto_confirm) {
555 'type' => NOTIFY_INTRO,
556 'notify_flags' => $r[0]['notify-flags'],
557 'language' => $r[0]['language'],
558 'to_name' => $r[0]['username'],
559 'to_email' => $r[0]['email'],
560 'uid' => $r[0]['uid'],
561 'link' => System::baseUrl() . '/notifications/intros',
562 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : L10n::t('[Name Withheld]')),
563 'source_link' => $r[0]['url'],
564 'source_photo' => $r[0]['photo'],
565 'verb' => Activity::REQ_FRIEND,
571 require_once 'mod/dfrn_confirm.php';
573 'uid' => $r[0]['uid'],
574 'node' => $r[0]['nickname'],
575 'dfrn_id' => $r[0]['issued-id'],
576 'intro_id' => $intro[0]['id'],
577 'duplex' => (($r[0]['page-flags'] == User::PAGE_FLAGS_FREELOVE) ? 1 : 0),
579 dfrn_confirm_post($a, $handsfree);
583 if (!$auto_confirm) {
585 // If we are auto_confirming, this record will have already been nuked
586 // in dfrn_confirm_post()
588 q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
589 DBA::escape($_GET['confirm_key'])
596 // Normal web request. Display our user's introduction form.
597 if (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
598 if (!Config::get('system', 'local_block')) {
599 notice(L10n::t('Public access denied.') . EOL);
604 // Try to auto-fill the profile address
605 // At first look if an address was provided
606 // Otherwise take the local address
607 if (!empty($_GET['addr'])) {
608 $myaddr = hex2bin($_GET['addr']);
609 } elseif (!empty($_GET['address'])) {
610 $myaddr = $_GET['address'];
611 } elseif (local_user()) {
612 if (strlen($a->getURLPath())) {
613 $myaddr = System::baseUrl() . '/profile/' . $a->user['nickname'];
615 $myaddr = $a->user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
619 $myaddr = Profile::getMyURL();
622 $target_addr = $a->profile['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
624 /* The auto_request form only has the profile address
625 * because nobody is going to read the comments and
626 * it doesn't matter if they know you or not.
628 if ($a->profile['page-flags'] == User::PAGE_FLAGS_NORMAL) {
629 $tpl = Renderer::getMarkupTemplate('dfrn_request.tpl');
631 $tpl = Renderer::getMarkupTemplate('auto_request.tpl');
634 $page_desc = L10n::t("Please enter your 'Identity Address' from one of the following supported communications networks:");
636 $invite_desc = 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 site and join us today</a>.', get_server() . '/servers');
638 $o = Renderer::replaceMacros($tpl, [
639 '$header' => L10n::t('Friend/Connection Request'),
640 '$desc' => L10n::t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
641 '$pls_answer' => L10n::t('Please answer the following:'),
642 '$does_know_you' => ['knowyou', L10n::t('Does %s know you?', $a->profile['name']), false, '', [L10n::t('No'), L10n::t('Yes')]],
643 '$add_note' => L10n::t('Add a personal note:'),
644 '$page_desc' => $page_desc,
645 '$friendica' => L10n::t('Friendica'),
646 '$statusnet' => L10n::t("GNU Social \x28Pleroma, Mastodon\x29"),
647 '$diaspora' => L10n::t("Diaspora \x28Socialhome, Hubzilla\x29"),
648 '$diasnote' => L10n::t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.', $target_addr),
649 '$your_address' => L10n::t('Your Identity Address:'),
650 '$invite_desc' => $invite_desc,
651 '$submit' => L10n::t('Submit Request'),
652 '$cancel' => L10n::t('Cancel'),
653 '$nickname' => $a->argv[1],
654 '$name' => $a->profile['name'],