7 * Purpose: Handles communication associated with the issuance of
12 require_once('include/enotify.php');
13 require_once('include/Scrape.php');
15 if(! function_exists('dfrn_request_init')) {
16 function dfrn_request_init(&$a) {
21 profile_load($a,$which);
27 * Function: dfrn_request_post
30 * Handles multiple scenarios.
33 * Clicking 'submit' on a friend request page.
36 * Following Scenario 1, we are brought back to our home site
37 * in order to link our friend request with our own server cell.
38 * After logging in, we click 'submit' to approve the linkage.
42 if(! function_exists('dfrn_request_post')) {
43 function dfrn_request_post(&$a) {
45 if(($a->argc != 2) || (! count($a->profile))) {
46 logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
51 if(x($_POST, 'cancel')) {
58 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
59 * to confirm the request, and then we've clicked submit (perhaps after logging in).
60 * That brings us here:
64 if((x($_POST,'localconfirm')) && ($_POST['localconfirm'] == 1)) {
67 * Ensure this is a valid request
70 if(local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST,'dfrn_url'))) {
73 $dfrn_url = notags(trim($_POST['dfrn_url']));
74 $aes_allow = (((x($_POST,'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
75 $confirm_key = ((x($_POST,'confirm_key')) ? $_POST['confirm_key'] : "");
76 $hidden = ((x($_POST,'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
77 $contact_record = null;
82 * Lookup the contact based on their URL (which is the only unique thing we have at the moment)
85 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND (`url` = '%s' OR `nurl` = '%s') AND `self` = 0 LIMIT 1",
88 dbesc(normalise_link($dfrn_url))
92 if(strlen($r[0]['dfrn-id'])) {
95 * We don't need to be here. It has already happened.
98 notice( t("This introduction has already been accepted.") . EOL );
102 $contact_record = $r[0];
105 if(is_array($contact_record)) {
106 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
109 intval($contact_record['id'])
115 * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
118 $parms = scrape_dfrn($dfrn_url);
120 if(! count($parms)) {
121 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
126 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
127 if(! x($parms,'photo'))
128 notice( t('Warning: profile location has no profile photo.') . EOL );
129 $invalid = validate_dfrn($parms);
131 notice( sprintf( tt("%d required parameter was not found at the given location",
132 "%d required parameters were not found at the given location",
133 $invalid), $invalid) . EOL );
138 $dfrn_request = $parms['dfrn-request'];
140 /********* Escape the entire array ********/
144 /******************************************/
147 * Create a contact record on our site for the other person
150 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
151 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`)
152 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
153 intval(local_user()),
156 dbesc(normalise_link($dfrn_url)),
162 $parms['dfrn-request'],
163 $parms['dfrn-confirm'],
164 $parms['dfrn-notify'],
174 info( t("Introduction complete.") . EOL);
177 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
178 intval(local_user()),
180 $parms['key'] // this was already escaped
183 $def_gid = get_default_group(local_user(), $r[0]["network"]);
184 if(intval($def_gid)) {
185 require_once('include/group.php');
186 group_add_member(local_user(), '', $r[0]['id'], $def_gid);
188 $forwardurl = $a->get_baseurl()."/contacts/".$r[0]['id'];
190 $forwardurl = $a->get_baseurl()."/contacts";
193 * Allow the blocked remote notification to complete
196 if(is_array($contact_record))
197 $dfrn_request = $contact_record['request'];
199 if(strlen($dfrn_request) && strlen($confirm_key))
200 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
202 // (ignore reply, nothing we can do it failed)
204 // Old: goaway(zrl($dfrn_url));
206 return; // NOTREACHED
212 // invalid/bogus request
214 notice( t('Unrecoverable protocol error.') . EOL );
216 return; // NOTREACHED
223 * We are the requestee. A person from a remote cell has made an introduction
224 * on our profile web page and clicked submit. We will use their DFRN-URL to
225 * figure out how to contact their cell.
227 * Scrape the originating DFRN-URL for everything we need. Create a contact record
228 * and an introduction to show our user next time he/she logs in.
229 * Finally redirect back to the requestor so that their site can record the request.
230 * If our user (the requestee) later confirms this request, a record of it will need
231 * to exist on the requestor's cell in order for the confirmation process to complete..
233 * It's possible that neither the requestor or the requestee are logged in at the moment,
234 * and the requestor does not yet have any credentials to the requestee profile.
236 * Who is the requestee? We've already loaded their profile which means their nickname should be
237 * in $a->argv[1] and we should have their complete info in $a->profile.
241 if(! (is_array($a->profile) && count($a->profile))) {
242 notice( t('Profile unavailable.') . EOL);
246 $nickname = $a->profile['nickname'];
247 $notify_flags = $a->profile['notify-flags'];
248 $uid = $a->profile['uid'];
249 $maxreq = intval($a->profile['maxreq']);
250 $contact_record = null;
255 if( x($_POST,'dfrn_url')) {
258 * Block friend request spam
262 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
263 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
266 if(count($r) > $maxreq) {
267 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
268 notice( t('Spam protection measures have been invoked.') . EOL);
269 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
276 * Cleanup old introductions that remain blocked.
277 * Also remove the contact record, but only if there is no existing relationship
278 * Do not remove email contacts as these may be awaiting email verification
281 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
282 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
283 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
284 AND `contact`.`network` != '%s'
285 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ",
291 q("DELETE FROM `contact` WHERE `id` = %d",
295 q("DELETE FROM `intro` WHERE `id` = %d",
303 * Cleanup any old email intros - which will have a greater lifetime
306 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
307 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
308 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
309 AND `contact`.`network` = '%s'
310 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ",
316 q("DELETE FROM `contact` WHERE `id` = %d",
320 q("DELETE FROM `intro` WHERE `id` = %d",
326 $email_follow = (x($_POST,'email_follow') ? intval($_POST['email_follow']) : 0);
327 $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
329 $url = trim($_POST['dfrn_url']);
331 notice( t("Invalid locator") . EOL );
339 if(! validate_email($url)) {
340 notice( t('Invalid email address.') . EOL);
345 $name = ($realname) ? $realname : $addr;
346 $nick = substr($addr,0,strpos($addr,'@'));
347 $url = 'http://' . substr($addr,strpos($addr,'@') + 1);
348 $nurl = normalise_url($host);
349 $poll = 'email ' . random_string();
350 $notify = 'smtp ' . random_string();
353 $network = NETWORK_MAIL2;
354 $rel = CONTACT_IS_FOLLOWER;
356 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
357 if(get_config('system','dfrn_only'))
360 if(! $mail_disabled) {
362 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
367 notice( t('This account has not been configured for email. Request failed.') . EOL);
372 $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
373 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
375 dbesc(datetime_convert()),
389 $r = q("SELECT `id`, `network` FROM `contact` WHERE `poll` = '%s' AND `uid` = %d LIMIT 1",
394 $contact_id = $r[0]['id'];
396 $def_gid = get_default_group($uid, $r[0]["network"]);
397 if (intval($def_gid)) {
398 require_once('include/group.php');
399 group_add_member($uid, '', $contact_id, $def_gid);
402 $photo = avatar_img($addr);
404 $r = q("UPDATE `contact` SET
410 `avatar-date` = '%s',
417 dbesc(datetime_convert()),
418 dbesc(datetime_convert()),
419 dbesc(datetime_convert()),
424 // contact is created. Now create an introduction
426 $hash = random_string();
428 $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
429 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
432 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
433 dbesc(notags(trim($_POST['dfrn-request-message']))),
435 dbesc(datetime_convert()),
439 // Next send an email verify form to the requestor.
442 // Detect the network
443 $data = probe_url($url);
444 $network = $data["network"];
446 // Canonicalise email-style profile locator
447 $url = webfinger_dfrn($url,$hcard);
449 if (substr($url,0,5) === 'stat:') {
451 // Every time we detect the remote subscription we define this as OStatus.
452 // We do this even if it is not OStatus.
453 // we only need to pass this through another section of the code.
454 if ($network != NETWORK_DIASPORA)
455 $network = NETWORK_OSTATUS;
457 $url = substr($url,5);
459 $network = NETWORK_DFRN;
462 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
464 if($network === NETWORK_DFRN) {
465 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
471 if(strlen($ret[0]['issued-id'])) {
472 notice( t('You have already introduced yourself here.') . EOL );
475 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
476 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
480 $contact_record = $ret[0];
481 $parms = array('dfrn-request' => $ret[0]['request']);
485 $issued_id = random_string();
487 if(is_array($contact_record)) {
488 // There is a contact record but no issued-id, so this
489 // is a reciprocal introduction from a known contact
490 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
492 intval($contact_record['id'])
496 if(! validate_url($url)) {
497 notice( t('Invalid profile URL.') . EOL);
498 goaway($a->get_baseurl() . '/' . $a->cmd);
499 return; // NOTREACHED
502 if(! allowed_url($url)) {
503 notice( t('Disallowed profile URL.') . EOL);
504 goaway($a->get_baseurl() . '/' . $a->cmd);
505 return; // NOTREACHED
509 require_once('include/Scrape.php');
511 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
513 if(! count($parms)) {
514 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
515 goaway($a->get_baseurl() . '/' . $a->cmd);
519 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
520 if(! x($parms,'photo'))
521 notice( t('Warning: profile location has no profile photo.') . EOL );
522 $invalid = validate_dfrn($parms);
524 notice( sprintf( tt("%d required parameter was not found at the given location",
525 "%d required parameters were not found at the given location",
526 $invalid), $invalid) . EOL );
533 $parms['url'] = $url;
534 $parms['issued-id'] = $issued_id;
538 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
539 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
540 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
542 dbesc(datetime_convert()),
544 dbesc(normalise_link($parms['url'])),
551 $parms['dfrn-request'],
552 $parms['dfrn-confirm'],
553 $parms['dfrn-notify'],
559 // find the contact record we just created
561 $r = q("SELECT `id` FROM `contact`
562 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
568 $contact_record = $r[0];
573 notice( t('Failed to update contact record.') . EOL );
577 $hash = random_string() . (string) time(); // Generate a confirm_key
579 if(is_array($contact_record)) {
580 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
581 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
583 intval($contact_record['id']),
584 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
585 dbesc(notags(trim($_POST['dfrn-request-message']))),
587 dbesc(datetime_convert())
591 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
594 info( t('Your introduction has been sent.') . EOL );
596 // "Homecoming" - send the requestor back to their site to record the introduction.
598 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
599 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
601 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
602 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
603 . '&confirm_key=' . $hash
604 . (($aes_allow) ? "&aes_allow=1" : "")
607 // END $network === NETWORK_DFRN
608 } elseif (($network != NETWORK_PHANTOM) AND ($url != "")) {
612 * Substitute our user's feed URL into $url template
613 * Send the subscriber home to subscribe
617 // Diaspora needs the uri in the format user@domain.tld
618 // Diaspora will support the remote subscription in a future version
619 if ($network == NETWORK_DIASPORA) {
620 $uri = $nickname.'@'.$a->get_hostname();
623 $uri .= '/'.$a->get_path();
625 $uri = urlencode($uri);
627 $uri = $a->get_baseurl().'/profile/'.$nickname;
629 $url = str_replace('{uri}', $uri, $url);
632 // END $network != NETWORK_PHANTOM
634 notice(t("Remote subscription can't be done for your network. Please subscribe directly on your system.").EOL);
644 if(! function_exists('dfrn_request_content')) {
645 function dfrn_request_content(&$a) {
647 if(($a->argc != 2) || (! count($a->profile)))
651 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
652 // to send us to the post section to record the introduction.
654 if(x($_GET,'dfrn_url')) {
657 info( t("Please login to confirm introduction.") . EOL );
658 /* setup the return URL to come back to this page if they use openid */
659 $_SESSION['return_url'] = $a->query_string;
663 // Edge case, but can easily happen in the wild. This person is authenticated,
664 // but not as the person who needs to deal with this request.
666 if ($a->user['nickname'] != $a->argv[1]) {
667 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
671 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
672 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
673 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
675 // Checking fastlane for validity
676 if (x($_SESSION, "fastlane") AND (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
677 $_POST["dfrn_url"] = $dfrn_url;
678 $_POST["confirm_key"] = $confirm_key;
679 $_POST["localconfirm"] = 1;
680 $_POST["hidden-contact"] = 0;
681 $_POST["submit"] = t('Confirm');
683 dfrn_request_post($a);
686 return; // NOTREACHED
689 $tpl = get_markup_template("dfrn_req_confirm.tpl");
690 $o = replace_macros($tpl,array(
691 '$dfrn_url' => $dfrn_url,
692 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
693 '$hidethem' => t('Hide this contact'),
694 '$hidechecked' => '',
695 '$confirm_key' => $confirm_key,
696 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
697 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
698 '$submit' => t('Confirm'),
699 '$uid' => $_SESSION['uid'],
700 '$nickname' => $a->user['nickname'],
701 'dfrn_rawurl' => $_GET['dfrn_url']
706 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
708 // we are the requestee and it is now safe to send our user their introduction,
709 // We could just unblock it, but first we have to jump through a few hoops to
710 // send an email, or even to find out if we need to send an email.
712 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
713 dbesc($_GET['confirm_key'])
718 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
719 WHERE `contact`.`id` = %d LIMIT 1",
720 intval($intro[0]['contact-id'])
723 $auto_confirm = false;
726 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
727 $auto_confirm = true;
729 if(! $auto_confirm) {
732 'type' => NOTIFY_INTRO,
733 'notify_flags' => $r[0]['notify-flags'],
734 'language' => $r[0]['language'],
735 'to_name' => $r[0]['username'],
736 'to_email' => $r[0]['email'],
737 'uid' => $r[0]['uid'],
738 'link' => $a->get_baseurl() . '/notifications/intros',
739 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
740 'source_link' => $r[0]['url'],
741 'source_photo' => $r[0]['photo'],
742 'verb' => ACTIVITY_REQ_FRIEND,
748 require_once('mod/dfrn_confirm.php');
750 'uid' => $r[0]['uid'],
751 'node' => $r[0]['nickname'],
752 'dfrn_id' => $r[0]['issued-id'],
753 'intro_id' => $intro[0]['id'],
754 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
755 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
757 dfrn_confirm_post($a,$handsfree);
762 if(! $auto_confirm) {
764 // If we are auto_confirming, this record will have already been nuked
765 // in dfrn_confirm_post()
767 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
768 dbesc($_GET['confirm_key'])
774 return; // NOTREACHED
779 * Normal web request. Display our user's introduction form.
782 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
783 if(! get_config('system','local_block')) {
784 notice( t('Public access denied.') . EOL);
791 * Try to auto-fill the profile address
794 // At first look if an address was provided
795 // Otherwise take the local address
796 if (x($_GET,'addr') AND ($_GET['addr'] != ""))
797 $myaddr = hex2bin($_GET['addr']);
798 elseif (x($_GET,'address') AND ($_GET['address'] != ""))
799 $myaddr = $_GET['address'];
800 elseif(local_user()) {
801 if(strlen($a->path)) {
802 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
805 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
807 } else // last, try a zrl
808 $myaddr = get_my_url();
810 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
815 * The auto_request form only has the profile address
816 * because nobody is going to read the comments and
817 * it doesn't matter if they know you or not.
821 if($a->profile['page-flags'] == PAGE_NORMAL)
822 $tpl = get_markup_template('dfrn_request.tpl');
824 $tpl = get_markup_template('auto_request.tpl');
826 $page_desc = t("Please enter your 'Identity Address' from one of the following supported communications networks:");
828 // see if we are allowed to have NETWORK_MAIL2 contacts
830 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
831 if(get_config('system','dfrn_only'))
834 if(! $mail_disabled) {
835 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
836 intval($a->profile['uid'])
842 // "coming soon" is disabled for now
843 //$emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
846 $invite_desc = sprintf(
847 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>.'),
851 $o = replace_macros($tpl,array(
852 '$header' => t('Friend/Connection Request'),
853 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
854 '$pls_answer' => t('Please answer the following:'),
855 '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'),$a->profile['name']), false, '', array(t('No'),t('Yes'))),
856 /*'$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
859 '$add_note' => t('Add a personal note:'),
860 '$page_desc' => $page_desc,
861 '$friendica' => t('Friendica'),
862 '$statusnet' => t('StatusNet/Federated Social Web'),
863 '$diaspora' => t('Diaspora'),
864 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
865 '$your_address' => t('Your Identity Address:'),
866 '$invite_desc' => $invite_desc,
867 '$emailnet' => $emailnet,
868 '$submit' => t('Submit Request'),
869 '$cancel' => t('Cancel'),
870 '$nickname' => $a->argv[1],
871 '$name' => $a->profile['name'],
877 return; // Somebody is fishing.