4 * @file mod/dfrn_request.php
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\Search;
22 use Friendica\Core\System;
23 use Friendica\Core\Session;
24 use Friendica\Database\DBA;
26 use Friendica\Model\Contact;
27 use Friendica\Model\Group;
28 use Friendica\Model\Profile;
29 use Friendica\Model\User;
30 use Friendica\Module\Security\Login;
31 use Friendica\Network\Probe;
32 use Friendica\Protocol\Activity;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Network;
35 use Friendica\Util\Strings;
37 function dfrn_request_init(App $a)
41 Profile::load($a, $which);
48 * Function: dfrn_request_post
51 * Handles multiple scenarios.
54 * Clicking 'submit' on a friend request page.
57 * Following Scenario 1, we are brought back to our home site
58 * in order to link our friend request with our own server cell.
59 * After logging in, we click 'submit' to approve the linkage.
62 * @throws ImagickException
63 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
65 function dfrn_request_post(App $a)
67 if (($a->argc != 2) || (!count($a->profile))) {
68 Logger::log('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
72 if (!empty($_POST['cancel'])) {
73 DI::baseUrl()->redirect();
77 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
78 * to confirm the request, and then we've clicked submit (perhaps after logging in).
79 * That brings us here:
81 if (!empty($_POST['localconfirm']) && ($_POST['localconfirm'] == 1)) {
82 // Ensure this is a valid request
83 if (local_user() && ($a->user['nickname'] == $a->argv[1]) && !empty($_POST['dfrn_url'])) {
84 $dfrn_url = Strings::escapeTags(trim($_POST['dfrn_url']));
85 $aes_allow = !empty($_POST['aes_allow']);
86 $confirm_key = $_POST['confirm_key'] ?? '';
87 $hidden = (!empty($_POST['hidden-contact']) ? intval($_POST['hidden-contact']) : 0);
88 $contact_record = null;
92 if (!empty($dfrn_url)) {
93 // Lookup the contact based on their URL (which is the only unique thing we have at the moment)
94 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
96 DBA::escape(Strings::normaliseLink($dfrn_url))
99 if (DBA::isResult($r)) {
100 if (strlen($r[0]['dfrn-id'])) {
101 // We don't need to be here. It has already happened.
102 notice(DI::l10n()->t("This introduction has already been accepted.") . EOL);
105 $contact_record = $r[0];
109 if (is_array($contact_record)) {
110 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
113 intval($contact_record['id'])
116 // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
117 $parms = Probe::profile($dfrn_url);
119 if (!count($parms)) {
120 notice(DI::l10n()->t('Profile location is not valid or does not contain profile information.') . EOL);
123 if (empty($parms['fn'])) {
124 notice(DI::l10n()->t('Warning: profile location has no identifiable owner name.') . EOL);
126 if (empty($parms['photo'])) {
127 notice(DI::l10n()->t('Warning: profile location has no profile photo.') . EOL);
129 $invalid = Probe::validDfrn($parms);
131 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) . EOL);
136 $dfrn_request = $parms['dfrn-request'];
138 $photo = $parms["photo"];
140 // Escape the entire array
141 DBA::escapeArray($parms);
143 // Create a contact record on our site for the other person
144 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
145 `request`, `confirm`, `notify`, `poll`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
146 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
147 intval(local_user()),
148 DateTimeFormat::utcNow(),
149 DBA::escape($dfrn_url),
150 DBA::escape(Strings::normaliseLink($dfrn_url)),
156 $parms['dfrn-request'],
157 $parms['dfrn-confirm'],
158 $parms['dfrn-notify'],
160 DBA::escape(Protocol::DFRN),
169 info(DI::l10n()->t("Introduction complete.") . EOL);
172 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
173 intval(local_user()),
174 DBA::escape($dfrn_url),
175 $parms['key'] ?? '' // Potentially missing
177 if (DBA::isResult($r)) {
178 Group::addMember(User::getDefaultGroup(local_user(), $r[0]["network"]), $r[0]['id']);
181 Contact::updateAvatar($photo, local_user(), $r[0]["id"], true);
184 $forward_path = "contact/" . $r[0]['id'];
186 $forward_path = "contact";
189 // Allow the blocked remote notification to complete
190 if (is_array($contact_record)) {
191 $dfrn_request = $contact_record['request'];
194 if (!empty($dfrn_request) && strlen($confirm_key)) {
195 Network::fetchUrl($dfrn_request . '?confirm_key=' . $confirm_key);
198 // (ignore reply, nothing we can do it failed)
199 DI::baseUrl()->redirect($forward_path);
200 return; // NOTREACHED
204 // invalid/bogus request
205 notice(DI::l10n()->t('Unrecoverable protocol error.') . EOL);
206 DI::baseUrl()->redirect();
207 return; // NOTREACHED
214 * We are the requestee. A person from a remote cell has made an introduction
215 * on our profile web page and clicked submit. We will use their DFRN-URL to
216 * figure out how to contact their cell.
218 * Scrape the originating DFRN-URL for everything we need. Create a contact record
219 * and an introduction to show our user next time he/she logs in.
220 * Finally redirect back to the requestor so that their site can record the request.
221 * If our user (the requestee) later confirms this request, a record of it will need
222 * to exist on the requestor's cell in order for the confirmation process to complete..
224 * It's possible that neither the requestor or the requestee are logged in at the moment,
225 * and the requestor does not yet have any credentials to the requestee profile.
227 * Who is the requestee? We've already loaded their profile which means their nickname should be
228 * in $a->argv[1] and we should have their complete info in $a->profile.
231 if (!(is_array($a->profile) && count($a->profile))) {
232 notice(DI::l10n()->t('Profile unavailable.') . EOL);
236 $nickname = $a->profile['nickname'];
237 $uid = $a->profile['uid'];
238 $maxreq = intval($a->profile['maxreq']);
239 $contact_record = null;
245 if (!empty($_POST['dfrn_url'])) {
246 // Block friend request spam
248 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
249 DBA::escape(DateTimeFormat::utc('now - 24 hours')),
252 if (DBA::isResult($r) && count($r) > $maxreq) {
253 notice(DI::l10n()->t('%s has received too many connection requests today.', $a->profile['name']) . EOL);
254 notice(DI::l10n()->t('Spam protection measures have been invoked.') . EOL);
255 notice(DI::l10n()->t('Friends are advised to please try again in 24 hours.') . EOL);
260 /* Cleanup old introductions that remain blocked.
261 * Also remove the contact record, but only if there is no existing relationship
263 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
264 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
265 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
266 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
268 if (DBA::isResult($r)) {
269 foreach ($r as $rr) {
271 DBA::delete('contact', ['id' => $rr['cid'], 'self' => false]);
273 DBA::delete('intro', ['id' => $rr['iid']]);
277 $url = trim($_POST['dfrn_url']);
279 notice(DI::l10n()->t("Invalid locator") . EOL);
285 // Detect the network
286 $data = Probe::uri($url);
287 $network = $data["network"];
289 // Canonicalise email-style profile locator
290 $url = Probe::webfingerDfrn($url, $hcard);
292 if (substr($url, 0, 5) === 'stat:') {
293 // Every time we detect the remote subscription we define this as OStatus.
294 // We do this even if it is not OStatus.
295 // we only need to pass this through another section of the code.
296 if ($network != Protocol::DIASPORA) {
297 $network = Protocol::OSTATUS;
300 $url = substr($url, 5);
302 $network = Protocol::DFRN;
305 Logger::log('dfrn_request: url: ' . $url . ',network=' . $network, Logger::DEBUG);
307 if ($network === Protocol::DFRN) {
308 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
313 if (DBA::isResult($ret)) {
314 if (strlen($ret[0]['issued-id'])) {
315 notice(DI::l10n()->t('You have already introduced yourself here.') . EOL);
317 } elseif ($ret[0]['rel'] == Contact::FRIEND) {
318 notice(DI::l10n()->t('Apparently you are already friends with %s.', $a->profile['name']) . EOL);
321 $contact_record = $ret[0];
322 $parms = ['dfrn-request' => $ret[0]['request']];
326 $issued_id = Strings::getRandomHex();
328 if (is_array($contact_record)) {
329 // There is a contact record but no issued-id, so this
330 // is a reciprocal introduction from a known contact
331 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
332 DBA::escape($issued_id),
333 intval($contact_record['id'])
336 $url = Network::isUrlValid($url);
338 notice(DI::l10n()->t('Invalid profile URL.') . EOL);
339 DI::baseUrl()->redirect(DI::args()->getCommand());
340 return; // NOTREACHED
343 if (!Network::isUrlAllowed($url)) {
344 notice(DI::l10n()->t('Disallowed profile URL.') . EOL);
345 DI::baseUrl()->redirect(DI::args()->getCommand());
346 return; // NOTREACHED
349 if (Network::isUrlBlocked($url)) {
350 notice(DI::l10n()->t('Blocked domain') . EOL);
351 DI::baseUrl()->redirect(DI::args()->getCommand());
352 return; // NOTREACHED
355 $parms = Probe::profile(($hcard) ? $hcard : $url);
357 if (!count($parms)) {
358 notice(DI::l10n()->t('Profile location is not valid or does not contain profile information.') . EOL);
359 DI::baseUrl()->redirect(DI::args()->getCommand());
361 if (empty($parms['fn'])) {
362 notice(DI::l10n()->t('Warning: profile location has no identifiable owner name.') . EOL);
364 if (empty($parms['photo'])) {
365 notice(DI::l10n()->t('Warning: profile location has no profile photo.') . EOL);
367 $invalid = Probe::validDfrn($parms);
369 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) . EOL);
375 $parms['url'] = $url;
376 $parms['issued-id'] = $issued_id;
377 $photo = $parms["photo"];
379 DBA::escapeArray($parms);
380 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
381 `request`, `confirm`, `notify`, `poll`, `network`, `blocked`, `pending` )
382 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
384 DBA::escape(DateTimeFormat::utcNow()),
386 DBA::escape(Strings::normaliseLink($url)),
393 $parms['dfrn-request'],
394 $parms['dfrn-confirm'],
395 $parms['dfrn-notify'],
397 DBA::escape(Protocol::DFRN),
402 // find the contact record we just created
404 $r = q("SELECT `id` FROM `contact`
405 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
410 if (DBA::isResult($r)) {
411 $contact_record = $r[0];
412 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
417 notice(DI::l10n()->t('Failed to update contact record.') . EOL);
421 $hash = Strings::getRandomHex() . (string) time(); // Generate a confirm_key
423 if (is_array($contact_record)) {
424 q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
425 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
427 intval($contact_record['id']),
428 intval(!empty($_POST['knowyou'])),
429 DBA::escape(Strings::escapeTags(trim($_POST['dfrn-request-message'] ?? ''))),
431 DBA::escape(DateTimeFormat::utcNow())
435 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
437 info(DI::l10n()->t('Your introduction has been sent.') . EOL);
440 // "Homecoming" - send the requestor back to their site to record the introduction.
441 $dfrn_url = bin2hex(DI::baseUrl()->get() . '/profile/' . $nickname);
442 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
444 System::externalRedirect($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
445 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
446 . '&confirm_key=' . $hash
447 . (($aes_allow) ? "&aes_allow=1" : "")
450 // END $network === Protocol::DFRN
451 } elseif (($network != Protocol::PHANTOM) && ($url != "")) {
453 /* Substitute our user's feed URL into $url template
454 * Send the subscriber home to subscribe
456 // Diaspora needs the uri in the format user@domain.tld
457 // Diaspora will support the remote subscription in a future version
458 if ($network == Protocol::DIASPORA) {
459 $uri = $nickname . '@' . DI::baseUrl()->getHostname();
461 if (DI::baseUrl()->getUrlPath()) {
462 $uri .= '/' . DI::baseUrl()->getUrlPath();
465 $uri = urlencode($uri);
467 $uri = 'profile/' . $nickname;
470 $url = str_replace('{uri}', $uri, $url);
471 System::externalRedirect($url);
473 // END $network != Protocol::PHANTOM
475 notice(DI::l10n()->t("Remote subscription can't be done for your network. Please subscribe directly on your system.") . EOL);
481 function dfrn_request_content(App $a)
483 if ($a->argc != 2 || empty($a->profile)) {
487 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
488 // to send us to the post section to record the introduction.
489 if (!empty($_GET['dfrn_url'])) {
491 info(DI::l10n()->t("Please login to confirm introduction.") . EOL);
492 /* setup the return URL to come back to this page if they use openid */
493 return Login::form();
496 // Edge case, but can easily happen in the wild. This person is authenticated,
497 // but not as the person who needs to deal with this request.
498 if ($a->user['nickname'] != $a->argv[1]) {
499 notice(DI::l10n()->t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
500 return Login::form();
503 $dfrn_url = Strings::escapeTags(trim(hex2bin($_GET['dfrn_url'])));
504 $aes_allow = !empty($_GET['aes_allow']);
505 $confirm_key = $_GET['confirm_key'] ?? '';
507 // Checking fastlane for validity
508 if (!empty($_SESSION['fastlane']) && (Strings::normaliseLink($_SESSION["fastlane"]) == Strings::normaliseLink($dfrn_url))) {
509 $_POST["dfrn_url"] = $dfrn_url;
510 $_POST["confirm_key"] = $confirm_key;
511 $_POST["localconfirm"] = 1;
512 $_POST["hidden-contact"] = 0;
513 $_POST["submit"] = DI::l10n()->t('Confirm');
515 dfrn_request_post($a);
520 $tpl = Renderer::getMarkupTemplate("dfrn_req_confirm.tpl");
521 $o = Renderer::replaceMacros($tpl, [
522 '$dfrn_url' => $dfrn_url,
523 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
524 '$hidethem' => DI::l10n()->t('Hide this contact'),
525 '$confirm_key' => $confirm_key,
526 '$welcome' => DI::l10n()->t('Welcome home %s.', $a->user['username']),
527 '$please' => DI::l10n()->t('Please confirm your introduction/connection request to %s.', $dfrn_url),
528 '$submit' => DI::l10n()->t('Confirm'),
529 '$uid' => $_SESSION['uid'],
530 '$nickname' => $a->user['nickname'],
531 'dfrn_rawurl' => $_GET['dfrn_url']
534 } elseif (!empty($_GET['confirm_key'])) {
535 // we are the requestee and it is now safe to send our user their introduction,
536 // We could just unblock it, but first we have to jump through a few hoops to
537 // send an email, or even to find out if we need to send an email.
538 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
539 DBA::escape($_GET['confirm_key'])
542 if (DBA::isResult($intro)) {
543 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
544 WHERE `contact`.`id` = %d LIMIT 1",
545 intval($intro[0]['contact-id'])
548 $auto_confirm = false;
550 if (DBA::isResult($r)) {
551 if ($r[0]['page-flags'] != User::PAGE_FLAGS_NORMAL && $r[0]['page-flags'] != User::PAGE_FLAGS_PRVGROUP) {
552 $auto_confirm = true;
555 if (!$auto_confirm) {
557 'type' => NOTIFY_INTRO,
558 'notify_flags' => $r[0]['notify-flags'],
559 'language' => $r[0]['language'],
560 'to_name' => $r[0]['username'],
561 'to_email' => $r[0]['email'],
562 'uid' => $r[0]['uid'],
563 'link' => DI::baseUrl() . '/notifications/intros',
564 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : DI::l10n()->t('[Name Withheld]')),
565 'source_link' => $r[0]['url'],
566 'source_photo' => $r[0]['photo'],
567 'verb' => Activity::REQ_FRIEND,
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 (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
600 if (!Config::get('system', 'local_block')) {
601 notice(DI::l10n()->t('Public access denied.') . EOL);
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 $page_desc = DI::l10n()->t("Please enter your 'Identity Address' from one of the following supported communications networks:");
638 $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 site and join us today</a>.', Search::getGlobalDirectory() . '/servers');
640 $o = Renderer::replaceMacros($tpl, [
641 '$header' => DI::l10n()->t('Friend/Connection Request'),
642 '$desc' => DI::l10n()->t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
643 '$pls_answer' => DI::l10n()->t('Please answer the following:'),
644 '$does_know_you' => ['knowyou', DI::l10n()->t('Does %s know you?', $a->profile['name']), false, '', [DI::l10n()->t('No'), DI::l10n()->t('Yes')]],
645 '$add_note' => DI::l10n()->t('Add a personal note:'),
646 '$page_desc' => $page_desc,
647 '$friendica' => DI::l10n()->t('Friendica'),
648 '$statusnet' => DI::l10n()->t("GNU Social \x28Pleroma, Mastodon\x29"),
649 '$diaspora' => DI::l10n()->t("Diaspora \x28Socialhome, Hubzilla\x29"),
650 '$diasnote' => DI::l10n()->t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.', $target_addr),
651 '$your_address' => DI::l10n()->t('Your Identity Address:'),
652 '$invite_desc' => $invite_desc,
653 '$submit' => DI::l10n()->t('Submit Request'),
654 '$cancel' => DI::l10n()->t('Cancel'),
655 '$nickname' => $a->argv[1],
656 '$name' => $a->profile['name'],