3 * @copyright Copyright (C) 2010-2021, the Friendica project
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\Notification;
39 use Friendica\Model\Profile;
40 use Friendica\Model\User;
41 use Friendica\Module\Security\Login;
42 use Friendica\Network\Probe;
43 use Friendica\Protocol\Activity;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Network;
46 use Friendica\Util\Strings;
48 function dfrn_request_init(App $a)
52 Profile::load($a, $which);
59 * Function: dfrn_request_post
62 * Handles multiple scenarios.
65 * Clicking 'submit' on a friend request page.
68 * Following Scenario 1, we are brought back to our home site
69 * in order to link our friend request with our own server cell.
70 * After logging in, we click 'submit' to approve the linkage.
73 * @throws ImagickException
74 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
76 function dfrn_request_post(App $a)
78 if ($a->argc != 2 || empty($a->profile)) {
79 Logger::log('Wrong count of argc or profiles: argc=' . $a->argc . ', profile()=' . count($a->profile ?? []));
83 if (!empty($_POST['cancel'])) {
84 DI::baseUrl()->redirect();
88 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
89 * to confirm the request, and then we've clicked submit (perhaps after logging in).
90 * That brings us here:
92 if (!empty($_POST['localconfirm']) && ($_POST['localconfirm'] == 1)) {
93 // Ensure this is a valid request
94 if (local_user() && ($a->user['nickname'] == $a->argv[1]) && !empty($_POST['dfrn_url'])) {
95 $dfrn_url = Strings::escapeTags(trim($_POST['dfrn_url']));
96 $aes_allow = !empty($_POST['aes_allow']);
97 $confirm_key = $_POST['confirm_key'] ?? '';
98 $hidden = (!empty($_POST['hidden-contact']) ? intval($_POST['hidden-contact']) : 0);
99 $contact_record = null;
103 if (!empty($dfrn_url)) {
104 // Lookup the contact based on their URL (which is the only unique thing we have at the moment)
105 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
106 intval(local_user()),
107 DBA::escape(Strings::normaliseLink($dfrn_url))
110 if (DBA::isResult($r)) {
111 if (strlen($r[0]['dfrn-id'])) {
112 // We don't need to be here. It has already happened.
113 notice(DI::l10n()->t("This introduction has already been accepted."));
116 $contact_record = $r[0];
120 if (is_array($contact_record)) {
121 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
124 intval($contact_record['id'])
127 // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
128 $parms = Probe::profile($dfrn_url);
130 if (!count($parms)) {
131 notice(DI::l10n()->t('Profile location is not valid or does not contain profile information.'));
134 if (empty($parms['fn'])) {
135 notice(DI::l10n()->t('Warning: profile location has no identifiable owner name.'));
137 if (empty($parms['photo'])) {
138 notice(DI::l10n()->t('Warning: profile location has no profile photo.'));
140 $invalid = Probe::validDfrn($parms);
142 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));
147 $dfrn_request = $parms['dfrn-request'];
149 $photo = $parms["photo"];
151 // Escape the entire array
152 DBA::escapeArray($parms);
154 // Create a contact record on our site for the other person
155 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
156 `request`, `confirm`, `notify`, `poll`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
157 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
158 intval(local_user()),
159 DateTimeFormat::utcNow(),
160 DBA::escape($dfrn_url),
161 DBA::escape(Strings::normaliseLink($dfrn_url)),
167 $parms['dfrn-request'],
168 $parms['dfrn-confirm'],
169 $parms['dfrn-notify'],
171 DBA::escape(Protocol::DFRN),
180 info(DI::l10n()->t("Introduction complete."));
183 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
184 intval(local_user()),
185 DBA::escape($dfrn_url),
186 $parms['key'] ?? '' // Potentially missing
188 if (DBA::isResult($r)) {
189 Group::addMember(User::getDefaultGroup(local_user(), $r[0]["network"]), $r[0]['id']);
192 Contact::updateAvatar($r[0]["id"], $photo, true);
195 $forward_path = "contact/" . $r[0]['id'];
197 $forward_path = "contact";
200 // Allow the blocked remote notification to complete
201 if (is_array($contact_record)) {
202 $dfrn_request = $contact_record['request'];
205 if (!empty($dfrn_request) && strlen($confirm_key)) {
206 DI::httpRequest()->fetch($dfrn_request . '?confirm_key=' . $confirm_key);
209 // (ignore reply, nothing we can do it failed)
210 DI::baseUrl()->redirect($forward_path);
211 return; // NOTREACHED
215 // invalid/bogus request
216 notice(DI::l10n()->t('Unrecoverable protocol error.'));
217 DI::baseUrl()->redirect();
218 return; // NOTREACHED
225 * We are the requestee. A person from a remote cell has made an introduction
226 * on our profile web page and clicked submit. We will use their DFRN-URL to
227 * figure out how to contact their cell.
229 * Scrape the originating DFRN-URL for everything we need. Create a contact record
230 * and an introduction to show our user next time he/she logs in.
231 * Finally redirect back to the requestor so that their site can record the request.
232 * If our user (the requestee) later confirms this request, a record of it will need
233 * to exist on the requestor's cell in order for the confirmation process to complete..
235 * It's possible that neither the requestor or the requestee are logged in at the moment,
236 * and the requestor does not yet have any credentials to the requestee profile.
238 * Who is the requestee? We've already loaded their profile which means their nickname should be
239 * in $a->argv[1] and we should have their complete info in $a->profile.
242 if (empty($a->profile['uid'])) {
243 notice(DI::l10n()->t('Profile unavailable.'));
247 $nickname = $a->profile['nickname'];
248 $uid = $a->profile['uid'];
249 $maxreq = intval($a->profile['maxreq']);
250 $contact_record = null;
256 if (!empty($_POST['dfrn_url'])) {
257 // Block friend request spam
259 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
260 DBA::escape(DateTimeFormat::utc('now - 24 hours')),
263 if (DBA::isResult($r) && count($r) > $maxreq) {
264 notice(DI::l10n()->t('%s has received too many connection requests today.', $a->profile['name']));
265 notice(DI::l10n()->t('Spam protection measures have been invoked.'));
266 notice(DI::l10n()->t('Friends are advised to please try again in 24 hours.'));
271 /* Cleanup old introductions that remain blocked.
272 * Also remove the contact record, but only if there is no existing relationship
274 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
275 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
276 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
277 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
279 if (DBA::isResult($r)) {
280 foreach ($r as $rr) {
282 DBA::delete('contact', ['id' => $rr['cid'], 'self' => false]);
284 DBA::delete('intro', ['id' => $rr['iid']]);
288 $url = trim($_POST['dfrn_url']);
290 notice(DI::l10n()->t("Invalid locator"));
296 // Detect the network
297 $data = Contact::getByURL($url);
298 $network = $data["network"];
300 // Canonicalize email-style profile locator
301 $url = Probe::webfingerDfrn($data['url'] ?? $url, $hcard);
303 if (substr($url, 0, 5) === 'stat:') {
304 // Every time we detect the remote subscription we define this as OStatus.
305 // We do this even if it is not OStatus.
306 // we only need to pass this through another section of the code.
307 if ($network != Protocol::DIASPORA) {
308 $network = Protocol::OSTATUS;
311 $url = substr($url, 5);
313 $network = Protocol::DFRN;
316 Logger::log('dfrn_request: url: ' . $url . ',network=' . $network, Logger::DEBUG);
318 if ($network === Protocol::DFRN) {
319 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
324 if (DBA::isResult($ret)) {
325 if (strlen($ret[0]['issued-id'])) {
326 notice(DI::l10n()->t('You have already introduced yourself here.'));
328 } elseif ($ret[0]['rel'] == Contact::FRIEND) {
329 notice(DI::l10n()->t('Apparently you are already friends with %s.', $a->profile['name']));
332 $contact_record = $ret[0];
333 $parms = ['dfrn-request' => $ret[0]['request']];
337 $issued_id = Strings::getRandomHex();
339 if (is_array($contact_record)) {
340 // There is a contact record but no issued-id, so this
341 // is a reciprocal introduction from a known contact
342 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
343 DBA::escape($issued_id),
344 intval($contact_record['id'])
347 $url = Network::isUrlValid($url);
349 notice(DI::l10n()->t('Invalid profile URL.'));
350 DI::baseUrl()->redirect(DI::args()->getCommand());
351 return; // NOTREACHED
354 if (!Network::isUrlAllowed($url)) {
355 notice(DI::l10n()->t('Disallowed profile URL.'));
356 DI::baseUrl()->redirect(DI::args()->getCommand());
357 return; // NOTREACHED
360 if (Network::isUrlBlocked($url)) {
361 notice(DI::l10n()->t('Blocked domain'));
362 DI::baseUrl()->redirect(DI::args()->getCommand());
363 return; // NOTREACHED
366 $parms = Probe::profile(($hcard) ? $hcard : $url);
368 if (!count($parms)) {
369 notice(DI::l10n()->t('Profile location is not valid or does not contain profile information.'));
370 DI::baseUrl()->redirect(DI::args()->getCommand());
372 if (empty($parms['fn'])) {
373 notice(DI::l10n()->t('Warning: profile location has no identifiable owner name.'));
375 if (empty($parms['photo'])) {
376 notice(DI::l10n()->t('Warning: profile location has no profile photo.'));
378 $invalid = Probe::validDfrn($parms);
380 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));
386 $parms['url'] = $url;
387 $parms['issued-id'] = $issued_id;
388 $photo = $parms["photo"];
390 DBA::escapeArray($parms);
391 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
392 `request`, `confirm`, `notify`, `poll`, `network`, `blocked`, `pending` )
393 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
395 DBA::escape(DateTimeFormat::utcNow()),
397 DBA::escape(Strings::normaliseLink($url)),
404 $parms['dfrn-request'],
405 $parms['dfrn-confirm'],
406 $parms['dfrn-notify'],
408 DBA::escape(Protocol::DFRN),
413 // find the contact record we just created
415 $r = q("SELECT `id` FROM `contact`
416 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
421 if (DBA::isResult($r)) {
422 $contact_record = $r[0];
423 Contact::updateAvatar($contact_record["id"], $photo, true);
428 notice(DI::l10n()->t('Failed to update contact record.'));
432 $hash = Strings::getRandomHex() . (string) time(); // Generate a confirm_key
434 if (is_array($contact_record)) {
435 q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
436 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
438 intval($contact_record['id']),
439 intval(!empty($_POST['knowyou'])),
440 DBA::escape(Strings::escapeTags(trim($_POST['dfrn-request-message'] ?? ''))),
442 DBA::escape(DateTimeFormat::utcNow())
446 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
448 info(DI::l10n()->t('Your introduction has been sent.'));
451 // "Homecoming" - send the requestor back to their site to record the introduction.
452 $dfrn_url = bin2hex(DI::baseUrl()->get() . '/profile/' . $nickname);
453 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
455 System::externalRedirect($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
456 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
457 . '&confirm_key=' . $hash
458 . (($aes_allow) ? "&aes_allow=1" : "")
461 // END $network === Protocol::DFRN
462 } elseif (($network != Protocol::PHANTOM) && ($url != "")) {
464 /* Substitute our user's feed URL into $url template
465 * Send the subscriber home to subscribe
467 // Diaspora needs the uri in the format user@domain.tld
468 // Diaspora will support the remote subscription in a future version
469 if ($network == Protocol::DIASPORA) {
470 $uri = urlencode($a->profile['addr']);
472 $uri = urlencode($a->profile['url']);
475 $url = str_replace('{uri}', $uri, $url);
476 System::externalRedirect($url);
478 // END $network != Protocol::PHANTOM
480 notice(DI::l10n()->t("Remote subscription can't be done for your network. Please subscribe directly on your system."));
486 function dfrn_request_content(App $a)
488 if ($a->argc != 2 || empty($a->profile)) {
492 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
493 // to send us to the post section to record the introduction.
494 if (!empty($_GET['dfrn_url'])) {
496 info(DI::l10n()->t("Please login to confirm introduction."));
497 /* setup the return URL to come back to this page if they use openid */
498 return Login::form();
501 // Edge case, but can easily happen in the wild. This person is authenticated,
502 // but not as the person who needs to deal with this request.
503 if ($a->user['nickname'] != $a->argv[1]) {
504 notice(DI::l10n()->t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile."));
505 return Login::form();
508 $dfrn_url = Strings::escapeTags(trim(hex2bin($_GET['dfrn_url'])));
509 $aes_allow = !empty($_GET['aes_allow']);
510 $confirm_key = $_GET['confirm_key'] ?? '';
512 // Checking fastlane for validity
513 if (!empty($_SESSION['fastlane']) && (Strings::normaliseLink($_SESSION["fastlane"]) == Strings::normaliseLink($dfrn_url))) {
514 $_POST["dfrn_url"] = $dfrn_url;
515 $_POST["confirm_key"] = $confirm_key;
516 $_POST["localconfirm"] = 1;
517 $_POST["hidden-contact"] = 0;
518 $_POST["submit"] = DI::l10n()->t('Confirm');
520 dfrn_request_post($a);
525 $tpl = Renderer::getMarkupTemplate("dfrn_req_confirm.tpl");
526 $o = Renderer::replaceMacros($tpl, [
527 '$dfrn_url' => $dfrn_url,
528 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
529 '$hidethem' => DI::l10n()->t('Hide this contact'),
530 '$confirm_key' => $confirm_key,
531 '$welcome' => DI::l10n()->t('Welcome home %s.', $a->user['username']),
532 '$please' => DI::l10n()->t('Please confirm your introduction/connection request to %s.', $dfrn_url),
533 '$submit' => DI::l10n()->t('Confirm'),
534 '$uid' => $_SESSION['uid'],
535 '$nickname' => $a->user['nickname'],
536 'dfrn_rawurl' => $_GET['dfrn_url']
539 } elseif (!empty($_GET['confirm_key'])) {
540 // we are the requestee and it is now safe to send our user their introduction,
541 // We could just unblock it, but first we have to jump through a few hoops to
542 // send an email, or even to find out if we need to send an email.
543 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
544 DBA::escape($_GET['confirm_key'])
547 if (DBA::isResult($intro)) {
548 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
549 WHERE `contact`.`id` = %d LIMIT 1",
550 intval($intro[0]['contact-id'])
553 $auto_confirm = false;
555 if (DBA::isResult($r)) {
556 if ($r[0]['page-flags'] != User::PAGE_FLAGS_NORMAL && $r[0]['page-flags'] != User::PAGE_FLAGS_PRVGROUP) {
557 $auto_confirm = true;
560 if (!$auto_confirm) {
562 'type' => Notification\Type::INTRO,
563 'otype' => Notification\ObjectType::INTRO,
564 'verb' => Activity::REQ_FRIEND,
565 'uid' => $r[0]['uid'],
566 'cid' => $r[0]['id'],
567 'link' => DI::baseUrl() . '/notifications/intros',
572 require_once 'mod/dfrn_confirm.php';
574 'uid' => $r[0]['uid'],
575 'node' => $r[0]['nickname'],
576 'dfrn_id' => $r[0]['issued-id'],
577 'intro_id' => $intro[0]['id'],
578 'duplex' => (($r[0]['page-flags'] == User::PAGE_FLAGS_FREELOVE) ? 1 : 0),
580 dfrn_confirm_post($a, $handsfree);
584 if (!$auto_confirm) {
586 // If we are auto_confirming, this record will have already been nuked
587 // in dfrn_confirm_post()
589 q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
590 DBA::escape($_GET['confirm_key'])
597 // Normal web request. Display our user's introduction form.
598 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
599 if (!DI::config()->get('system', 'local_block')) {
600 notice(DI::l10n()->t('Public access denied.'));
605 // Try to auto-fill the profile address
606 // At first look if an address was provided
607 // Otherwise take the local address
608 if (!empty($_GET['addr'])) {
609 $myaddr = hex2bin($_GET['addr']);
610 } elseif (!empty($_GET['address'])) {
611 $myaddr = $_GET['address'];
612 } elseif (local_user()) {
613 if (strlen(DI::baseUrl()->getUrlPath())) {
614 $myaddr = DI::baseUrl() . '/profile/' . $a->user['nickname'];
616 $myaddr = $a->user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
620 $myaddr = Profile::getMyURL();
623 $target_addr = $a->profile['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
625 /* The auto_request form only has the profile address
626 * because nobody is going to read the comments and
627 * it doesn't matter if they know you or not.
629 if ($a->profile['page-flags'] == User::PAGE_FLAGS_NORMAL) {
630 $tpl = Renderer::getMarkupTemplate('dfrn_request.tpl');
632 $tpl = Renderer::getMarkupTemplate('auto_request.tpl');
635 $o = Renderer::replaceMacros($tpl, [
636 '$header' => DI::l10n()->t('Friend/Connection Request'),
637 '$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),
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 node and join us today</a>.', Search::getGlobalDirectory() . '/servers'),
639 '$your_address' => DI::l10n()->t('Your Webfinger address or profile URL:'),
640 '$pls_answer' => DI::l10n()->t('Please answer the following:'),
641 '$submit' => DI::l10n()->t('Submit Request'),
642 '$cancel' => DI::l10n()->t('Cancel'),
644 '$request' => 'dfrn_request/' . $a->argv[1],
645 '$name' => $a->profile['name'],
646 '$myaddr' => $myaddr,
648 '$does_know_you' => ['knowyou', DI::l10n()->t('%s knows you', $a->profile['name'])],
649 '$addnote_field' => ['dfrn-request-message', DI::l10n()->t('Add a personal note:')],