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 DBA::escape(normalise_link($dfrn_url))
90 if (DBA::isResult($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::escapeArray($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`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
137 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
138 intval(local_user()),
139 DateTimeFormat::utcNow(),
140 DBA::escape($dfrn_url),
141 DBA::escape(normalise_link($dfrn_url)),
147 $parms['dfrn-request'],
148 $parms['dfrn-confirm'],
149 $parms['dfrn-notify'],
151 DBA::escape(NETWORK_DFRN),
160 info(L10n::t("Introduction complete.") . EOL);
163 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
164 intval(local_user()),
165 DBA::escape($dfrn_url),
166 $parms['key'] // this was already escaped
168 if (DBA::isResult($r)) {
169 Group::addMember(User::getDefaultGroup(local_user(), $r[0]["network"]), $r[0]['id']);
172 Contact::updateAvatar($photo, local_user(), $r[0]["id"], true);
175 $forwardurl = System::baseUrl() . "/contacts/" . $r[0]['id'];
177 $forwardurl = System::baseUrl() . "/contacts";
180 // Allow the blocked remote notification to complete
181 if (is_array($contact_record)) {
182 $dfrn_request = $contact_record['request'];
185 if (strlen($dfrn_request) && strlen($confirm_key)) {
186 $s = Network::fetchUrl($dfrn_request . '?confirm_key=' . $confirm_key);
189 // (ignore reply, nothing we can do it failed)
191 return; // NOTREACHED
195 // invalid/bogus request
196 notice(L10n::t('Unrecoverable protocol error.') . EOL);
197 goaway(System::baseUrl());
198 return; // NOTREACHED
205 * We are the requestee. A person from a remote cell has made an introduction
206 * on our profile web page and clicked submit. We will use their DFRN-URL to
207 * figure out how to contact their cell.
209 * Scrape the originating DFRN-URL for everything we need. Create a contact record
210 * and an introduction to show our user next time he/she logs in.
211 * Finally redirect back to the requestor so that their site can record the request.
212 * If our user (the requestee) later confirms this request, a record of it will need
213 * to exist on the requestor's cell in order for the confirmation process to complete..
215 * It's possible that neither the requestor or the requestee are logged in at the moment,
216 * and the requestor does not yet have any credentials to the requestee profile.
218 * Who is the requestee? We've already loaded their profile which means their nickname should be
219 * in $a->argv[1] and we should have their complete info in $a->profile.
222 if (!(is_array($a->profile) && count($a->profile))) {
223 notice(L10n::t('Profile unavailable.') . EOL);
227 $nickname = $a->profile['nickname'];
228 $notify_flags = $a->profile['notify-flags'];
229 $uid = $a->profile['uid'];
230 $maxreq = intval($a->profile['maxreq']);
231 $contact_record = null;
237 if (x($_POST, 'dfrn_url')) {
238 // Block friend request spam
240 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
241 DBA::escape(DateTimeFormat::utc('now - 24 hours')),
244 if (DBA::isResult($r) && count($r) > $maxreq) {
245 notice(L10n::t('%s has received too many connection requests today.', $a->profile['name']) . EOL);
246 notice(L10n::t('Spam protection measures have been invoked.') . EOL);
247 notice(L10n::t('Friends are advised to please try again in 24 hours.') . EOL);
252 /* Cleanup old introductions that remain blocked.
253 * Also remove the contact record, but only if there is no existing relationship
255 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
256 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
257 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
258 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
260 if (DBA::isResult($r)) {
261 foreach ($r as $rr) {
263 DBA::delete('contact', ['id' => $rr['cid'], 'self' => false]);
265 DBA::delete('intro', ['id' => $rr['iid']]);
269 $real_name = x($_POST, 'realname') ? notags(trim($_POST['realname'])) : '';
271 $url = trim($_POST['dfrn_url']);
273 notice(L10n::t("Invalid locator") . EOL);
279 // Detect the network
280 $data = Probe::uri($url);
281 $network = $data["network"];
283 // Canonicalise email-style profile locator
284 $url = Probe::webfingerDfrn($url, $hcard);
286 if (substr($url, 0, 5) === 'stat:') {
287 // Every time we detect the remote subscription we define this as OStatus.
288 // We do this even if it is not OStatus.
289 // we only need to pass this through another section of the code.
290 if ($network != NETWORK_DIASPORA) {
291 $network = NETWORK_OSTATUS;
294 $url = substr($url, 5);
296 $network = NETWORK_DFRN;
299 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
301 if ($network === NETWORK_DFRN) {
302 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
307 if (DBA::isResult($ret)) {
308 if (strlen($ret[0]['issued-id'])) {
309 notice(L10n::t('You have already introduced yourself here.') . EOL);
311 } elseif ($ret[0]['rel'] == Contact::FRIEND) {
312 notice(L10n::t('Apparently you are already friends with %s.', $a->profile['name']) . EOL);
315 $contact_record = $ret[0];
316 $parms = ['dfrn-request' => $ret[0]['request']];
320 $issued_id = random_string();
322 if (is_array($contact_record)) {
323 // There is a contact record but no issued-id, so this
324 // is a reciprocal introduction from a known contact
325 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
326 DBA::escape($issued_id),
327 intval($contact_record['id'])
330 $url = Network::isUrlValid($url);
332 notice(L10n::t('Invalid profile URL.') . EOL);
333 goaway(System::baseUrl() . '/' . $a->cmd);
334 return; // NOTREACHED
337 if (!Network::isUrlAllowed($url)) {
338 notice(L10n::t('Disallowed profile URL.') . EOL);
339 goaway(System::baseUrl() . '/' . $a->cmd);
340 return; // NOTREACHED
343 if (Network::isUrlBlocked($url)) {
344 notice(L10n::t('Blocked domain') . EOL);
345 goaway(System::baseUrl() . '/' . $a->cmd);
346 return; // NOTREACHED
349 $parms = Probe::profile(($hcard) ? $hcard : $url);
351 if (!count($parms)) {
352 notice(L10n::t('Profile location is not valid or does not contain profile information.') . EOL);
353 goaway(System::baseUrl() . '/' . $a->cmd);
355 if (!x($parms, 'fn')) {
356 notice(L10n::t('Warning: profile location has no identifiable owner name.') . EOL);
358 if (!x($parms, 'photo')) {
359 notice(L10n::t('Warning: profile location has no profile photo.') . EOL);
361 $invalid = Probe::validDfrn($parms);
363 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);
369 $parms['url'] = $url;
370 $parms['issued-id'] = $issued_id;
371 $photo = $parms["photo"];
373 DBA::escapeArray($parms);
374 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
375 `request`, `confirm`, `notify`, `poll`, `network`, `blocked`, `pending` )
376 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
378 DBA::escape(DateTimeFormat::utcNow()),
380 DBA::escape(normalise_link($url)),
387 $parms['dfrn-request'],
388 $parms['dfrn-confirm'],
389 $parms['dfrn-notify'],
391 DBA::escape(NETWORK_DFRN),
396 // find the contact record we just created
398 $r = q("SELECT `id` FROM `contact`
399 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
404 if (DBA::isResult($r)) {
405 $contact_record = $r[0];
406 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
411 notice(L10n::t('Failed to update contact record.') . EOL);
415 $hash = random_string() . (string) time(); // Generate a confirm_key
417 if (is_array($contact_record)) {
418 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
419 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
421 intval($contact_record['id']),
422 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
423 DBA::escape(notags(trim(defaults($_POST, 'dfrn-request-message', '')))),
425 DBA::escape(DateTimeFormat::utcNow())
429 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
431 info(L10n::t('Your introduction has been sent.') . EOL);
434 // "Homecoming" - send the requestor back to their site to record the introduction.
435 $dfrn_url = bin2hex(System::baseUrl() . '/profile/' . $nickname);
436 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
438 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
439 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
440 . '&confirm_key=' . $hash
441 . (($aes_allow) ? "&aes_allow=1" : "")
444 // END $network === NETWORK_DFRN
445 } elseif (($network != NETWORK_PHANTOM) && ($url != "")) {
447 /* Substitute our user's feed URL into $url template
448 * Send the subscriber home to subscribe
450 // Diaspora needs the uri in the format user@domain.tld
451 // Diaspora will support the remote subscription in a future version
452 if ($network == NETWORK_DIASPORA) {
453 $uri = $nickname . '@' . $a->get_hostname();
455 if ($a->get_path()) {
456 $uri .= '/' . $a->get_path();
459 $uri = urlencode($uri);
461 $uri = System::baseUrl() . '/profile/' . $nickname;
464 $url = str_replace('{uri}', $uri, $url);
467 // END $network != NETWORK_PHANTOM
469 notice(L10n::t("Remote subscription can't be done for your network. Please subscribe directly on your system.") . EOL);
475 function dfrn_request_content(App $a)
477 if (($a->argc != 2) || (!count($a->profile))) {
481 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
482 // to send us to the post section to record the introduction.
483 if (x($_GET, 'dfrn_url')) {
485 info(L10n::t("Please login to confirm introduction.") . EOL);
486 /* setup the return URL to come back to this page if they use openid */
487 return Login::form();
490 // Edge case, but can easily happen in the wild. This person is authenticated,
491 // but not as the person who needs to deal with this request.
492 if ($a->user['nickname'] != $a->argv[1]) {
493 notice(L10n::t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
494 return Login::form();
497 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
498 $aes_allow = x($_GET, 'aes_allow') && $_GET['aes_allow'] == 1 ? 1 : 0;
499 $confirm_key = x($_GET, 'confirm_key') ? $_GET['confirm_key'] : "";
501 // Checking fastlane for validity
502 if (x($_SESSION, "fastlane") && (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
503 $_POST["dfrn_url"] = $dfrn_url;
504 $_POST["confirm_key"] = $confirm_key;
505 $_POST["localconfirm"] = 1;
506 $_POST["hidden-contact"] = 0;
507 $_POST["submit"] = L10n::t('Confirm');
509 dfrn_request_post($a);
512 return; // NOTREACHED
515 $tpl = get_markup_template("dfrn_req_confirm.tpl");
516 $o = replace_macros($tpl, [
517 '$dfrn_url' => $dfrn_url,
518 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
519 '$hidethem' => L10n::t('Hide this contact'),
520 '$hidechecked' => '',
521 '$confirm_key' => $confirm_key,
522 '$welcome' => L10n::t('Welcome home %s.', $a->user['username']),
523 '$please' => L10n::t('Please confirm your introduction/connection request to %s.', $dfrn_url),
524 '$submit' => L10n::t('Confirm'),
525 '$uid' => $_SESSION['uid'],
526 '$nickname' => $a->user['nickname'],
527 'dfrn_rawurl' => $_GET['dfrn_url']
530 } elseif ((x($_GET, 'confirm_key')) && strlen($_GET['confirm_key'])) {
531 // we are the requestee and it is now safe to send our user their introduction,
532 // We could just unblock it, but first we have to jump through a few hoops to
533 // send an email, or even to find out if we need to send an email.
534 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
535 DBA::escape($_GET['confirm_key'])
538 if (DBA::isResult($intro)) {
539 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
540 WHERE `contact`.`id` = %d LIMIT 1",
541 intval($intro[0]['contact-id'])
544 $auto_confirm = false;
546 if (DBA::isResult($r)) {
547 if ($r[0]['page-flags'] != Contact::PAGE_NORMAL && $r[0]['page-flags'] != Contact::PAGE_PRVGROUP) {
548 $auto_confirm = true;
551 if (!$auto_confirm) {
553 'type' => NOTIFY_INTRO,
554 'notify_flags' => $r[0]['notify-flags'],
555 'language' => $r[0]['language'],
556 'to_name' => $r[0]['username'],
557 'to_email' => $r[0]['email'],
558 'uid' => $r[0]['uid'],
559 'link' => System::baseUrl() . '/notifications/intros',
560 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : L10n::t('[Name Withheld]')),
561 'source_link' => $r[0]['url'],
562 'source_photo' => $r[0]['photo'],
563 'verb' => ACTIVITY_REQ_FRIEND,
569 require_once 'mod/dfrn_confirm.php';
571 'uid' => $r[0]['uid'],
572 'node' => $r[0]['nickname'],
573 'dfrn_id' => $r[0]['issued-id'],
574 'intro_id' => $intro[0]['id'],
575 'duplex' => (($r[0]['page-flags'] == Contact::PAGE_FREELOVE) ? 1 : 0),
577 dfrn_confirm_post($a, $handsfree);
581 if (!$auto_confirm) {
583 // If we are auto_confirming, this record will have already been nuked
584 // in dfrn_confirm_post()
586 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
587 DBA::escape($_GET['confirm_key'])
593 return; // NOTREACHED
595 // Normal web request. Display our user's introduction form.
596 if ((Config::get('system', 'block_public')) && (!local_user()) && (!remote_user())) {
597 if (!Config::get('system', 'local_block')) {
598 notice(L10n::t('Public access denied.') . EOL);
603 // Try to auto-fill the profile address
604 // At first look if an address was provided
605 // Otherwise take the local address
606 if (x($_GET, 'addr') && ($_GET['addr'] != "")) {
607 $myaddr = hex2bin($_GET['addr']);
608 } elseif (x($_GET, 'address') && ($_GET['address'] != "")) {
609 $myaddr = $_GET['address'];
610 } elseif (local_user()) {
611 if (strlen($a->urlpath)) {
612 $myaddr = System::baseUrl() . '/profile/' . $a->user['nickname'];
614 $myaddr = $a->user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
618 $myaddr = Profile::getMyURL();
621 $target_addr = $a->profile['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
623 /* The auto_request form only has the profile address
624 * because nobody is going to read the comments and
625 * it doesn't matter if they know you or not.
627 if ($a->profile['page-flags'] == Contact::PAGE_NORMAL) {
628 $tpl = get_markup_template('dfrn_request.tpl');
630 $tpl = get_markup_template('auto_request.tpl');
633 $page_desc = L10n::t("Please enter your 'Identity Address' from one of the following supported communications networks:");
635 $invite_desc = sprintf(
636 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>.'),
637 get_server() . '/servers'
640 $o = replace_macros($tpl, [
641 '$header' => L10n::t('Friend/Connection Request'),
642 '$desc' => L10n::t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
643 '$pls_answer' => L10n::t('Please answer the following:'),
644 '$does_know_you' => ['knowyou', L10n::t('Does %s know you?', $a->profile['name']), false, '', [L10n::t('No'), L10n::t('Yes')]],
645 '$add_note' => L10n::t('Add a personal note:'),
646 '$page_desc' => $page_desc,
647 '$friendica' => L10n::t('Friendica'),
648 '$statusnet' => L10n::t("GNU Social \x28Pleroma, Mastodon\x29"),
649 '$diaspora' => L10n::t("Diaspora \x28Socialhome, Hubzilla\x29"),
650 '$diasnote' => L10n::t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.', $target_addr),
651 '$your_address' => L10n::t('Your Identity Address:'),
652 '$invite_desc' => $invite_desc,
653 '$submit' => L10n::t('Submit Request'),
654 '$cancel' => L10n::t('Cancel'),
655 '$nickname' => $a->argv[1],
656 '$name' => $a->profile['name'],
662 return; // Somebody is fishing.