3 * @file mod/dfrn_request.php
4 * @brief Module: dfrn_request
6 * Purpose: Handles communication associated with the issuance of
9 * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
10 * You also find a graphic which describes the confirmation process at
11 * https://github.com/friendica/friendica/blob/master/spec/dfrn2_contact_request.png
14 use Friendica\Core\Config;
15 use Friendica\Core\PConfig;
16 use Friendica\Core\System;
17 use Friendica\Database\DBM;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Group;
20 use Friendica\Model\User;
21 use Friendica\Network\Probe;
23 require_once 'include/enotify.php';
25 function dfrn_request_init(App $a)
30 profile_load($a, $which);
36 * Function: dfrn_request_post
39 * Handles multiple scenarios.
42 * Clicking 'submit' on a friend request page.
45 * Following Scenario 1, we are brought back to our home site
46 * in order to link our friend request with our own server cell.
47 * After logging in, we click 'submit' to approve the linkage.
50 function dfrn_request_post(App $a) {
52 if(($a->argc != 2) || (! count($a->profile))) {
53 logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
58 if(x($_POST, 'cancel')) {
59 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:
71 if((x($_POST,'localconfirm')) && ($_POST['localconfirm'] == 1)) {
74 * Ensure this is a valid request
77 if(local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST,'dfrn_url'))) {
80 $dfrn_url = notags(trim($_POST['dfrn_url']));
81 $aes_allow = (((x($_POST,'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
82 $confirm_key = ((x($_POST,'confirm_key')) ? $_POST['confirm_key'] : "");
83 $hidden = ((x($_POST,'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
84 $contact_record = null;
91 * Lookup the contact based on their URL (which is the only unique thing we have at the moment)
94 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
96 dbesc(normalise_link($dfrn_url))
99 if (DBM::is_result($r)) {
100 if(strlen($r[0]['dfrn-id'])) {
103 * We don't need to be here. It has already happened.
106 notice( t("This introduction has already been accepted.") . EOL );
110 $contact_record = $r[0];
113 if(is_array($contact_record)) {
114 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
117 intval($contact_record['id'])
123 * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
126 $parms = Probe::profile($dfrn_url);
128 if (! count($parms)) {
129 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
133 if (! x($parms,'fn')) {
134 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
136 if (! x($parms,'photo')) {
137 notice( t('Warning: profile location has no profile photo.') . EOL );
139 $invalid = Probe::validDfrn($parms);
141 notice( sprintf( tt("%d required parameter was not found at the given location",
142 "%d required parameters were not found at the given location",
143 $invalid), $invalid) . EOL );
148 $dfrn_request = $parms['dfrn-request'];
150 $photo = $parms["photo"];
152 // Escape the entire array
153 DBM::esc_array($parms);
156 * Create a contact record on our site for the other person
159 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
160 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
161 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
162 intval(local_user()),
165 dbesc(normalise_link($dfrn_url)),
171 $parms['dfrn-request'],
172 $parms['dfrn-confirm'],
173 $parms['dfrn-notify'],
185 info( t("Introduction complete.") . EOL);
188 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
189 intval(local_user()),
191 $parms['key'] // this was already escaped
193 if (DBM::is_result($r)) {
194 Group::addMember(User::getDefaultGroup($uid, $r[0]["network"]), $r[0]['id']);
197 Contact::updateAvatar($photo, local_user(), $r[0]["id"], true);
200 $forwardurl = System::baseUrl()."/contacts/".$r[0]['id'];
202 $forwardurl = System::baseUrl()."/contacts";
206 * Allow the blocked remote notification to complete
209 if (is_array($contact_record)) {
210 $dfrn_request = $contact_record['request'];
213 if (strlen($dfrn_request) && strlen($confirm_key)) {
214 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
217 // (ignore reply, nothing we can do it failed)
219 // Old: goaway(zrl($dfrn_url));
221 return; // NOTREACHED
227 // invalid/bogus request
229 notice( t('Unrecoverable protocol error.') . EOL );
230 goaway(System::baseUrl());
231 return; // NOTREACHED
238 * We are the requestee. A person from a remote cell has made an introduction
239 * on our profile web page and clicked submit. We will use their DFRN-URL to
240 * figure out how to contact their cell.
242 * Scrape the originating DFRN-URL for everything we need. Create a contact record
243 * and an introduction to show our user next time he/she logs in.
244 * Finally redirect back to the requestor so that their site can record the request.
245 * If our user (the requestee) later confirms this request, a record of it will need
246 * to exist on the requestor's cell in order for the confirmation process to complete..
248 * It's possible that neither the requestor or the requestee are logged in at the moment,
249 * and the requestor does not yet have any credentials to the requestee profile.
251 * Who is the requestee? We've already loaded their profile which means their nickname should be
252 * in $a->argv[1] and we should have their complete info in $a->profile.
256 if(! (is_array($a->profile) && count($a->profile))) {
257 notice( t('Profile unavailable.') . EOL);
261 $nickname = $a->profile['nickname'];
262 $notify_flags = $a->profile['notify-flags'];
263 $uid = $a->profile['uid'];
264 $maxreq = intval($a->profile['maxreq']);
265 $contact_record = null;
272 if( x($_POST,'dfrn_url')) {
275 * Block friend request spam
279 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
280 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
283 if (DBM::is_result($r) && count($r) > $maxreq) {
284 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
285 notice( t('Spam protection measures have been invoked.') . EOL);
286 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
293 * Cleanup old introductions that remain blocked.
294 * Also remove the contact record, but only if there is no existing relationship
297 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
298 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
299 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
300 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
302 if (DBM::is_result($r)) {
303 foreach ($r as $rr) {
305 q("DELETE FROM `contact` WHERE `id` = %d AND NOT `self`",
309 q("DELETE FROM `intro` WHERE `id` = %d",
315 $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
317 $url = trim($_POST['dfrn_url']);
319 notice( t("Invalid locator") . EOL );
325 // Detect the network
326 $data = Probe::uri($url);
327 $network = $data["network"];
329 // Canonicalise email-style profile locator
330 $url = Probe::webfingerDfrn($url,$hcard);
332 if (substr($url,0,5) === 'stat:') {
334 // Every time we detect the remote subscription we define this as OStatus.
335 // We do this even if it is not OStatus.
336 // we only need to pass this through another section of the code.
337 if ($network != NETWORK_DIASPORA) {
338 $network = NETWORK_OSTATUS;
341 $url = substr($url,5);
343 $network = NETWORK_DFRN;
346 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
348 if($network === NETWORK_DFRN) {
349 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
354 if (DBM::is_result($ret)) {
355 if(strlen($ret[0]['issued-id'])) {
356 notice( t('You have already introduced yourself here.') . EOL );
359 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
360 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
364 $contact_record = $ret[0];
365 $parms = array('dfrn-request' => $ret[0]['request']);
369 $issued_id = random_string();
371 if(is_array($contact_record)) {
372 // There is a contact record but no issued-id, so this
373 // is a reciprocal introduction from a known contact
374 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
376 intval($contact_record['id'])
380 $url = validate_url($url);
382 notice( t('Invalid profile URL.') . EOL);
383 goaway(System::baseUrl() . '/' . $a->cmd);
384 return; // NOTREACHED
387 if (! allowed_url($url)) {
388 notice( t('Disallowed profile URL.') . EOL);
389 goaway(System::baseUrl() . '/' . $a->cmd);
390 return; // NOTREACHED
393 if (blocked_url($url)) {
394 notice( t('Blocked domain') . EOL);
395 goaway(System::baseUrl() . '/' . $a->cmd);
396 return; // NOTREACHED
399 $parms = Probe::profile(($hcard) ? $hcard : $url);
401 if (! count($parms)) {
402 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
403 goaway(System::baseUrl() . '/' . $a->cmd);
406 if (! x($parms,'fn')) {
407 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
409 if (! x($parms,'photo')) {
410 notice( t('Warning: profile location has no profile photo.') . EOL );
412 $invalid = Probe::validDfrn($parms);
414 notice( sprintf( tt("%d required parameter was not found at the given location",
415 "%d required parameters were not found at the given location",
416 $invalid), $invalid) . EOL );
423 $parms['url'] = $url;
424 $parms['issued-id'] = $issued_id;
425 $photo = $parms["photo"];
427 DBM::esc_array($parms);
428 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
429 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `blocked`, `pending` )
430 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
432 dbesc(datetime_convert()),
434 dbesc(normalise_link($url)),
441 $parms['dfrn-request'],
442 $parms['dfrn-confirm'],
443 $parms['dfrn-notify'],
451 // find the contact record we just created
453 $r = q("SELECT `id` FROM `contact`
454 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
459 if (DBM::is_result($r)) {
460 $contact_record = $r[0];
461 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
467 notice( t('Failed to update contact record.') . EOL );
471 $hash = random_string() . (string) time(); // Generate a confirm_key
473 if (is_array($contact_record)) {
474 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
475 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
477 intval($contact_record['id']),
478 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
479 dbesc(notags(trim($_POST['dfrn-request-message']))),
481 dbesc(datetime_convert())
485 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
488 info( t('Your introduction has been sent.') . EOL );
491 // "Homecoming" - send the requestor back to their site to record the introduction.
493 $dfrn_url = bin2hex(System::baseUrl() . '/profile/' . $nickname);
494 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
496 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
497 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
498 . '&confirm_key=' . $hash
499 . (($aes_allow) ? "&aes_allow=1" : "")
502 // END $network === NETWORK_DFRN
503 } elseif (($network != NETWORK_PHANTOM) && ($url != "")) {
507 * Substitute our user's feed URL into $url template
508 * Send the subscriber home to subscribe
512 // Diaspora needs the uri in the format user@domain.tld
513 // Diaspora will support the remote subscription in a future version
514 if ($network == NETWORK_DIASPORA) {
515 $uri = $nickname.'@'.$a->get_hostname();
518 $uri .= '/'.$a->get_path();
520 $uri = urlencode($uri);
522 $uri = System::baseUrl().'/profile/'.$nickname;
525 $url = str_replace('{uri}', $uri, $url);
528 // END $network != NETWORK_PHANTOM
530 notice(t("Remote subscription can't be done for your network. Please subscribe directly on your system.").EOL);
538 function dfrn_request_content(App $a) {
540 if (($a->argc != 2) || (! count($a->profile))) {
545 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
546 // to send us to the post section to record the introduction.
548 if (x($_GET,'dfrn_url')) {
550 if (! local_user()) {
551 info( t("Please login to confirm introduction.") . EOL );
552 /* setup the return URL to come back to this page if they use openid */
553 $_SESSION['return_url'] = $a->query_string;
557 // Edge case, but can easily happen in the wild. This person is authenticated,
558 // but not as the person who needs to deal with this request.
560 if ($a->user['nickname'] != $a->argv[1]) {
561 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
565 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
566 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
567 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
569 // Checking fastlane for validity
570 if (x($_SESSION, "fastlane") && (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
571 $_POST["dfrn_url"] = $dfrn_url;
572 $_POST["confirm_key"] = $confirm_key;
573 $_POST["localconfirm"] = 1;
574 $_POST["hidden-contact"] = 0;
575 $_POST["submit"] = t('Confirm');
577 dfrn_request_post($a);
580 return; // NOTREACHED
583 $tpl = get_markup_template("dfrn_req_confirm.tpl");
584 $o = replace_macros($tpl,array(
585 '$dfrn_url' => $dfrn_url,
586 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
587 '$hidethem' => t('Hide this contact'),
588 '$hidechecked' => '',
589 '$confirm_key' => $confirm_key,
590 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
591 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
592 '$submit' => t('Confirm'),
593 '$uid' => $_SESSION['uid'],
594 '$nickname' => $a->user['nickname'],
595 'dfrn_rawurl' => $_GET['dfrn_url']
600 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
602 // we are the requestee and it is now safe to send our user their introduction,
603 // We could just unblock it, but first we have to jump through a few hoops to
604 // send an email, or even to find out if we need to send an email.
606 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
607 dbesc($_GET['confirm_key'])
610 if (DBM::is_result($intro)) {
612 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
613 WHERE `contact`.`id` = %d LIMIT 1",
614 intval($intro[0]['contact-id'])
617 $auto_confirm = false;
619 if (DBM::is_result($r)) {
620 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
621 $auto_confirm = true;
623 if(! $auto_confirm) {
626 'type' => NOTIFY_INTRO,
627 'notify_flags' => $r[0]['notify-flags'],
628 'language' => $r[0]['language'],
629 'to_name' => $r[0]['username'],
630 'to_email' => $r[0]['email'],
631 'uid' => $r[0]['uid'],
632 'link' => System::baseUrl() . '/notifications/intros',
633 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
634 'source_link' => $r[0]['url'],
635 'source_photo' => $r[0]['photo'],
636 'verb' => ACTIVITY_REQ_FRIEND,
642 require_once 'mod/dfrn_confirm.php';
644 'uid' => $r[0]['uid'],
645 'node' => $r[0]['nickname'],
646 'dfrn_id' => $r[0]['issued-id'],
647 'intro_id' => $intro[0]['id'],
648 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
649 'activity' => intval(PConfig::get($r[0]['uid'],'system','post_newfriend'))
651 dfrn_confirm_post($a,$handsfree);
656 if(! $auto_confirm) {
658 // If we are auto_confirming, this record will have already been nuked
659 // in dfrn_confirm_post()
661 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
662 dbesc($_GET['confirm_key'])
668 return; // NOTREACHED
673 * Normal web request. Display our user's introduction form.
676 if((Config::get('system','block_public')) && (! local_user()) && (! remote_user())) {
677 if(! Config::get('system','local_block')) {
678 notice( t('Public access denied.') . EOL);
685 * Try to auto-fill the profile address
688 // At first look if an address was provided
689 // Otherwise take the local address
690 if (x($_GET,'addr') && ($_GET['addr'] != "")) {
691 $myaddr = hex2bin($_GET['addr']);
692 } elseif (x($_GET,'address') && ($_GET['address'] != "")) {
693 $myaddr = $_GET['address'];
694 } elseif (local_user()) {
695 if (strlen($a->path)) {
696 $myaddr = System::baseUrl() . '/profile/' . $a->user['nickname'];
698 $myaddr = $a->user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(),'://') + 3 );
702 $myaddr = get_my_url();
705 $target_addr = $a->profile['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(),'://') + 3 );
710 * The auto_request form only has the profile address
711 * because nobody is going to read the comments and
712 * it doesn't matter if they know you or not.
716 if ($a->profile['page-flags'] == PAGE_NORMAL) {
717 $tpl = get_markup_template('dfrn_request.tpl');
719 $tpl = get_markup_template('auto_request.tpl');
722 $page_desc = t("Please enter your 'Identity Address' from one of the following supported communications networks:");
724 $invite_desc = sprintf(
725 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>.'),
729 $o = replace_macros($tpl,array(
730 '$header' => t('Friend/Connection Request'),
731 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
732 '$pls_answer' => t('Please answer the following:'),
733 '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'),$a->profile['name']), false, '', array(t('No'), t('Yes'))),
734 /*'$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
737 '$add_note' => t('Add a personal note:'),
738 '$page_desc' => $page_desc,
739 '$friendica' => t('Friendica'),
740 '$statusnet' => t('GNU Social (Pleroma, Mastodon)'),
741 '$diaspora' => t('Diaspora (Socialhome, Hubzilla)'),
742 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
743 '$your_address' => t('Your Identity Address:'),
744 '$invite_desc' => $invite_desc,
745 '$submit' => t('Submit Request'),
746 '$cancel' => t('Cancel'),
747 '$nickname' => $a->argv[1],
748 '$name' => $a->profile['name'],
754 return; // Somebody is fishing.