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];
94 if (is_array($contact_record)) {
95 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d", intval($aes_allow), intval($hidden), intval($contact_record['id'])
98 // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
99 $parms = Probe::profile($dfrn_url);
101 if (!count($parms)) {
102 notice(t('Profile location is not valid or does not contain profile information.') . EOL);
105 if (!x($parms, 'fn')) {
106 notice(t('Warning: profile location has no identifiable owner name.') . EOL);
108 if (!x($parms, 'photo')) {
109 notice(t('Warning: profile location has no profile photo.') . EOL);
111 $invalid = Probe::validDfrn($parms);
113 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);
118 $dfrn_request = $parms['dfrn-request'];
120 $photo = $parms["photo"];
122 // Escape the entire array
123 DBM::esc_array($parms);
125 // Create a contact record on our site for the other person
126 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
127 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
128 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
129 intval(local_user()),
132 dbesc(normalise_link($dfrn_url)),
138 $parms['dfrn-request'],
139 $parms['dfrn-confirm'],
140 $parms['dfrn-notify'],
152 info(t("Introduction complete.") . EOL);
155 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
156 intval(local_user()),
158 $parms['key'] // this was already escaped
160 if (DBM::is_result($r)) {
161 Group::addMember(User::getDefaultGroup($uid, $r[0]["network"]), $r[0]['id']);
164 Contact::updateAvatar($photo, local_user(), $r[0]["id"], true);
167 $forwardurl = System::baseUrl() . "/contacts/" . $r[0]['id'];
169 $forwardurl = System::baseUrl() . "/contacts";
172 // Allow the blocked remote notification to complete
173 if (is_array($contact_record)) {
174 $dfrn_request = $contact_record['request'];
177 if (strlen($dfrn_request) && strlen($confirm_key)) {
178 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
181 // (ignore reply, nothing we can do it failed)
182 // Old: goaway(zrl($dfrn_url));
184 return; // NOTREACHED
188 // invalid/bogus request
189 notice(t('Unrecoverable protocol error.') . EOL);
190 goaway(System::baseUrl());
191 return; // NOTREACHED
198 * We are the requestee. A person from a remote cell has made an introduction
199 * on our profile web page and clicked submit. We will use their DFRN-URL to
200 * figure out how to contact their cell.
202 * Scrape the originating DFRN-URL for everything we need. Create a contact record
203 * and an introduction to show our user next time he/she logs in.
204 * Finally redirect back to the requestor so that their site can record the request.
205 * If our user (the requestee) later confirms this request, a record of it will need
206 * to exist on the requestor's cell in order for the confirmation process to complete..
208 * It's possible that neither the requestor or the requestee are logged in at the moment,
209 * and the requestor does not yet have any credentials to the requestee profile.
211 * Who is the requestee? We've already loaded their profile which means their nickname should be
212 * in $a->argv[1] and we should have their complete info in $a->profile.
215 if (!(is_array($a->profile) && count($a->profile))) {
216 notice(t('Profile unavailable.') . EOL);
220 $nickname = $a->profile['nickname'];
221 $notify_flags = $a->profile['notify-flags'];
222 $uid = $a->profile['uid'];
223 $maxreq = intval($a->profile['maxreq']);
224 $contact_record = null;
230 if (x($_POST, 'dfrn_url')) {
231 // Block friend request spam
233 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
234 dbesc(datetime_convert('UTC', 'UTC', 'now - 24 hours')),
237 if (DBM::is_result($r) && count($r) > $maxreq) {
238 notice(sprintf(t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
239 notice(t('Spam protection measures have been invoked.') . EOL);
240 notice(t('Friends are advised to please try again in 24 hours.') . EOL);
245 /* Cleanup old introductions that remain blocked.
246 * Also remove the contact record, but only if there is no existing relationship
248 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
249 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
250 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
251 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
253 if (DBM::is_result($r)) {
254 foreach ($r as $rr) {
256 q("DELETE FROM `contact` WHERE `id` = %d AND NOT `self`",
260 q("DELETE FROM `intro` WHERE `id` = %d",
266 $real_name = x($_POST, 'realname') ? notags(trim($_POST['realname'])) : '';
268 $url = trim($_POST['dfrn_url']);
270 notice(t("Invalid locator") . EOL);
276 // Detect the network
277 $data = Probe::uri($url);
278 $network = $data["network"];
280 // Canonicalise email-style profile locator
281 $url = Probe::webfingerDfrn($url, $hcard);
283 if (substr($url, 0, 5) === 'stat:') {
284 // Every time we detect the remote subscription we define this as OStatus.
285 // We do this even if it is not OStatus.
286 // we only need to pass this through another section of the code.
287 if ($network != NETWORK_DIASPORA) {
288 $network = NETWORK_OSTATUS;
291 $url = substr($url, 5);
293 $network = NETWORK_DFRN;
296 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
298 if ($network === NETWORK_DFRN) {
299 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
304 if (DBM::is_result($ret)) {
305 if (strlen($ret[0]['issued-id'])) {
306 notice(t('You have already introduced yourself here.') . EOL);
308 } elseif ($ret[0]['rel'] == CONTACT_IS_FRIEND) {
309 notice(sprintf(t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
312 $contact_record = $ret[0];
313 $parms = array('dfrn-request' => $ret[0]['request']);
317 $issued_id = random_string();
319 if (is_array($contact_record)) {
320 // There is a contact record but no issued-id, so this
321 // is a reciprocal introduction from a known contact
322 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
324 intval($contact_record['id'])
327 $url = validate_url($url);
329 notice(t('Invalid profile URL.') . EOL);
330 goaway(System::baseUrl() . '/' . $a->cmd);
331 return; // NOTREACHED
334 if (!allowed_url($url)) {
335 notice(t('Disallowed profile URL.') . EOL);
336 goaway(System::baseUrl() . '/' . $a->cmd);
337 return; // NOTREACHED
340 if (blocked_url($url)) {
341 notice(t('Blocked domain') . EOL);
342 goaway(System::baseUrl() . '/' . $a->cmd);
343 return; // NOTREACHED
346 $parms = Probe::profile(($hcard) ? $hcard : $url);
348 if (!count($parms)) {
349 notice(t('Profile location is not valid or does not contain profile information.') . EOL);
350 goaway(System::baseUrl() . '/' . $a->cmd);
352 if (!x($parms, 'fn')) {
353 notice(t('Warning: profile location has no identifiable owner name.') . EOL);
355 if (!x($parms, 'photo')) {
356 notice(t('Warning: profile location has no profile photo.') . EOL);
358 $invalid = Probe::validDfrn($parms);
360 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);
366 $parms['url'] = $url;
367 $parms['issued-id'] = $issued_id;
368 $photo = $parms["photo"];
370 DBM::esc_array($parms);
371 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
372 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `blocked`, `pending` )
373 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
375 dbesc(datetime_convert()),
377 dbesc(normalise_link($url)),
384 $parms['dfrn-request'],
385 $parms['dfrn-confirm'],
386 $parms['dfrn-notify'],
394 // find the contact record we just created
396 $r = q("SELECT `id` FROM `contact`
397 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
402 if (DBM::is_result($r)) {
403 $contact_record = $r[0];
404 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
409 notice(t('Failed to update contact record.') . EOL);
413 $hash = random_string() . (string) time(); // Generate a confirm_key
415 if (is_array($contact_record)) {
416 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
417 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
419 intval($contact_record['id']),
420 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
421 dbesc(notags(trim($_POST['dfrn-request-message']))),
423 dbesc(datetime_convert())
427 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
429 info(t('Your introduction has been sent.') . EOL);
432 // "Homecoming" - send the requestor back to their site to record the introduction.
433 $dfrn_url = bin2hex(System::baseUrl() . '/profile/' . $nickname);
434 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
436 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
437 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
438 . '&confirm_key=' . $hash
439 . (($aes_allow) ? "&aes_allow=1" : "")
442 // END $network === NETWORK_DFRN
443 } elseif (($network != NETWORK_PHANTOM) && ($url != "")) {
445 /* Substitute our user's feed URL into $url template
446 * Send the subscriber home to subscribe
448 // Diaspora needs the uri in the format user@domain.tld
449 // Diaspora will support the remote subscription in a future version
450 if ($network == NETWORK_DIASPORA) {
451 $uri = $nickname . '@' . $a->get_hostname();
453 if ($a->get_path()) {
454 $uri .= '/' . $a->get_path();
457 $uri = urlencode($uri);
459 $uri = System::baseUrl() . '/profile/' . $nickname;
462 $url = str_replace('{uri}', $uri, $url);
465 // END $network != NETWORK_PHANTOM
467 notice(t("Remote subscription can't be done for your network. Please subscribe directly on your system.") . EOL);
473 function dfrn_request_content(App $a)
475 if (($a->argc != 2) || (!count($a->profile))) {
479 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
480 // to send us to the post section to record the introduction.
481 if (x($_GET, 'dfrn_url')) {
483 info(t("Please login to confirm introduction.") . EOL);
484 /* setup the return URL to come back to this page if they use openid */
485 return Login::form();
488 // Edge case, but can easily happen in the wild. This person is authenticated,
489 // but not as the person who needs to deal with this request.
490 if ($a->user['nickname'] != $a->argv[1]) {
491 notice(t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
492 return Login::form();
495 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
496 $aes_allow = x($_GET, 'aes_allow') && $_GET['aes_allow'] == 1 ? 1 : 0;
497 $confirm_key = x($_GET, 'confirm_key') ? $_GET['confirm_key'] : "";
499 // Checking fastlane for validity
500 if (x($_SESSION, "fastlane") && (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
501 $_POST["dfrn_url"] = $dfrn_url;
502 $_POST["confirm_key"] = $confirm_key;
503 $_POST["localconfirm"] = 1;
504 $_POST["hidden-contact"] = 0;
505 $_POST["submit"] = t('Confirm');
507 dfrn_request_post($a);
510 return; // NOTREACHED
513 $tpl = get_markup_template("dfrn_req_confirm.tpl");
514 $o = replace_macros($tpl, array(
515 '$dfrn_url' => $dfrn_url,
516 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
517 '$hidethem' => t('Hide this contact'),
518 '$hidechecked' => '',
519 '$confirm_key' => $confirm_key,
520 '$welcome' => sprintf(t('Welcome home %s.'), $a->user['username']),
521 '$please' => sprintf(t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
522 '$submit' => t('Confirm'),
523 '$uid' => $_SESSION['uid'],
524 '$nickname' => $a->user['nickname'],
525 'dfrn_rawurl' => $_GET['dfrn_url']
528 } elseif ((x($_GET, 'confirm_key')) && strlen($_GET['confirm_key'])) {
529 // we are the requestee and it is now safe to send our user their introduction,
530 // We could just unblock it, but first we have to jump through a few hoops to
531 // send an email, or even to find out if we need to send an email.
532 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
533 dbesc($_GET['confirm_key'])
536 if (DBM::is_result($intro)) {
537 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
538 WHERE `contact`.`id` = %d LIMIT 1",
539 intval($intro[0]['contact-id'])
542 $auto_confirm = false;
544 if (DBM::is_result($r)) {
545 if ($r[0]['page-flags'] != PAGE_NORMAL && $r[0]['page-flags'] != PAGE_PRVGROUP) {
546 $auto_confirm = true;
549 if (!$auto_confirm) {
551 'type' => NOTIFY_INTRO,
552 'notify_flags' => $r[0]['notify-flags'],
553 'language' => $r[0]['language'],
554 'to_name' => $r[0]['username'],
555 'to_email' => $r[0]['email'],
556 'uid' => $r[0]['uid'],
557 'link' => System::baseUrl() . '/notifications/intros',
558 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
559 'source_link' => $r[0]['url'],
560 'source_photo' => $r[0]['photo'],
561 'verb' => ACTIVITY_REQ_FRIEND,
567 require_once 'mod/dfrn_confirm.php';
569 'uid' => $r[0]['uid'],
570 'node' => $r[0]['nickname'],
571 'dfrn_id' => $r[0]['issued-id'],
572 'intro_id' => $intro[0]['id'],
573 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
574 'activity' => intval(PConfig::get($r[0]['uid'], 'system', 'post_newfriend'))
576 dfrn_confirm_post($a, $handsfree);
580 if (!$auto_confirm) {
582 // If we are auto_confirming, this record will have already been nuked
583 // in dfrn_confirm_post()
585 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
586 dbesc($_GET['confirm_key'])
592 return; // NOTREACHED
594 // Normal web request. Display our user's introduction form.
595 if ((Config::get('system', 'block_public')) && (!local_user()) && (!remote_user())) {
596 if (!Config::get('system', 'local_block')) {
597 notice(t('Public access denied.') . EOL);
602 // Try to auto-fill the profile address
603 // At first look if an address was provided
604 // Otherwise take the local address
605 if (x($_GET, 'addr') && ($_GET['addr'] != "")) {
606 $myaddr = hex2bin($_GET['addr']);
607 } elseif (x($_GET, 'address') && ($_GET['address'] != "")) {
608 $myaddr = $_GET['address'];
609 } elseif (local_user()) {
610 if (strlen($a->path)) {
611 $myaddr = System::baseUrl() . '/profile/' . $a->user['nickname'];
613 $myaddr = $a->user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
617 $myaddr = get_my_url();
620 $target_addr = $a->profile['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
622 /* The auto_request form only has the profile address
623 * because nobody is going to read the comments and
624 * it doesn't matter if they know you or not.
626 if ($a->profile['page-flags'] == PAGE_NORMAL) {
627 $tpl = get_markup_template('dfrn_request.tpl');
629 $tpl = get_markup_template('auto_request.tpl');
632 $page_desc = t("Please enter your 'Identity Address' from one of the following supported communications networks:");
634 $invite_desc = sprintf(
635 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>.'),
639 $o = replace_macros($tpl, array(
640 '$header' => t('Friend/Connection Request'),
641 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
642 '$pls_answer' => t('Please answer the following:'),
643 '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'), $a->profile['name']), false, '', array(t('No'), t('Yes'))),
644 '$add_note' => t('Add a personal note:'),
645 '$page_desc' => $page_desc,
646 '$friendica' => t('Friendica'),
647 '$statusnet' => t('GNU Social (Pleroma, Mastodon)'),
648 '$diaspora' => t('Diaspora (Socialhome, Hubzilla)'),
649 '$diasnote' => sprintf(t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'), $target_addr),
650 '$your_address' => t('Your Identity Address:'),
651 '$invite_desc' => $invite_desc,
652 '$submit' => t('Submit Request'),
653 '$cancel' => t('Cancel'),
654 '$nickname' => $a->argv[1],
655 '$name' => $a->profile['name'],
661 return; // Somebody is fishing.