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\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Profile;
23 use Friendica\Model\User;
24 use Friendica\Module\Login;
25 use Friendica\Network\Probe;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
29 require_once 'include/enotify.php';
31 function dfrn_request_init(App $a)
37 Profile::load($a, $which);
42 * Function: dfrn_request_post
45 * Handles multiple scenarios.
48 * Clicking 'submit' on a friend request page.
51 * Following Scenario 1, we are brought back to our home site
52 * in order to link our friend request with our own server cell.
53 * After logging in, we click 'submit' to approve the linkage.
56 function dfrn_request_post(App $a)
58 if (($a->argc != 2) || (!count($a->profile))) {
59 logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
63 if (x($_POST, 'cancel')) {
64 goaway(System::baseUrl());
68 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
69 * to confirm the request, and then we've clicked submit (perhaps after logging in).
70 * That brings us here:
72 if ((x($_POST, 'localconfirm')) && ($_POST['localconfirm'] == 1)) {
73 // Ensure this is a valid request
74 if (local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST, 'dfrn_url'))) {
75 $dfrn_url = notags(trim($_POST['dfrn_url']));
76 $aes_allow = (((x($_POST, 'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
77 $confirm_key = ((x($_POST, 'confirm_key')) ? $_POST['confirm_key'] : "");
78 $hidden = ((x($_POST, 'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
79 $contact_record = null;
84 // Lookup the contact based on their URL (which is the only unique thing we have at the moment)
85 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
87 dbesc(normalise_link($dfrn_url))
90 if (DBA::is_result($r)) {
91 if (strlen($r[0]['dfrn-id'])) {
92 // We don't need to be here. It has already happened.
93 notice(L10n::t("This introduction has already been accepted.") . EOL);
96 $contact_record = $r[0];
100 if (is_array($contact_record)) {
101 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
104 intval($contact_record['id'])
107 // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
108 $parms = Probe::profile($dfrn_url);
110 if (!count($parms)) {
111 notice(L10n::t('Profile location is not valid or does not contain profile information.') . EOL);
114 if (!x($parms, 'fn')) {
115 notice(L10n::t('Warning: profile location has no identifiable owner name.') . EOL);
117 if (!x($parms, 'photo')) {
118 notice(L10n::t('Warning: profile location has no profile photo.') . EOL);
120 $invalid = Probe::validDfrn($parms);
122 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);
127 $dfrn_request = $parms['dfrn-request'];
129 $photo = $parms["photo"];
131 // Escape the entire array
132 DBA::esc_array($parms);
134 // Create a contact record on our site for the other person
135 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
136 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
137 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
138 intval(local_user()),
139 DateTimeFormat::utcNow(),
141 dbesc(normalise_link($dfrn_url)),
147 $parms['dfrn-request'],
148 $parms['dfrn-confirm'],
149 $parms['dfrn-notify'],
161 info(L10n::t("Introduction complete.") . EOL);
164 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
165 intval(local_user()),
167 $parms['key'] // this was already escaped
169 if (DBA::is_result($r)) {
170 Group::addMember(User::getDefaultGroup(local_user(), $r[0]["network"]), $r[0]['id']);
173 Contact::updateAvatar($photo, local_user(), $r[0]["id"], true);
176 $forwardurl = System::baseUrl() . "/contacts/" . $r[0]['id'];
178 $forwardurl = System::baseUrl() . "/contacts";
181 // Allow the blocked remote notification to complete
182 if (is_array($contact_record)) {
183 $dfrn_request = $contact_record['request'];
186 if (strlen($dfrn_request) && strlen($confirm_key)) {
187 $s = Network::fetchUrl($dfrn_request . '?confirm_key=' . $confirm_key);
190 // (ignore reply, nothing we can do it failed)
192 return; // NOTREACHED
196 // invalid/bogus request
197 notice(L10n::t('Unrecoverable protocol error.') . EOL);
198 goaway(System::baseUrl());
199 return; // NOTREACHED
206 * We are the requestee. A person from a remote cell has made an introduction
207 * on our profile web page and clicked submit. We will use their DFRN-URL to
208 * figure out how to contact their cell.
210 * Scrape the originating DFRN-URL for everything we need. Create a contact record
211 * and an introduction to show our user next time he/she logs in.
212 * Finally redirect back to the requestor so that their site can record the request.
213 * If our user (the requestee) later confirms this request, a record of it will need
214 * to exist on the requestor's cell in order for the confirmation process to complete..
216 * It's possible that neither the requestor or the requestee are logged in at the moment,
217 * and the requestor does not yet have any credentials to the requestee profile.
219 * Who is the requestee? We've already loaded their profile which means their nickname should be
220 * in $a->argv[1] and we should have their complete info in $a->profile.
223 if (!(is_array($a->profile) && count($a->profile))) {
224 notice(L10n::t('Profile unavailable.') . EOL);
228 $nickname = $a->profile['nickname'];
229 $notify_flags = $a->profile['notify-flags'];
230 $uid = $a->profile['uid'];
231 $maxreq = intval($a->profile['maxreq']);
232 $contact_record = null;
238 if (x($_POST, 'dfrn_url')) {
239 // Block friend request spam
241 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
242 dbesc(DateTimeFormat::utc('now - 24 hours')),
245 if (DBA::is_result($r) && count($r) > $maxreq) {
246 notice(L10n::t('%s has received too many connection requests today.', $a->profile['name']) . EOL);
247 notice(L10n::t('Spam protection measures have been invoked.') . EOL);
248 notice(L10n::t('Friends are advised to please try again in 24 hours.') . EOL);
253 /* Cleanup old introductions that remain blocked.
254 * Also remove the contact record, but only if there is no existing relationship
256 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
257 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
258 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
259 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
261 if (DBA::is_result($r)) {
262 foreach ($r as $rr) {
264 DBA::delete('contact', ['id' => $rr['cid'], 'self' => false]);
266 DBA::delete('intro', ['id' => $rr['iid']]);
270 $real_name = x($_POST, 'realname') ? notags(trim($_POST['realname'])) : '';
272 $url = trim($_POST['dfrn_url']);
274 notice(L10n::t("Invalid locator") . EOL);
280 // Detect the network
281 $data = Probe::uri($url);
282 $network = $data["network"];
284 // Canonicalise email-style profile locator
285 $url = Probe::webfingerDfrn($url, $hcard);
287 if (substr($url, 0, 5) === 'stat:') {
288 // Every time we detect the remote subscription we define this as OStatus.
289 // We do this even if it is not OStatus.
290 // we only need to pass this through another section of the code.
291 if ($network != NETWORK_DIASPORA) {
292 $network = NETWORK_OSTATUS;
295 $url = substr($url, 5);
297 $network = NETWORK_DFRN;
300 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
302 if ($network === NETWORK_DFRN) {
303 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
308 if (DBA::is_result($ret)) {
309 if (strlen($ret[0]['issued-id'])) {
310 notice(L10n::t('You have already introduced yourself here.') . EOL);
312 } elseif ($ret[0]['rel'] == CONTACT_IS_FRIEND) {
313 notice(L10n::t('Apparently you are already friends with %s.', $a->profile['name']) . EOL);
316 $contact_record = $ret[0];
317 $parms = ['dfrn-request' => $ret[0]['request']];
321 $issued_id = random_string();
323 if (is_array($contact_record)) {
324 // There is a contact record but no issued-id, so this
325 // is a reciprocal introduction from a known contact
326 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
328 intval($contact_record['id'])
331 $url = Network::isUrlValid($url);
333 notice(L10n::t('Invalid profile URL.') . EOL);
334 goaway(System::baseUrl() . '/' . $a->cmd);
335 return; // NOTREACHED
338 if (!Network::isUrlAllowed($url)) {
339 notice(L10n::t('Disallowed profile URL.') . EOL);
340 goaway(System::baseUrl() . '/' . $a->cmd);
341 return; // NOTREACHED
344 if (Network::isUrlBlocked($url)) {
345 notice(L10n::t('Blocked domain') . EOL);
346 goaway(System::baseUrl() . '/' . $a->cmd);
347 return; // NOTREACHED
350 $parms = Probe::profile(($hcard) ? $hcard : $url);
352 if (!count($parms)) {
353 notice(L10n::t('Profile location is not valid or does not contain profile information.') . EOL);
354 goaway(System::baseUrl() . '/' . $a->cmd);
356 if (!x($parms, 'fn')) {
357 notice(L10n::t('Warning: profile location has no identifiable owner name.') . EOL);
359 if (!x($parms, 'photo')) {
360 notice(L10n::t('Warning: profile location has no profile photo.') . EOL);
362 $invalid = Probe::validDfrn($parms);
364 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);
370 $parms['url'] = $url;
371 $parms['issued-id'] = $issued_id;
372 $photo = $parms["photo"];
374 DBA::esc_array($parms);
375 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
376 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `blocked`, `pending` )
377 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
379 dbesc(DateTimeFormat::utcNow()),
381 dbesc(normalise_link($url)),
388 $parms['dfrn-request'],
389 $parms['dfrn-confirm'],
390 $parms['dfrn-notify'],
398 // find the contact record we just created
400 $r = q("SELECT `id` FROM `contact`
401 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
406 if (DBA::is_result($r)) {
407 $contact_record = $r[0];
408 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
413 notice(L10n::t('Failed to update contact record.') . EOL);
417 $hash = random_string() . (string) time(); // Generate a confirm_key
419 if (is_array($contact_record)) {
420 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
421 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
423 intval($contact_record['id']),
424 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
425 dbesc(notags(trim($_POST['dfrn-request-message']))),
427 dbesc(DateTimeFormat::utcNow())
431 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
433 info(L10n::t('Your introduction has been sent.') . EOL);
436 // "Homecoming" - send the requestor back to their site to record the introduction.
437 $dfrn_url = bin2hex(System::baseUrl() . '/profile/' . $nickname);
438 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
440 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
441 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
442 . '&confirm_key=' . $hash
443 . (($aes_allow) ? "&aes_allow=1" : "")
446 // END $network === NETWORK_DFRN
447 } elseif (($network != NETWORK_PHANTOM) && ($url != "")) {
449 /* Substitute our user's feed URL into $url template
450 * Send the subscriber home to subscribe
452 // Diaspora needs the uri in the format user@domain.tld
453 // Diaspora will support the remote subscription in a future version
454 if ($network == NETWORK_DIASPORA) {
455 $uri = $nickname . '@' . $a->get_hostname();
457 if ($a->get_path()) {
458 $uri .= '/' . $a->get_path();
461 $uri = urlencode($uri);
463 $uri = System::baseUrl() . '/profile/' . $nickname;
466 $url = str_replace('{uri}', $uri, $url);
469 // END $network != NETWORK_PHANTOM
471 notice(L10n::t("Remote subscription can't be done for your network. Please subscribe directly on your system.") . EOL);
477 function dfrn_request_content(App $a)
479 if (($a->argc != 2) || (!count($a->profile))) {
483 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
484 // to send us to the post section to record the introduction.
485 if (x($_GET, 'dfrn_url')) {
487 info(L10n::t("Please login to confirm introduction.") . EOL);
488 /* setup the return URL to come back to this page if they use openid */
489 return Login::form();
492 // Edge case, but can easily happen in the wild. This person is authenticated,
493 // but not as the person who needs to deal with this request.
494 if ($a->user['nickname'] != $a->argv[1]) {
495 notice(L10n::t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
496 return Login::form();
499 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
500 $aes_allow = x($_GET, 'aes_allow') && $_GET['aes_allow'] == 1 ? 1 : 0;
501 $confirm_key = x($_GET, 'confirm_key') ? $_GET['confirm_key'] : "";
503 // Checking fastlane for validity
504 if (x($_SESSION, "fastlane") && (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
505 $_POST["dfrn_url"] = $dfrn_url;
506 $_POST["confirm_key"] = $confirm_key;
507 $_POST["localconfirm"] = 1;
508 $_POST["hidden-contact"] = 0;
509 $_POST["submit"] = L10n::t('Confirm');
511 dfrn_request_post($a);
514 return; // NOTREACHED
517 $tpl = get_markup_template("dfrn_req_confirm.tpl");
518 $o = replace_macros($tpl, [
519 '$dfrn_url' => $dfrn_url,
520 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
521 '$hidethem' => L10n::t('Hide this contact'),
522 '$hidechecked' => '',
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 ((x($_GET, 'confirm_key')) && strlen($_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 dbesc($_GET['confirm_key'])
540 if (DBA::is_result($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::is_result($r)) {
549 if ($r[0]['page-flags'] != PAGE_NORMAL && $r[0]['page-flags'] != PAGE_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'] == PAGE_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 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
589 dbesc($_GET['confirm_key'])
595 return; // NOTREACHED
597 // Normal web request. Display our user's introduction form.
598 if ((Config::get('system', 'block_public')) && (!local_user()) && (!remote_user())) {
599 if (!Config::get('system', 'local_block')) {
600 notice(L10n::t('Public access denied.') . EOL);
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 (x($_GET, 'addr') && ($_GET['addr'] != "")) {
609 $myaddr = hex2bin($_GET['addr']);
610 } elseif (x($_GET, 'address') && ($_GET['address'] != "")) {
611 $myaddr = $_GET['address'];
612 } elseif (local_user()) {
613 if (strlen($a->urlpath)) {
614 $myaddr = System::baseUrl() . '/profile/' . $a->user['nickname'];
616 $myaddr = $a->user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
620 $myaddr = Profile::getMyURL();
623 $target_addr = $a->profile['nickname'] . '@' . substr(System::baseUrl(), strpos(System::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'] == PAGE_NORMAL) {
630 $tpl = get_markup_template('dfrn_request.tpl');
632 $tpl = get_markup_template('auto_request.tpl');
635 $page_desc = L10n::t("Please enter your 'Identity Address' from one of the following supported communications networks:");
637 $invite_desc = sprintf(
638 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>.'),
639 get_server() . '/servers'
642 $o = replace_macros($tpl, [
643 '$header' => L10n::t('Friend/Connection Request'),
644 '$desc' => L10n::t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
645 '$pls_answer' => L10n::t('Please answer the following:'),
646 '$does_know_you' => ['knowyou', L10n::t('Does %s know you?', $a->profile['name']), false, '', [L10n::t('No'), L10n::t('Yes')]],
647 '$add_note' => L10n::t('Add a personal note:'),
648 '$page_desc' => $page_desc,
649 '$friendica' => L10n::t('Friendica'),
650 '$statusnet' => L10n::t("GNU Social \x28Pleroma, Mastodon\x29"),
651 '$diaspora' => L10n::t("Diaspora \x28Socialhome, Hubzilla\x29"),
652 '$diasnote' => L10n::t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.', $target_addr),
653 '$your_address' => L10n::t('Your Identity Address:'),
654 '$invite_desc' => $invite_desc,
655 '$submit' => L10n::t('Submit Request'),
656 '$cancel' => L10n::t('Cancel'),
657 '$nickname' => $a->argv[1],
658 '$name' => $a->profile['name'],
664 return; // Somebody is fishing.