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 if (! validate_url($url)) {
381 notice( t('Invalid profile URL.') . EOL);
382 goaway(System::baseUrl() . '/' . $a->cmd);
383 return; // NOTREACHED
386 if (! allowed_url($url)) {
387 notice( t('Disallowed profile URL.') . EOL);
388 goaway(System::baseUrl() . '/' . $a->cmd);
389 return; // NOTREACHED
392 if (blocked_url($url)) {
393 notice( t('Blocked domain') . EOL);
394 goaway(System::baseUrl() . '/' . $a->cmd);
395 return; // NOTREACHED
398 $parms = Probe::profile(($hcard) ? $hcard : $url);
400 if (! count($parms)) {
401 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
402 goaway(System::baseUrl() . '/' . $a->cmd);
405 if (! x($parms,'fn')) {
406 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
408 if (! x($parms,'photo')) {
409 notice( t('Warning: profile location has no profile photo.') . EOL );
411 $invalid = Probe::validDfrn($parms);
413 notice( sprintf( tt("%d required parameter was not found at the given location",
414 "%d required parameters were not found at the given location",
415 $invalid), $invalid) . EOL );
422 $parms['url'] = $url;
423 $parms['issued-id'] = $issued_id;
424 $photo = $parms["photo"];
426 DBM::esc_array($parms);
427 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
428 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `blocked`, `pending` )
429 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
431 dbesc(datetime_convert()),
433 dbesc(normalise_link($url)),
440 $parms['dfrn-request'],
441 $parms['dfrn-confirm'],
442 $parms['dfrn-notify'],
450 // find the contact record we just created
452 $r = q("SELECT `id` FROM `contact`
453 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
458 if (DBM::is_result($r)) {
459 $contact_record = $r[0];
460 Contact::updateAvatar($photo, $uid, $contact_record["id"], true);
466 notice( t('Failed to update contact record.') . EOL );
470 $hash = random_string() . (string) time(); // Generate a confirm_key
472 if (is_array($contact_record)) {
473 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
474 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
476 intval($contact_record['id']),
477 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
478 dbesc(notags(trim($_POST['dfrn-request-message']))),
480 dbesc(datetime_convert())
484 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
487 info( t('Your introduction has been sent.') . EOL );
490 // "Homecoming" - send the requestor back to their site to record the introduction.
492 $dfrn_url = bin2hex(System::baseUrl() . '/profile/' . $nickname);
493 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
495 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
496 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
497 . '&confirm_key=' . $hash
498 . (($aes_allow) ? "&aes_allow=1" : "")
501 // END $network === NETWORK_DFRN
502 } elseif (($network != NETWORK_PHANTOM) && ($url != "")) {
506 * Substitute our user's feed URL into $url template
507 * Send the subscriber home to subscribe
511 // Diaspora needs the uri in the format user@domain.tld
512 // Diaspora will support the remote subscription in a future version
513 if ($network == NETWORK_DIASPORA) {
514 $uri = $nickname.'@'.$a->get_hostname();
517 $uri .= '/'.$a->get_path();
519 $uri = urlencode($uri);
521 $uri = System::baseUrl().'/profile/'.$nickname;
524 $url = str_replace('{uri}', $uri, $url);
527 // END $network != NETWORK_PHANTOM
529 notice(t("Remote subscription can't be done for your network. Please subscribe directly on your system.").EOL);
537 function dfrn_request_content(App $a) {
539 if (($a->argc != 2) || (! count($a->profile))) {
544 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
545 // to send us to the post section to record the introduction.
547 if (x($_GET,'dfrn_url')) {
549 if (! local_user()) {
550 info( t("Please login to confirm introduction.") . EOL );
551 /* setup the return URL to come back to this page if they use openid */
552 $_SESSION['return_url'] = $a->query_string;
556 // Edge case, but can easily happen in the wild. This person is authenticated,
557 // but not as the person who needs to deal with this request.
559 if ($a->user['nickname'] != $a->argv[1]) {
560 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
564 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
565 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
566 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
568 // Checking fastlane for validity
569 if (x($_SESSION, "fastlane") && (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
570 $_POST["dfrn_url"] = $dfrn_url;
571 $_POST["confirm_key"] = $confirm_key;
572 $_POST["localconfirm"] = 1;
573 $_POST["hidden-contact"] = 0;
574 $_POST["submit"] = t('Confirm');
576 dfrn_request_post($a);
579 return; // NOTREACHED
582 $tpl = get_markup_template("dfrn_req_confirm.tpl");
583 $o = replace_macros($tpl,array(
584 '$dfrn_url' => $dfrn_url,
585 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
586 '$hidethem' => t('Hide this contact'),
587 '$hidechecked' => '',
588 '$confirm_key' => $confirm_key,
589 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
590 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
591 '$submit' => t('Confirm'),
592 '$uid' => $_SESSION['uid'],
593 '$nickname' => $a->user['nickname'],
594 'dfrn_rawurl' => $_GET['dfrn_url']
599 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
601 // we are the requestee and it is now safe to send our user their introduction,
602 // We could just unblock it, but first we have to jump through a few hoops to
603 // send an email, or even to find out if we need to send an email.
605 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
606 dbesc($_GET['confirm_key'])
609 if (DBM::is_result($intro)) {
611 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
612 WHERE `contact`.`id` = %d LIMIT 1",
613 intval($intro[0]['contact-id'])
616 $auto_confirm = false;
618 if (DBM::is_result($r)) {
619 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
620 $auto_confirm = true;
622 if(! $auto_confirm) {
625 'type' => NOTIFY_INTRO,
626 'notify_flags' => $r[0]['notify-flags'],
627 'language' => $r[0]['language'],
628 'to_name' => $r[0]['username'],
629 'to_email' => $r[0]['email'],
630 'uid' => $r[0]['uid'],
631 'link' => System::baseUrl() . '/notifications/intros',
632 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
633 'source_link' => $r[0]['url'],
634 'source_photo' => $r[0]['photo'],
635 'verb' => ACTIVITY_REQ_FRIEND,
641 require_once 'mod/dfrn_confirm.php';
643 'uid' => $r[0]['uid'],
644 'node' => $r[0]['nickname'],
645 'dfrn_id' => $r[0]['issued-id'],
646 'intro_id' => $intro[0]['id'],
647 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
648 'activity' => intval(PConfig::get($r[0]['uid'],'system','post_newfriend'))
650 dfrn_confirm_post($a,$handsfree);
655 if(! $auto_confirm) {
657 // If we are auto_confirming, this record will have already been nuked
658 // in dfrn_confirm_post()
660 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
661 dbesc($_GET['confirm_key'])
667 return; // NOTREACHED
672 * Normal web request. Display our user's introduction form.
675 if((Config::get('system','block_public')) && (! local_user()) && (! remote_user())) {
676 if(! Config::get('system','local_block')) {
677 notice( t('Public access denied.') . EOL);
684 * Try to auto-fill the profile address
687 // At first look if an address was provided
688 // Otherwise take the local address
689 if (x($_GET,'addr') && ($_GET['addr'] != "")) {
690 $myaddr = hex2bin($_GET['addr']);
691 } elseif (x($_GET,'address') && ($_GET['address'] != "")) {
692 $myaddr = $_GET['address'];
693 } elseif (local_user()) {
694 if (strlen($a->path)) {
695 $myaddr = System::baseUrl() . '/profile/' . $a->user['nickname'];
697 $myaddr = $a->user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(),'://') + 3 );
701 $myaddr = get_my_url();
704 $target_addr = $a->profile['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(),'://') + 3 );
709 * The auto_request form only has the profile address
710 * because nobody is going to read the comments and
711 * it doesn't matter if they know you or not.
715 if ($a->profile['page-flags'] == PAGE_NORMAL) {
716 $tpl = get_markup_template('dfrn_request.tpl');
718 $tpl = get_markup_template('auto_request.tpl');
721 $page_desc = t("Please enter your 'Identity Address' from one of the following supported communications networks:");
723 $invite_desc = sprintf(
724 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>.'),
728 $o = replace_macros($tpl,array(
729 '$header' => t('Friend/Connection Request'),
730 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@gnusocial.de'),
731 '$pls_answer' => t('Please answer the following:'),
732 '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'),$a->profile['name']), false, '', array(t('No'), t('Yes'))),
733 /*'$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
736 '$add_note' => t('Add a personal note:'),
737 '$page_desc' => $page_desc,
738 '$friendica' => t('Friendica'),
739 '$statusnet' => t('GNU Social (Pleroma, Mastodon)'),
740 '$diaspora' => t('Diaspora (Socialhome, Hubzilla)'),
741 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
742 '$your_address' => t('Your Identity Address:'),
743 '$invite_desc' => $invite_desc,
744 '$submit' => t('Submit Request'),
745 '$cancel' => t('Cancel'),
746 '$nickname' => $a->argv[1],
747 '$name' => $a->profile['name'],
753 return; // Somebody is fishing.