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
15 use Friendica\Core\Config;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\System;
18 use Friendica\Database\DBM;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Group;
21 use Friendica\Model\User;
22 use Friendica\Model\Profile;
23 use Friendica\Module\Login;
24 use Friendica\Network\Probe;
26 require_once 'include/enotify.php';
28 function dfrn_request_init(App $a)
34 Profile::load($a, $which);
39 * Function: dfrn_request_post
42 * Handles multiple scenarios.
45 * Clicking 'submit' on a friend request page.
48 * Following Scenario 1, we are brought back to our home site
49 * in order to link our friend request with our own server cell.
50 * After logging in, we click 'submit' to approve the linkage.
53 function dfrn_request_post(App $a)
55 if (($a->argc != 2) || (!count($a->profile))) {
56 logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
60 if (x($_POST, 'cancel')) {
61 goaway(System::baseUrl());
65 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
66 * to confirm the request, and then we've clicked submit (perhaps after logging in).
67 * That brings us here:
69 if ((x($_POST, 'localconfirm')) && ($_POST['localconfirm'] == 1)) {
70 // Ensure this is a valid request
71 if (local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST, 'dfrn_url'))) {
72 $dfrn_url = notags(trim($_POST['dfrn_url']));
73 $aes_allow = (((x($_POST, 'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
74 $confirm_key = ((x($_POST, 'confirm_key')) ? $_POST['confirm_key'] : "");
75 $hidden = ((x($_POST, 'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
76 $contact_record = null;
81 // Lookup the contact based on their URL (which is the only unique thing we have at the moment)
82 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
84 dbesc(normalise_link($dfrn_url))
87 if (DBM::is_result($r)) {
88 if (strlen($r[0]['dfrn-id'])) {
89 // We don't need to be here. It has already happened.
90 notice(t("This introduction has already been accepted.") . EOL);
93 $contact_record = $r[0];
97 if (is_array($contact_record)) {
98 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
101 intval($contact_record['id'])
104 // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
105 $parms = Probe::profile($dfrn_url);
107 if (!count($parms)) {
108 notice(t('Profile location is not valid or does not contain profile information.') . EOL);
111 if (!x($parms, 'fn')) {
112 notice(t('Warning: profile location has no identifiable owner name.') . EOL);
114 if (!x($parms, 'photo')) {
115 notice(t('Warning: profile location has no profile photo.') . EOL);
117 $invalid = Probe::validDfrn($parms);
119 notice(sprintf(tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid), $invalid) . EOL);
124 $dfrn_request = $parms['dfrn-request'];
126 $photo = $parms["photo"];
128 // Escape the entire array
129 DBM::esc_array($parms);
131 // Create a contact record on our site for the other person
132 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
133 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
134 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
135 intval(local_user()),
138 dbesc(normalise_link($dfrn_url)),
144 $parms['dfrn-request'],
145 $parms['dfrn-confirm'],
146 $parms['dfrn-notify'],
158 info(t("Introduction complete.") . EOL);
161 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
162 intval(local_user()),
164 $parms['key'] // this was already escaped
166 if (DBM::is_result($r)) {
167 Group::addMember(User::getDefaultGroup($uid, $r[0]["network"]), $r[0]['id']);
170 Contact::updateAvatar($photo, local_user(), $r[0]["id"], true);
173 $forwardurl = System::baseUrl() . "/contacts/" . $r[0]['id'];
175 $forwardurl = System::baseUrl() . "/contacts";
178 // Allow the blocked remote notification to complete
179 if (is_array($contact_record)) {
180 $dfrn_request = $contact_record['request'];
183 if (strlen($dfrn_request) && strlen($confirm_key)) {
184 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
187 // (ignore reply, nothing we can do it failed)
188 // Old: goaway(Profile::zrl($dfrn_url));
190 return; // NOTREACHED
194 // invalid/bogus request
195 notice(t('Unrecoverable protocol error.') . EOL);
196 goaway(System::baseUrl());
197 return; // NOTREACHED
204 * We are the requestee. A person from a remote cell has made an introduction
205 * on our profile web page and clicked submit. We will use their DFRN-URL to
206 * figure out how to contact their cell.
208 * Scrape the originating DFRN-URL for everything we need. Create a contact record
209 * and an introduction to show our user next time he/she logs in.
210 * Finally redirect back to the requestor so that their site can record the request.
211 * If our user (the requestee) later confirms this request, a record of it will need
212 * to exist on the requestor's cell in order for the confirmation process to complete..
214 * It's possible that neither the requestor or the requestee are logged in at the moment,
215 * and the requestor does not yet have any credentials to the requestee profile.
217 * Who is the requestee? We've already loaded their profile which means their nickname should be
218 * in $a->argv[1] and we should have their complete info in $a->profile.
221 if (!(is_array($a->profile) && count($a->profile))) {
222 notice(t('Profile unavailable.') . EOL);
226 $nickname = $a->profile['nickname'];
227 $notify_flags = $a->profile['notify-flags'];
228 $uid = $a->profile['uid'];
229 $maxreq = intval($a->profile['maxreq']);
230 $contact_record = null;
236 if (x($_POST, 'dfrn_url')) {
237 // Block friend request spam
239 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
240 dbesc(datetime_convert('UTC', 'UTC', 'now - 24 hours')),
243 if (DBM::is_result($r) && count($r) > $maxreq) {
244 notice(sprintf(t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
245 notice(t('Spam protection measures have been invoked.') . EOL);
246 notice(t('Friends are advised to please try again in 24 hours.') . EOL);
251 /* Cleanup old introductions that remain blocked.
252 * Also remove the contact record, but only if there is no existing relationship
254 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
255 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
256 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
257 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
259 if (DBM::is_result($r)) {
260 foreach ($r as $rr) {
262 q("DELETE FROM `contact` WHERE `id` = %d AND NOT `self`",
266 q("DELETE FROM `intro` WHERE `id` = %d",
272 $real_name = x($_POST, 'realname') ? notags(trim($_POST['realname'])) : '';
274 $url = trim($_POST['dfrn_url']);
276 notice(t("Invalid locator") . EOL);
282 // Detect the network
283 $data = Probe::uri($url);
284 $network = $data["network"];
286 // Canonicalise email-style profile locator
287 $url = Probe::webfingerDfrn($url, $hcard);
289 if (substr($url, 0, 5) === 'stat:') {
290 // Every time we detect the remote subscription we define this as OStatus.
291 // We do this even if it is not OStatus.
292 // we only need to pass this through another section of the code.
293 if ($network != NETWORK_DIASPORA) {
294 $network = NETWORK_OSTATUS;
297 $url = substr($url, 5);
299 $network = NETWORK_DFRN;
302 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
304 if ($network === NETWORK_DFRN) {
305 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
310 if (DBM::is_result($ret)) {
311 if (strlen($ret[0]['issued-id'])) {
312 notice(t('You have already introduced yourself here.') . EOL);
314 } elseif ($ret[0]['rel'] == CONTACT_IS_FRIEND) {
315 notice(sprintf(t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
318 $contact_record = $ret[0];
319 $parms = array('dfrn-request' => $ret[0]['request']);
323 $issued_id = random_string();
325 if (is_array($contact_record)) {
326 // There is a contact record but no issued-id, so this
327 // is a reciprocal introduction from a known contact
328 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
330 intval($contact_record['id'])
333 $url = validate_url($url);
335 notice(t('Invalid profile URL.') . EOL);
336 goaway(System::baseUrl() . '/' . $a->cmd);
337 return; // NOTREACHED
340 if (!allowed_url($url)) {
341 notice(t('Disallowed profile URL.') . EOL);
342 goaway(System::baseUrl() . '/' . $a->cmd);
343 return; // NOTREACHED
346 if (blocked_url($url)) {
347 notice(t('Blocked domain') . EOL);
348 goaway(System::baseUrl() . '/' . $a->cmd);
349 return; // NOTREACHED
352 $parms = Probe::profile(($hcard) ? $hcard : $url);
354 if (!count($parms)) {
355 notice(t('Profile location is not valid or does not contain profile information.') . EOL);
356 goaway(System::baseUrl() . '/' . $a->cmd);
358 if (!x($parms, 'fn')) {
359 notice(t('Warning: profile location has no identifiable owner name.') . EOL);
361 if (!x($parms, 'photo')) {
362 notice(t('Warning: profile location has no profile photo.') . EOL);
364 $invalid = Probe::validDfrn($parms);
366 notice(sprintf(tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid), $invalid) . EOL);
372 $parms['url'] = $url;
373 $parms['issued-id'] = $issued_id;
374 $photo = $parms["photo"];
376 DBM::esc_array($parms);
377 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
378 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `blocked`, `pending` )
379 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
381 dbesc(datetime_convert()),
383 dbesc(normalise_link($url)),
390 $parms['dfrn-request'],
391 $parms['dfrn-confirm'],
392 $parms['dfrn-notify'],
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 (DBM::is_result($r)) {
409 $contact_record = $r[0];
410 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
415 notice(t('Failed to update contact record.') . EOL);
419 $hash = random_string() . (string) time(); // Generate a confirm_key
421 if (is_array($contact_record)) {
422 $ret = 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 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
427 dbesc(notags(trim($_POST['dfrn-request-message']))),
429 dbesc(datetime_convert())
433 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
435 info(t('Your introduction has been sent.') . EOL);
438 // "Homecoming" - send the requestor back to their site to record the introduction.
439 $dfrn_url = bin2hex(System::baseUrl() . '/profile/' . $nickname);
440 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
442 goaway($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 === NETWORK_DFRN
449 } elseif (($network != NETWORK_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 == NETWORK_DIASPORA) {
457 $uri = $nickname . '@' . $a->get_hostname();
459 if ($a->get_path()) {
460 $uri .= '/' . $a->get_path();
463 $uri = urlencode($uri);
465 $uri = System::baseUrl() . '/profile/' . $nickname;
468 $url = str_replace('{uri}', $uri, $url);
471 // END $network != NETWORK_PHANTOM
473 notice(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) || (!count($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 (x($_GET, 'dfrn_url')) {
489 info(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(t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
498 return Login::form();
501 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
502 $aes_allow = x($_GET, 'aes_allow') && $_GET['aes_allow'] == 1 ? 1 : 0;
503 $confirm_key = x($_GET, 'confirm_key') ? $_GET['confirm_key'] : "";
505 // Checking fastlane for validity
506 if (x($_SESSION, "fastlane") && (normalise_link($_SESSION["fastlane"]) == normalise_link($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"] = t('Confirm');
513 dfrn_request_post($a);
516 return; // NOTREACHED
519 $tpl = get_markup_template("dfrn_req_confirm.tpl");
520 $o = replace_macros($tpl, array(
521 '$dfrn_url' => $dfrn_url,
522 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
523 '$hidethem' => t('Hide this contact'),
524 '$hidechecked' => '',
525 '$confirm_key' => $confirm_key,
526 '$welcome' => sprintf(t('Welcome home %s.'), $a->user['username']),
527 '$please' => sprintf(t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
528 '$submit' => t('Confirm'),
529 '$uid' => $_SESSION['uid'],
530 '$nickname' => $a->user['nickname'],
531 'dfrn_rawurl' => $_GET['dfrn_url']
534 } elseif ((x($_GET, 'confirm_key')) && strlen($_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 dbesc($_GET['confirm_key'])
542 if (DBM::is_result($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 (DBM::is_result($r)) {
551 if ($r[0]['page-flags'] != PAGE_NORMAL && $r[0]['page-flags'] != PAGE_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' => System::baseUrl() . '/notifications/intros',
564 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : 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'] == PAGE_FREELOVE) ? 1 : 0),
580 'activity' => intval(PConfig::get($r[0]['uid'], 'system', 'post_newfriend'))
582 dfrn_confirm_post($a, $handsfree);
586 if (!$auto_confirm) {
588 // If we are auto_confirming, this record will have already been nuked
589 // in dfrn_confirm_post()
591 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
592 dbesc($_GET['confirm_key'])
598 return; // NOTREACHED
600 // Normal web request. Display our user's introduction form.
601 if ((Config::get('system', 'block_public')) && (!local_user()) && (!remote_user())) {
602 if (!Config::get('system', 'local_block')) {
603 notice(t('Public access denied.') . EOL);
608 // Try to auto-fill the profile address
609 // At first look if an address was provided
610 // Otherwise take the local address
611 if (x($_GET, 'addr') && ($_GET['addr'] != "")) {
612 $myaddr = hex2bin($_GET['addr']);
613 } elseif (x($_GET, 'address') && ($_GET['address'] != "")) {
614 $myaddr = $_GET['address'];
615 } elseif (local_user()) {
616 if (strlen($a->path)) {
617 $myaddr = System::baseUrl() . '/profile/' . $a->user['nickname'];
619 $myaddr = $a->user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
623 $myaddr = Profile::getMyURL();
626 $target_addr = $a->profile['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
628 /* The auto_request form only has the profile address
629 * because nobody is going to read the comments and
630 * it doesn't matter if they know you or not.
632 if ($a->profile['page-flags'] == PAGE_NORMAL) {
633 $tpl = get_markup_template('dfrn_request.tpl');
635 $tpl = get_markup_template('auto_request.tpl');
638 $page_desc = t("Please enter your 'Identity Address' from one of the following supported communications networks:");
640 $invite_desc = sprintf(
641 t('If you are not yet a member of the free social web, <a href="%s/siteinfo">follow this link to find a public Friendica site and join us today</a>.'),
645 $o = replace_macros($tpl, array(
646 '$header' => t('Friend/Connection Request'),
647 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
648 '$pls_answer' => t('Please answer the following:'),
649 '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'), $a->profile['name']), false, '', array(t('No'), t('Yes'))),
650 '$add_note' => t('Add a personal note:'),
651 '$page_desc' => $page_desc,
652 '$friendica' => t('Friendica'),
653 '$statusnet' => t('GNU Social (Pleroma, Mastodon)'),
654 '$diaspora' => t('Diaspora (Socialhome, Hubzilla)'),
655 '$diasnote' => sprintf(t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'), $target_addr),
656 '$your_address' => t('Your Identity Address:'),
657 '$invite_desc' => $invite_desc,
658 '$submit' => t('Submit Request'),
659 '$cancel' => t('Cancel'),
660 '$nickname' => $a->argv[1],
661 '$name' => $a->profile['name'],
667 return; // Somebody is fishing.