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\L10n;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\System;
19 use Friendica\Database\DBM;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Group;
22 use Friendica\Model\User;
23 use Friendica\Model\Profile;
24 use Friendica\Module\Login;
25 use Friendica\Network\Probe;
27 require_once 'include/enotify.php';
29 function dfrn_request_init(App $a)
35 Profile::load($a, $which);
40 * Function: dfrn_request_post
43 * Handles multiple scenarios.
46 * Clicking 'submit' on a friend request page.
49 * Following Scenario 1, we are brought back to our home site
50 * in order to link our friend request with our own server cell.
51 * After logging in, we click 'submit' to approve the linkage.
54 function dfrn_request_post(App $a)
56 if (($a->argc != 2) || (!count($a->profile))) {
57 logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
61 if (x($_POST, 'cancel')) {
62 goaway(System::baseUrl());
66 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
67 * to confirm the request, and then we've clicked submit (perhaps after logging in).
68 * That brings us here:
70 if ((x($_POST, 'localconfirm')) && ($_POST['localconfirm'] == 1)) {
71 // Ensure this is a valid request
72 if (local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST, 'dfrn_url'))) {
73 $dfrn_url = notags(trim($_POST['dfrn_url']));
74 $aes_allow = (((x($_POST, 'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
75 $confirm_key = ((x($_POST, 'confirm_key')) ? $_POST['confirm_key'] : "");
76 $hidden = ((x($_POST, 'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
77 $contact_record = null;
82 // Lookup the contact based on their URL (which is the only unique thing we have at the moment)
83 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
85 dbesc(normalise_link($dfrn_url))
88 if (DBM::is_result($r)) {
89 if (strlen($r[0]['dfrn-id'])) {
90 // We don't need to be here. It has already happened.
91 notice(L10n::t("This introduction has already been accepted.") . EOL);
94 $contact_record = $r[0];
98 if (is_array($contact_record)) {
99 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
102 intval($contact_record['id'])
105 // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
106 $parms = Probe::profile($dfrn_url);
108 if (!count($parms)) {
109 notice(L10n::t('Profile location is not valid or does not contain profile information.') . EOL);
112 if (!x($parms, 'fn')) {
113 notice(L10n::t('Warning: profile location has no identifiable owner name.') . EOL);
115 if (!x($parms, 'photo')) {
116 notice(L10n::t('Warning: profile location has no profile photo.') . EOL);
118 $invalid = Probe::validDfrn($parms);
120 notice(sprintf(L10n::tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid), $invalid) . EOL);
125 $dfrn_request = $parms['dfrn-request'];
127 $photo = $parms["photo"];
129 // Escape the entire array
130 DBM::esc_array($parms);
132 // Create a contact record on our site for the other person
133 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
134 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
135 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
136 intval(local_user()),
139 dbesc(normalise_link($dfrn_url)),
145 $parms['dfrn-request'],
146 $parms['dfrn-confirm'],
147 $parms['dfrn-notify'],
159 info(L10n::t("Introduction complete.") . EOL);
162 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
163 intval(local_user()),
165 $parms['key'] // this was already escaped
167 if (DBM::is_result($r)) {
168 Group::addMember(User::getDefaultGroup($uid, $r[0]["network"]), $r[0]['id']);
171 Contact::updateAvatar($photo, local_user(), $r[0]["id"], true);
174 $forwardurl = System::baseUrl() . "/contacts/" . $r[0]['id'];
176 $forwardurl = System::baseUrl() . "/contacts";
179 // Allow the blocked remote notification to complete
180 if (is_array($contact_record)) {
181 $dfrn_request = $contact_record['request'];
184 if (strlen($dfrn_request) && strlen($confirm_key)) {
185 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
188 // (ignore reply, nothing we can do it failed)
189 // Old: goaway(Profile::zrl($dfrn_url));
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 dbesc(datetime_convert('UTC', 'UTC', 'now - 24 hours')),
244 if (DBM::is_result($r) && count($r) > $maxreq) {
245 notice(sprintf(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 (DBM::is_result($r)) {
261 foreach ($r as $rr) {
263 q("DELETE FROM `contact` WHERE `id` = %d AND NOT `self`",
267 q("DELETE FROM `intro` WHERE `id` = %d",
273 $real_name = x($_POST, 'realname') ? notags(trim($_POST['realname'])) : '';
275 $url = trim($_POST['dfrn_url']);
277 notice(L10n::t("Invalid locator") . EOL);
283 // Detect the network
284 $data = Probe::uri($url);
285 $network = $data["network"];
287 // Canonicalise email-style profile locator
288 $url = Probe::webfingerDfrn($url, $hcard);
290 if (substr($url, 0, 5) === 'stat:') {
291 // Every time we detect the remote subscription we define this as OStatus.
292 // We do this even if it is not OStatus.
293 // we only need to pass this through another section of the code.
294 if ($network != NETWORK_DIASPORA) {
295 $network = NETWORK_OSTATUS;
298 $url = substr($url, 5);
300 $network = NETWORK_DFRN;
303 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
305 if ($network === NETWORK_DFRN) {
306 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
311 if (DBM::is_result($ret)) {
312 if (strlen($ret[0]['issued-id'])) {
313 notice(L10n::t('You have already introduced yourself here.') . EOL);
315 } elseif ($ret[0]['rel'] == CONTACT_IS_FRIEND) {
316 notice(sprintf(L10n::t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
319 $contact_record = $ret[0];
320 $parms = ['dfrn-request' => $ret[0]['request']];
324 $issued_id = random_string();
326 if (is_array($contact_record)) {
327 // There is a contact record but no issued-id, so this
328 // is a reciprocal introduction from a known contact
329 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
331 intval($contact_record['id'])
334 $url = validate_url($url);
336 notice(L10n::t('Invalid profile URL.') . EOL);
337 goaway(System::baseUrl() . '/' . $a->cmd);
338 return; // NOTREACHED
341 if (!allowed_url($url)) {
342 notice(L10n::t('Disallowed profile URL.') . EOL);
343 goaway(System::baseUrl() . '/' . $a->cmd);
344 return; // NOTREACHED
347 if (blocked_url($url)) {
348 notice(L10n::t('Blocked domain') . EOL);
349 goaway(System::baseUrl() . '/' . $a->cmd);
350 return; // NOTREACHED
353 $parms = Probe::profile(($hcard) ? $hcard : $url);
355 if (!count($parms)) {
356 notice(L10n::t('Profile location is not valid or does not contain profile information.') . EOL);
357 goaway(System::baseUrl() . '/' . $a->cmd);
359 if (!x($parms, 'fn')) {
360 notice(L10n::t('Warning: profile location has no identifiable owner name.') . EOL);
362 if (!x($parms, 'photo')) {
363 notice(L10n::t('Warning: profile location has no profile photo.') . EOL);
365 $invalid = Probe::validDfrn($parms);
367 notice(sprintf(L10n::tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid), $invalid) . EOL);
373 $parms['url'] = $url;
374 $parms['issued-id'] = $issued_id;
375 $photo = $parms["photo"];
377 DBM::esc_array($parms);
378 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
379 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `blocked`, `pending` )
380 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
382 dbesc(datetime_convert()),
384 dbesc(normalise_link($url)),
391 $parms['dfrn-request'],
392 $parms['dfrn-confirm'],
393 $parms['dfrn-notify'],
401 // find the contact record we just created
403 $r = q("SELECT `id` FROM `contact`
404 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
409 if (DBM::is_result($r)) {
410 $contact_record = $r[0];
411 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
416 notice(L10n::t('Failed to update contact record.') . EOL);
420 $hash = random_string() . (string) time(); // Generate a confirm_key
422 if (is_array($contact_record)) {
423 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
424 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
426 intval($contact_record['id']),
427 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
428 dbesc(notags(trim($_POST['dfrn-request-message']))),
430 dbesc(datetime_convert())
434 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
436 info(L10n::t('Your introduction has been sent.') . EOL);
439 // "Homecoming" - send the requestor back to their site to record the introduction.
440 $dfrn_url = bin2hex(System::baseUrl() . '/profile/' . $nickname);
441 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
443 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
444 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
445 . '&confirm_key=' . $hash
446 . (($aes_allow) ? "&aes_allow=1" : "")
449 // END $network === NETWORK_DFRN
450 } elseif (($network != NETWORK_PHANTOM) && ($url != "")) {
452 /* Substitute our user's feed URL into $url template
453 * Send the subscriber home to subscribe
455 // Diaspora needs the uri in the format user@domain.tld
456 // Diaspora will support the remote subscription in a future version
457 if ($network == NETWORK_DIASPORA) {
458 $uri = $nickname . '@' . $a->get_hostname();
460 if ($a->get_path()) {
461 $uri .= '/' . $a->get_path();
464 $uri = urlencode($uri);
466 $uri = System::baseUrl() . '/profile/' . $nickname;
469 $url = str_replace('{uri}', $uri, $url);
472 // END $network != NETWORK_PHANTOM
474 notice(L10n::t("Remote subscription can't be done for your network. Please subscribe directly on your system.") . EOL);
480 function dfrn_request_content(App $a)
482 if (($a->argc != 2) || (!count($a->profile))) {
486 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
487 // to send us to the post section to record the introduction.
488 if (x($_GET, 'dfrn_url')) {
490 info(L10n::t("Please login to confirm introduction.") . EOL);
491 /* setup the return URL to come back to this page if they use openid */
492 return Login::form();
495 // Edge case, but can easily happen in the wild. This person is authenticated,
496 // but not as the person who needs to deal with this request.
497 if ($a->user['nickname'] != $a->argv[1]) {
498 notice(L10n::t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
499 return Login::form();
502 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
503 $aes_allow = x($_GET, 'aes_allow') && $_GET['aes_allow'] == 1 ? 1 : 0;
504 $confirm_key = x($_GET, 'confirm_key') ? $_GET['confirm_key'] : "";
506 // Checking fastlane for validity
507 if (x($_SESSION, "fastlane") && (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
508 $_POST["dfrn_url"] = $dfrn_url;
509 $_POST["confirm_key"] = $confirm_key;
510 $_POST["localconfirm"] = 1;
511 $_POST["hidden-contact"] = 0;
512 $_POST["submit"] = L10n::t('Confirm');
514 dfrn_request_post($a);
517 return; // NOTREACHED
520 $tpl = get_markup_template("dfrn_req_confirm.tpl");
521 $o = replace_macros($tpl, [
522 '$dfrn_url' => $dfrn_url,
523 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
524 '$hidethem' => L10n::t('Hide this contact'),
525 '$hidechecked' => '',
526 '$confirm_key' => $confirm_key,
527 '$welcome' => sprintf(L10n::t('Welcome home %s.'), $a->user['username']),
528 '$please' => sprintf(L10n::t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
529 '$submit' => L10n::t('Confirm'),
530 '$uid' => $_SESSION['uid'],
531 '$nickname' => $a->user['nickname'],
532 'dfrn_rawurl' => $_GET['dfrn_url']
535 } elseif ((x($_GET, 'confirm_key')) && strlen($_GET['confirm_key'])) {
536 // we are the requestee and it is now safe to send our user their introduction,
537 // We could just unblock it, but first we have to jump through a few hoops to
538 // send an email, or even to find out if we need to send an email.
539 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
540 dbesc($_GET['confirm_key'])
543 if (DBM::is_result($intro)) {
544 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
545 WHERE `contact`.`id` = %d LIMIT 1",
546 intval($intro[0]['contact-id'])
549 $auto_confirm = false;
551 if (DBM::is_result($r)) {
552 if ($r[0]['page-flags'] != PAGE_NORMAL && $r[0]['page-flags'] != PAGE_PRVGROUP) {
553 $auto_confirm = true;
556 if (!$auto_confirm) {
558 'type' => NOTIFY_INTRO,
559 'notify_flags' => $r[0]['notify-flags'],
560 'language' => $r[0]['language'],
561 'to_name' => $r[0]['username'],
562 'to_email' => $r[0]['email'],
563 'uid' => $r[0]['uid'],
564 'link' => System::baseUrl() . '/notifications/intros',
565 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : L10n::t('[Name Withheld]')),
566 'source_link' => $r[0]['url'],
567 'source_photo' => $r[0]['photo'],
568 'verb' => ACTIVITY_REQ_FRIEND,
574 require_once 'mod/dfrn_confirm.php';
576 'uid' => $r[0]['uid'],
577 'node' => $r[0]['nickname'],
578 'dfrn_id' => $r[0]['issued-id'],
579 'intro_id' => $intro[0]['id'],
580 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
581 'activity' => intval(PConfig::get($r[0]['uid'], 'system', 'post_newfriend'))
583 dfrn_confirm_post($a, $handsfree);
587 if (!$auto_confirm) {
589 // If we are auto_confirming, this record will have already been nuked
590 // in dfrn_confirm_post()
592 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
593 dbesc($_GET['confirm_key'])
599 return; // NOTREACHED
601 // Normal web request. Display our user's introduction form.
602 if ((Config::get('system', 'block_public')) && (!local_user()) && (!remote_user())) {
603 if (!Config::get('system', 'local_block')) {
604 notice(L10n::t('Public access denied.') . EOL);
609 // Try to auto-fill the profile address
610 // At first look if an address was provided
611 // Otherwise take the local address
612 if (x($_GET, 'addr') && ($_GET['addr'] != "")) {
613 $myaddr = hex2bin($_GET['addr']);
614 } elseif (x($_GET, 'address') && ($_GET['address'] != "")) {
615 $myaddr = $_GET['address'];
616 } elseif (local_user()) {
617 if (strlen($a->path)) {
618 $myaddr = System::baseUrl() . '/profile/' . $a->user['nickname'];
620 $myaddr = $a->user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
624 $myaddr = Profile::getMyURL();
627 $target_addr = $a->profile['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
629 /* The auto_request form only has the profile address
630 * because nobody is going to read the comments and
631 * it doesn't matter if they know you or not.
633 if ($a->profile['page-flags'] == PAGE_NORMAL) {
634 $tpl = get_markup_template('dfrn_request.tpl');
636 $tpl = get_markup_template('auto_request.tpl');
639 $page_desc = L10n::t("Please enter your 'Identity Address' from one of the following supported communications networks:");
641 $invite_desc = sprintf(
642 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>.'),
643 get_server() . '/servers'
646 $o = replace_macros($tpl, [
647 '$header' => L10n::t('Friend/Connection Request'),
648 '$desc' => L10n::t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
649 '$pls_answer' => L10n::t('Please answer the following:'),
650 '$does_know_you' => ['knowyou', sprintf(L10n::t('Does %s know you?'), $a->profile['name']), false, '', [L10n::t('No'), L10n::t('Yes')]],
651 '$add_note' => L10n::t('Add a personal note:'),
652 '$page_desc' => $page_desc,
653 '$friendica' => L10n::t('Friendica'),
654 '$statusnet' => L10n::t('GNU Social (Pleroma, Mastodon)'),
655 '$diaspora' => L10n::t('Diaspora (Socialhome, Hubzilla)'),
656 '$diasnote' => sprintf(L10n::t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'), $target_addr),
657 '$your_address' => L10n::t('Your Identity Address:'),
658 '$invite_desc' => $invite_desc,
659 '$submit' => L10n::t('Submit Request'),
660 '$cancel' => L10n::t('Cancel'),
661 '$nickname' => $a->argv[1],
662 '$name' => $a->profile['name'],
668 return; // Somebody is fishing.