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\Logger;
19 use Friendica\Core\Protocol;
20 use Friendica\Core\Renderer;
21 use Friendica\Core\System;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Profile;
26 use Friendica\Model\User;
27 use Friendica\Module\Login;
28 use Friendica\Network\Probe;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Network;
32 require_once 'include/enotify.php';
34 function dfrn_request_init(App $a)
40 Profile::load($a, $which);
45 * Function: dfrn_request_post
48 * Handles multiple scenarios.
51 * Clicking 'submit' on a friend request page.
54 * Following Scenario 1, we are brought back to our home site
55 * in order to link our friend request with our own server cell.
56 * After logging in, we click 'submit' to approve the linkage.
59 function dfrn_request_post(App $a)
61 if (($a->argc != 2) || (!count($a->profile))) {
62 Logger::log('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
66 if (x($_POST, 'cancel')) {
67 $a->internalRedirect();
71 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
72 * to confirm the request, and then we've clicked submit (perhaps after logging in).
73 * That brings us here:
75 if ((x($_POST, 'localconfirm')) && ($_POST['localconfirm'] == 1)) {
76 // Ensure this is a valid request
77 if (local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST, 'dfrn_url'))) {
78 $dfrn_url = notags(trim($_POST['dfrn_url']));
79 $aes_allow = (((x($_POST, 'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
80 $confirm_key = ((x($_POST, 'confirm_key')) ? $_POST['confirm_key'] : "");
81 $hidden = ((x($_POST, 'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
82 $contact_record = null;
87 // Lookup the contact based on their URL (which is the only unique thing we have at the moment)
88 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
90 DBA::escape(normalise_link($dfrn_url))
93 if (DBA::isResult($r)) {
94 if (strlen($r[0]['dfrn-id'])) {
95 // We don't need to be here. It has already happened.
96 notice(L10n::t("This introduction has already been accepted.") . EOL);
99 $contact_record = $r[0];
103 if (is_array($contact_record)) {
104 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
107 intval($contact_record['id'])
110 // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
111 $parms = Probe::profile($dfrn_url);
113 if (!count($parms)) {
114 notice(L10n::t('Profile location is not valid or does not contain profile information.') . EOL);
117 if (!x($parms, 'fn')) {
118 notice(L10n::t('Warning: profile location has no identifiable owner name.') . EOL);
120 if (!x($parms, 'photo')) {
121 notice(L10n::t('Warning: profile location has no profile photo.') . EOL);
123 $invalid = Probe::validDfrn($parms);
125 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);
130 $dfrn_request = $parms['dfrn-request'];
132 $photo = $parms["photo"];
134 // Escape the entire array
135 DBA::escapeArray($parms);
137 // Create a contact record on our site for the other person
138 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
139 `request`, `confirm`, `notify`, `poll`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
140 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
141 intval(local_user()),
142 DateTimeFormat::utcNow(),
143 DBA::escape($dfrn_url),
144 DBA::escape(normalise_link($dfrn_url)),
150 $parms['dfrn-request'],
151 $parms['dfrn-confirm'],
152 $parms['dfrn-notify'],
154 DBA::escape(Protocol::DFRN),
163 info(L10n::t("Introduction complete.") . EOL);
166 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
167 intval(local_user()),
168 DBA::escape($dfrn_url),
169 $parms['key'] // this was already escaped
171 if (DBA::isResult($r)) {
172 Group::addMember(User::getDefaultGroup(local_user(), $r[0]["network"]), $r[0]['id']);
175 Contact::updateAvatar($photo, local_user(), $r[0]["id"], true);
178 $forward_path = "contact/" . $r[0]['id'];
180 $forward_path = "contact";
183 // Allow the blocked remote notification to complete
184 if (is_array($contact_record)) {
185 $dfrn_request = $contact_record['request'];
188 if (strlen($dfrn_request) && strlen($confirm_key)) {
189 $s = Network::fetchUrl($dfrn_request . '?confirm_key=' . $confirm_key);
192 // (ignore reply, nothing we can do it failed)
193 $a->internalRedirect($forward_path);
194 return; // NOTREACHED
198 // invalid/bogus request
199 notice(L10n::t('Unrecoverable protocol error.') . EOL);
200 $a->internalRedirect();
201 return; // NOTREACHED
208 * We are the requestee. A person from a remote cell has made an introduction
209 * on our profile web page and clicked submit. We will use their DFRN-URL to
210 * figure out how to contact their cell.
212 * Scrape the originating DFRN-URL for everything we need. Create a contact record
213 * and an introduction to show our user next time he/she logs in.
214 * Finally redirect back to the requestor so that their site can record the request.
215 * If our user (the requestee) later confirms this request, a record of it will need
216 * to exist on the requestor's cell in order for the confirmation process to complete..
218 * It's possible that neither the requestor or the requestee are logged in at the moment,
219 * and the requestor does not yet have any credentials to the requestee profile.
221 * Who is the requestee? We've already loaded their profile which means their nickname should be
222 * in $a->argv[1] and we should have their complete info in $a->profile.
225 if (!(is_array($a->profile) && count($a->profile))) {
226 notice(L10n::t('Profile unavailable.') . EOL);
230 $nickname = $a->profile['nickname'];
231 $notify_flags = $a->profile['notify-flags'];
232 $uid = $a->profile['uid'];
233 $maxreq = intval($a->profile['maxreq']);
234 $contact_record = null;
240 if (x($_POST, 'dfrn_url')) {
241 // Block friend request spam
243 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
244 DBA::escape(DateTimeFormat::utc('now - 24 hours')),
247 if (DBA::isResult($r) && count($r) > $maxreq) {
248 notice(L10n::t('%s has received too many connection requests today.', $a->profile['name']) . EOL);
249 notice(L10n::t('Spam protection measures have been invoked.') . EOL);
250 notice(L10n::t('Friends are advised to please try again in 24 hours.') . EOL);
255 /* Cleanup old introductions that remain blocked.
256 * Also remove the contact record, but only if there is no existing relationship
258 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
259 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
260 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
261 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
263 if (DBA::isResult($r)) {
264 foreach ($r as $rr) {
266 DBA::delete('contact', ['id' => $rr['cid'], 'self' => false]);
268 DBA::delete('intro', ['id' => $rr['iid']]);
272 $real_name = x($_POST, 'realname') ? notags(trim($_POST['realname'])) : '';
274 $url = trim($_POST['dfrn_url']);
276 notice(L10n::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 != Protocol::DIASPORA) {
294 $network = Protocol::OSTATUS;
297 $url = substr($url, 5);
299 $network = Protocol::DFRN;
302 Logger::log('dfrn_request: url: ' . $url . ',network=' . $network, Logger::DEBUG);
304 if ($network === Protocol::DFRN) {
305 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
310 if (DBA::isResult($ret)) {
311 if (strlen($ret[0]['issued-id'])) {
312 notice(L10n::t('You have already introduced yourself here.') . EOL);
314 } elseif ($ret[0]['rel'] == Contact::FRIEND) {
315 notice(L10n::t('Apparently you are already friends with %s.', $a->profile['name']) . EOL);
318 $contact_record = $ret[0];
319 $parms = ['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",
329 DBA::escape($issued_id),
330 intval($contact_record['id'])
333 $url = Network::isUrlValid($url);
335 notice(L10n::t('Invalid profile URL.') . EOL);
336 $a->internalRedirect($a->cmd);
337 return; // NOTREACHED
340 if (!Network::isUrlAllowed($url)) {
341 notice(L10n::t('Disallowed profile URL.') . EOL);
342 $a->internalRedirect($a->cmd);
343 return; // NOTREACHED
346 if (Network::isUrlBlocked($url)) {
347 notice(L10n::t('Blocked domain') . EOL);
348 $a->internalRedirect($a->cmd);
349 return; // NOTREACHED
352 $parms = Probe::profile(($hcard) ? $hcard : $url);
354 if (!count($parms)) {
355 notice(L10n::t('Profile location is not valid or does not contain profile information.') . EOL);
356 $a->internalRedirect($a->cmd);
358 if (!x($parms, 'fn')) {
359 notice(L10n::t('Warning: profile location has no identifiable owner name.') . EOL);
361 if (!x($parms, 'photo')) {
362 notice(L10n::t('Warning: profile location has no profile photo.') . EOL);
364 $invalid = Probe::validDfrn($parms);
366 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);
372 $parms['url'] = $url;
373 $parms['issued-id'] = $issued_id;
374 $photo = $parms["photo"];
376 DBA::escapeArray($parms);
377 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
378 `request`, `confirm`, `notify`, `poll`, `network`, `blocked`, `pending` )
379 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
381 DBA::escape(DateTimeFormat::utcNow()),
383 DBA::escape(normalise_link($url)),
390 $parms['dfrn-request'],
391 $parms['dfrn-confirm'],
392 $parms['dfrn-notify'],
394 DBA::escape(Protocol::DFRN),
399 // find the contact record we just created
401 $r = q("SELECT `id` FROM `contact`
402 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
407 if (DBA::isResult($r)) {
408 $contact_record = $r[0];
409 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
414 notice(L10n::t('Failed to update contact record.') . EOL);
418 $hash = random_string() . (string) time(); // Generate a confirm_key
420 if (is_array($contact_record)) {
421 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
422 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
424 intval($contact_record['id']),
425 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
426 DBA::escape(notags(trim(defaults($_POST, 'dfrn-request-message', '')))),
428 DBA::escape(DateTimeFormat::utcNow())
432 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
434 info(L10n::t('Your introduction has been sent.') . EOL);
437 // "Homecoming" - send the requestor back to their site to record the introduction.
438 $dfrn_url = bin2hex($a->getBaseURL() . '/profile/' . $nickname);
439 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
441 System::externalRedirect($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
442 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
443 . '&confirm_key=' . $hash
444 . (($aes_allow) ? "&aes_allow=1" : "")
447 // END $network === Protocol::DFRN
448 } elseif (($network != Protocol::PHANTOM) && ($url != "")) {
450 /* Substitute our user's feed URL into $url template
451 * Send the subscriber home to subscribe
453 // Diaspora needs the uri in the format user@domain.tld
454 // Diaspora will support the remote subscription in a future version
455 if ($network == Protocol::DIASPORA) {
456 $uri = $nickname . '@' . $a->getHostName();
458 if ($a->getURLPath()) {
459 $uri .= '/' . $a->getURLPath();
462 $uri = urlencode($uri);
464 $uri = 'profile/' . $nickname;
467 $url = str_replace('{uri}', $uri, $url);
468 System::externalRedirect($url);
470 // END $network != Protocol::PHANTOM
472 notice(L10n::t("Remote subscription can't be done for your network. Please subscribe directly on your system.") . EOL);
478 function dfrn_request_content(App $a)
480 if (($a->argc != 2) || (!count($a->profile))) {
484 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
485 // to send us to the post section to record the introduction.
486 if (x($_GET, 'dfrn_url')) {
488 info(L10n::t("Please login to confirm introduction.") . EOL);
489 /* setup the return URL to come back to this page if they use openid */
490 return Login::form();
493 // Edge case, but can easily happen in the wild. This person is authenticated,
494 // but not as the person who needs to deal with this request.
495 if ($a->user['nickname'] != $a->argv[1]) {
496 notice(L10n::t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
497 return Login::form();
500 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
501 $aes_allow = x($_GET, 'aes_allow') && $_GET['aes_allow'] == 1 ? 1 : 0;
502 $confirm_key = x($_GET, 'confirm_key') ? $_GET['confirm_key'] : "";
504 // Checking fastlane for validity
505 if (x($_SESSION, "fastlane") && (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
506 $_POST["dfrn_url"] = $dfrn_url;
507 $_POST["confirm_key"] = $confirm_key;
508 $_POST["localconfirm"] = 1;
509 $_POST["hidden-contact"] = 0;
510 $_POST["submit"] = L10n::t('Confirm');
512 dfrn_request_post($a);
515 return; // NOTREACHED
518 $tpl = Renderer::getMarkupTemplate("dfrn_req_confirm.tpl");
519 $o = Renderer::replaceMacros($tpl, [
520 '$dfrn_url' => $dfrn_url,
521 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
522 '$hidethem' => L10n::t('Hide this contact'),
523 '$hidechecked' => '',
524 '$confirm_key' => $confirm_key,
525 '$welcome' => L10n::t('Welcome home %s.', $a->user['username']),
526 '$please' => L10n::t('Please confirm your introduction/connection request to %s.', $dfrn_url),
527 '$submit' => L10n::t('Confirm'),
528 '$uid' => $_SESSION['uid'],
529 '$nickname' => $a->user['nickname'],
530 'dfrn_rawurl' => $_GET['dfrn_url']
533 } elseif ((x($_GET, 'confirm_key')) && strlen($_GET['confirm_key'])) {
534 // we are the requestee and it is now safe to send our user their introduction,
535 // We could just unblock it, but first we have to jump through a few hoops to
536 // send an email, or even to find out if we need to send an email.
537 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
538 DBA::escape($_GET['confirm_key'])
541 if (DBA::isResult($intro)) {
542 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
543 WHERE `contact`.`id` = %d LIMIT 1",
544 intval($intro[0]['contact-id'])
547 $auto_confirm = false;
549 if (DBA::isResult($r)) {
550 if ($r[0]['page-flags'] != Contact::PAGE_NORMAL && $r[0]['page-flags'] != Contact::PAGE_PRVGROUP) {
551 $auto_confirm = true;
554 if (!$auto_confirm) {
556 'type' => NOTIFY_INTRO,
557 'notify_flags' => $r[0]['notify-flags'],
558 'language' => $r[0]['language'],
559 'to_name' => $r[0]['username'],
560 'to_email' => $r[0]['email'],
561 'uid' => $r[0]['uid'],
562 'link' => System::baseUrl() . '/notifications/intros',
563 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : L10n::t('[Name Withheld]')),
564 'source_link' => $r[0]['url'],
565 'source_photo' => $r[0]['photo'],
566 'verb' => ACTIVITY_REQ_FRIEND,
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'] == Contact::PAGE_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 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
590 DBA::escape($_GET['confirm_key'])
596 return; // NOTREACHED
598 // Normal web request. Display our user's introduction form.
599 if ((Config::get('system', 'block_public')) && (!local_user()) && (!remote_user())) {
600 if (!Config::get('system', 'local_block')) {
601 notice(L10n::t('Public access denied.') . EOL);
606 // Try to auto-fill the profile address
607 // At first look if an address was provided
608 // Otherwise take the local address
609 if (x($_GET, 'addr') && ($_GET['addr'] != "")) {
610 $myaddr = hex2bin($_GET['addr']);
611 } elseif (x($_GET, 'address') && ($_GET['address'] != "")) {
612 $myaddr = $_GET['address'];
613 } elseif (local_user()) {
614 if (strlen($a->getURLPath())) {
615 $myaddr = System::baseUrl() . '/profile/' . $a->user['nickname'];
617 $myaddr = $a->user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
621 $myaddr = Profile::getMyURL();
624 $target_addr = $a->profile['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
626 /* The auto_request form only has the profile address
627 * because nobody is going to read the comments and
628 * it doesn't matter if they know you or not.
630 if ($a->profile['page-flags'] == Contact::PAGE_NORMAL) {
631 $tpl = Renderer::getMarkupTemplate('dfrn_request.tpl');
633 $tpl = Renderer::getMarkupTemplate('auto_request.tpl');
636 $page_desc = L10n::t("Please enter your 'Identity Address' from one of the following supported communications networks:");
638 $invite_desc = sprintf(
639 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>.'),
640 get_server() . '/servers'
643 $o = Renderer::replaceMacros($tpl, [
644 '$header' => L10n::t('Friend/Connection Request'),
645 '$desc' => L10n::t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
646 '$pls_answer' => L10n::t('Please answer the following:'),
647 '$does_know_you' => ['knowyou', L10n::t('Does %s know you?', $a->profile['name']), false, '', [L10n::t('No'), L10n::t('Yes')]],
648 '$add_note' => L10n::t('Add a personal note:'),
649 '$page_desc' => $page_desc,
650 '$friendica' => L10n::t('Friendica'),
651 '$statusnet' => L10n::t("GNU Social \x28Pleroma, Mastodon\x29"),
652 '$diaspora' => L10n::t("Diaspora \x28Socialhome, Hubzilla\x29"),
653 '$diasnote' => L10n::t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.', $target_addr),
654 '$your_address' => L10n::t('Your Identity Address:'),
655 '$invite_desc' => $invite_desc,
656 '$submit' => L10n::t('Submit Request'),
657 '$cancel' => L10n::t('Cancel'),
658 '$nickname' => $a->argv[1],
659 '$name' => $a->profile['name'],
665 return; // Somebody is fishing.