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\Module\Login;
23 use Friendica\Network\Probe;
25 require_once 'include/enotify.php';
27 function dfrn_request_init(App $a)
32 profile_load($a, $which);
37 * Function: dfrn_request_post
40 * Handles multiple scenarios.
43 * Clicking 'submit' on a friend request page.
46 * Following Scenario 1, we are brought back to our home site
47 * in order to link our friend request with our own server cell.
48 * After logging in, we click 'submit' to approve the linkage.
51 function dfrn_request_post(App $a)
53 if (($a->argc != 2) || (!count($a->profile))) {
54 logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
58 if (x($_POST, 'cancel')) {
59 goaway(System::baseUrl());
63 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
64 * to confirm the request, and then we've clicked submit (perhaps after logging in).
65 * That brings us here:
67 if ((x($_POST, 'localconfirm')) && ($_POST['localconfirm'] == 1)) {
68 // Ensure this is a valid request
69 if (local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST, 'dfrn_url'))) {
70 $dfrn_url = notags(trim($_POST['dfrn_url']));
71 $aes_allow = (((x($_POST, 'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
72 $confirm_key = ((x($_POST, 'confirm_key')) ? $_POST['confirm_key'] : "");
73 $hidden = ((x($_POST, 'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
74 $contact_record = null;
79 // Lookup the contact based on their URL (which is the only unique thing we have at the moment)
80 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
82 dbesc(normalise_link($dfrn_url))
85 if (DBM::is_result($r)) {
86 if (strlen($r[0]['dfrn-id'])) {
87 // We don't need to be here. It has already happened.
88 notice(t("This introduction has already been accepted.") . EOL);
91 $contact_record = $r[0];
95 if (is_array($contact_record)) {
96 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
99 intval($contact_record['id'])
102 // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
103 $parms = Probe::profile($dfrn_url);
105 if (!count($parms)) {
106 notice(t('Profile location is not valid or does not contain profile information.') . EOL);
109 if (!x($parms, 'fn')) {
110 notice(t('Warning: profile location has no identifiable owner name.') . EOL);
112 if (!x($parms, 'photo')) {
113 notice(t('Warning: profile location has no profile photo.') . EOL);
115 $invalid = Probe::validDfrn($parms);
117 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);
122 $dfrn_request = $parms['dfrn-request'];
124 $photo = $parms["photo"];
126 // Escape the entire array
127 DBM::esc_array($parms);
129 // Create a contact record on our site for the other person
130 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
131 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
132 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
133 intval(local_user()),
136 dbesc(normalise_link($dfrn_url)),
142 $parms['dfrn-request'],
143 $parms['dfrn-confirm'],
144 $parms['dfrn-notify'],
156 info(t("Introduction complete.") . EOL);
159 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
160 intval(local_user()),
162 $parms['key'] // this was already escaped
164 if (DBM::is_result($r)) {
165 Group::addMember(User::getDefaultGroup($uid, $r[0]["network"]), $r[0]['id']);
168 Contact::updateAvatar($photo, local_user(), $r[0]["id"], true);
171 $forwardurl = System::baseUrl() . "/contacts/" . $r[0]['id'];
173 $forwardurl = System::baseUrl() . "/contacts";
176 // Allow the blocked remote notification to complete
177 if (is_array($contact_record)) {
178 $dfrn_request = $contact_record['request'];
181 if (strlen($dfrn_request) && strlen($confirm_key)) {
182 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
185 // (ignore reply, nothing we can do it failed)
186 // Old: goaway(zrl($dfrn_url));
188 return; // NOTREACHED
192 // invalid/bogus request
193 notice(t('Unrecoverable protocol error.') . EOL);
194 goaway(System::baseUrl());
195 return; // NOTREACHED
202 * We are the requestee. A person from a remote cell has made an introduction
203 * on our profile web page and clicked submit. We will use their DFRN-URL to
204 * figure out how to contact their cell.
206 * Scrape the originating DFRN-URL for everything we need. Create a contact record
207 * and an introduction to show our user next time he/she logs in.
208 * Finally redirect back to the requestor so that their site can record the request.
209 * If our user (the requestee) later confirms this request, a record of it will need
210 * to exist on the requestor's cell in order for the confirmation process to complete..
212 * It's possible that neither the requestor or the requestee are logged in at the moment,
213 * and the requestor does not yet have any credentials to the requestee profile.
215 * Who is the requestee? We've already loaded their profile which means their nickname should be
216 * in $a->argv[1] and we should have their complete info in $a->profile.
219 if (!(is_array($a->profile) && count($a->profile))) {
220 notice(t('Profile unavailable.') . EOL);
224 $nickname = $a->profile['nickname'];
225 $notify_flags = $a->profile['notify-flags'];
226 $uid = $a->profile['uid'];
227 $maxreq = intval($a->profile['maxreq']);
228 $contact_record = null;
234 if (x($_POST, 'dfrn_url')) {
235 // Block friend request spam
237 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
238 dbesc(datetime_convert('UTC', 'UTC', 'now - 24 hours')),
241 if (DBM::is_result($r) && count($r) > $maxreq) {
242 notice(sprintf(t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
243 notice(t('Spam protection measures have been invoked.') . EOL);
244 notice(t('Friends are advised to please try again in 24 hours.') . EOL);
249 /* Cleanup old introductions that remain blocked.
250 * Also remove the contact record, but only if there is no existing relationship
252 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
253 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
254 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
255 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
257 if (DBM::is_result($r)) {
258 foreach ($r as $rr) {
260 q("DELETE FROM `contact` WHERE `id` = %d AND NOT `self`",
264 q("DELETE FROM `intro` WHERE `id` = %d",
270 $real_name = x($_POST, 'realname') ? notags(trim($_POST['realname'])) : '';
272 $url = trim($_POST['dfrn_url']);
274 notice(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 (DBM::is_result($ret)) {
309 if (strlen($ret[0]['issued-id'])) {
310 notice(t('You have already introduced yourself here.') . EOL);
312 } elseif ($ret[0]['rel'] == CONTACT_IS_FRIEND) {
313 notice(sprintf(t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
316 $contact_record = $ret[0];
317 $parms = array('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 = validate_url($url);
333 notice(t('Invalid profile URL.') . EOL);
334 goaway(System::baseUrl() . '/' . $a->cmd);
335 return; // NOTREACHED
338 if (!allowed_url($url)) {
339 notice(t('Disallowed profile URL.') . EOL);
340 goaway(System::baseUrl() . '/' . $a->cmd);
341 return; // NOTREACHED
344 if (blocked_url($url)) {
345 notice(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(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(t('Warning: profile location has no identifiable owner name.') . EOL);
359 if (!x($parms, 'photo')) {
360 notice(t('Warning: profile location has no profile photo.') . EOL);
362 $invalid = Probe::validDfrn($parms);
364 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);
370 $parms['url'] = $url;
371 $parms['issued-id'] = $issued_id;
372 $photo = $parms["photo"];
374 DBM::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(datetime_convert()),
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 (DBM::is_result($r)) {
407 $contact_record = $r[0];
408 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
413 notice(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(datetime_convert())
431 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
433 info(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(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(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(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"] = t('Confirm');
511 dfrn_request_post($a);
514 return; // NOTREACHED
517 $tpl = get_markup_template("dfrn_req_confirm.tpl");
518 $o = replace_macros($tpl, array(
519 '$dfrn_url' => $dfrn_url,
520 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
521 '$hidethem' => t('Hide this contact'),
522 '$hidechecked' => '',
523 '$confirm_key' => $confirm_key,
524 '$welcome' => sprintf(t('Welcome home %s.'), $a->user['username']),
525 '$please' => sprintf(t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
526 '$submit' => 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 (DBM::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 (DBM::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']) : 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),
578 'activity' => intval(PConfig::get($r[0]['uid'], 'system', 'post_newfriend'))
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 dbesc($_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(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->path)) {
615 $myaddr = System::baseUrl() . '/profile/' . $a->user['nickname'];
617 $myaddr = $a->user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
621 $myaddr = get_my_url();
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'] == PAGE_NORMAL) {
631 $tpl = get_markup_template('dfrn_request.tpl');
633 $tpl = get_markup_template('auto_request.tpl');
636 $page_desc = t("Please enter your 'Identity Address' from one of the following supported communications networks:");
638 $invite_desc = sprintf(
639 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>.'),
643 $o = replace_macros($tpl, array(
644 '$header' => t('Friend/Connection Request'),
645 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
646 '$pls_answer' => t('Please answer the following:'),
647 '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'), $a->profile['name']), false, '', array(t('No'), t('Yes'))),
648 '$add_note' => t('Add a personal note:'),
649 '$page_desc' => $page_desc,
650 '$friendica' => t('Friendica'),
651 '$statusnet' => t('GNU Social (Pleroma, Mastodon)'),
652 '$diaspora' => t('Diaspora (Socialhome, Hubzilla)'),
653 '$diasnote' => sprintf(t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'), $target_addr),
654 '$your_address' => t('Your Identity Address:'),
655 '$invite_desc' => $invite_desc,
656 '$submit' => t('Submit Request'),
657 '$cancel' => t('Cancel'),
658 '$nickname' => $a->argv[1],
659 '$name' => $a->profile['name'],
665 return; // Somebody is fishing.