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 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 $g = q("select def_gid from user where uid = %d limit 1",
186 if($g && intval($g[0]['def_gid'])) {
187 require_once('include/group.php');
188 group_add_member(local_user(),'',$r[0]['id'],$g[0]['def_gid']);
190 $forwardurl = $a->get_baseurl()."/contacts/".$r[0]['id'];
192 $forwardurl = $a->get_baseurl()."/contacts";
195 * Allow the blocked remote notification to complete
198 if(is_array($contact_record))
199 $dfrn_request = $contact_record['request'];
201 if(strlen($dfrn_request) && strlen($confirm_key))
202 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
204 // (ignore reply, nothing we can do it failed)
206 // Old: goaway(zrl($dfrn_url));
208 return; // NOTREACHED
214 // invalid/bogus request
216 notice( t('Unrecoverable protocol error.') . EOL );
218 return; // NOTREACHED
225 * We are the requestee. A person from a remote cell has made an introduction
226 * on our profile web page and clicked submit. We will use their DFRN-URL to
227 * figure out how to contact their cell.
229 * Scrape the originating DFRN-URL for everything we need. Create a contact record
230 * and an introduction to show our user next time he/she logs in.
231 * Finally redirect back to the requestor so that their site can record the request.
232 * If our user (the requestee) later confirms this request, a record of it will need
233 * to exist on the requestor's cell in order for the confirmation process to complete..
235 * It's possible that neither the requestor or the requestee are logged in at the moment,
236 * and the requestor does not yet have any credentials to the requestee profile.
238 * Who is the requestee? We've already loaded their profile which means their nickname should be
239 * in $a->argv[1] and we should have their complete info in $a->profile.
243 if(! (is_array($a->profile) && count($a->profile))) {
244 notice( t('Profile unavailable.') . EOL);
248 $nickname = $a->profile['nickname'];
249 $notify_flags = $a->profile['notify-flags'];
250 $uid = $a->profile['uid'];
251 $maxreq = intval($a->profile['maxreq']);
252 $contact_record = null;
257 if( x($_POST,'dfrn_url')) {
260 * Block friend request spam
264 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
265 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
268 if(count($r) > $maxreq) {
269 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
270 notice( t('Spam protection measures have been invoked.') . EOL);
271 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
278 * Cleanup old introductions that remain blocked.
279 * Also remove the contact record, but only if there is no existing relationship
280 * Do not remove email contacts as these may be awaiting email verification
283 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
284 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
285 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
286 AND `contact`.`network` != '%s'
287 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ",
293 q("DELETE FROM `contact` WHERE `id` = %d",
297 q("DELETE FROM `intro` WHERE `id` = %d",
305 * Cleanup any old email intros - which will have a greater lifetime
308 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
309 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
310 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
311 AND `contact`.`network` = '%s'
312 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ",
318 q("DELETE FROM `contact` WHERE `id` = %d",
322 q("DELETE FROM `intro` WHERE `id` = %d",
328 $email_follow = (x($_POST,'email_follow') ? intval($_POST['email_follow']) : 0);
329 $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
331 $url = trim($_POST['dfrn_url']);
333 notice( t("Invalid locator") . EOL );
341 if(! validate_email($url)) {
342 notice( t('Invalid email address.') . EOL);
347 $name = ($realname) ? $realname : $addr;
348 $nick = substr($addr,0,strpos($addr,'@'));
349 $url = 'http://' . substr($addr,strpos($addr,'@') + 1);
350 $nurl = normalise_url($host);
351 $poll = 'email ' . random_string();
352 $notify = 'smtp ' . random_string();
355 $network = NETWORK_MAIL2;
356 $rel = CONTACT_IS_FOLLOWER;
358 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
359 if(get_config('system','dfrn_only'))
362 if(! $mail_disabled) {
364 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
369 notice( t('This account has not been configured for email. Request failed.') . EOL);
374 $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
375 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
377 dbesc(datetime_convert()),
391 $r = q("select id from contact where poll = '%s' and uid = %d limit 1",
396 $contact_id = $r[0]['id'];
398 $g = q("select def_gid from user where uid = %d limit 1",
401 if($g && intval($g[0]['def_gid'])) {
402 require_once('include/group.php');
403 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
406 $photo = avatar_img($addr);
408 $r = q("UPDATE `contact` SET
414 `avatar-date` = '%s',
421 dbesc(datetime_convert()),
422 dbesc(datetime_convert()),
423 dbesc(datetime_convert()),
428 // contact is created. Now create an introduction
430 $hash = random_string();
432 $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
433 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
436 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
437 dbesc(notags(trim($_POST['dfrn-request-message']))),
439 dbesc(datetime_convert()),
443 // Next send an email verify form to the requestor.
446 // Detect the network
447 $data = probe_url($url);
448 $network = $data["network"];
450 // Canonicalise email-style profile locator
451 $url = webfinger_dfrn($url,$hcard);
453 if (substr($url,0,5) === 'stat:') {
455 // Every time we detect the remote subscription we define this as OStatus.
456 // We do this even if it is not OStatus.
457 // we only need to pass this through another section of the code.
458 if ($network != NETWORK_DIASPORA)
459 $network = NETWORK_OSTATUS;
461 $url = substr($url,5);
463 $network = NETWORK_DFRN;
466 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
468 if($network === NETWORK_DFRN) {
469 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
475 if(strlen($ret[0]['issued-id'])) {
476 notice( t('You have already introduced yourself here.') . EOL );
479 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
480 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
484 $contact_record = $ret[0];
485 $parms = array('dfrn-request' => $ret[0]['request']);
489 $issued_id = random_string();
491 if(is_array($contact_record)) {
492 // There is a contact record but no issued-id, so this
493 // is a reciprocal introduction from a known contact
494 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
496 intval($contact_record['id'])
500 if(! validate_url($url)) {
501 notice( t('Invalid profile URL.') . EOL);
502 goaway($a->get_baseurl() . '/' . $a->cmd);
503 return; // NOTREACHED
506 if(! allowed_url($url)) {
507 notice( t('Disallowed profile URL.') . EOL);
508 goaway($a->get_baseurl() . '/' . $a->cmd);
509 return; // NOTREACHED
513 require_once('include/Scrape.php');
515 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
517 if(! count($parms)) {
518 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
519 goaway($a->get_baseurl() . '/' . $a->cmd);
523 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
524 if(! x($parms,'photo'))
525 notice( t('Warning: profile location has no profile photo.') . EOL );
526 $invalid = validate_dfrn($parms);
528 notice( sprintf( tt("%d required parameter was not found at the given location",
529 "%d required parameters were not found at the given location",
530 $invalid), $invalid) . EOL );
537 $parms['url'] = $url;
538 $parms['issued-id'] = $issued_id;
542 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
543 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
544 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
546 dbesc(datetime_convert()),
548 dbesc(normalise_link($parms['url'])),
555 $parms['dfrn-request'],
556 $parms['dfrn-confirm'],
557 $parms['dfrn-notify'],
563 // find the contact record we just created
565 $r = q("SELECT `id` FROM `contact`
566 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
572 $contact_record = $r[0];
577 notice( t('Failed to update contact record.') . EOL );
581 $hash = random_string() . (string) time(); // Generate a confirm_key
583 if(is_array($contact_record)) {
584 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
585 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
587 intval($contact_record['id']),
588 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
589 dbesc(notags(trim($_POST['dfrn-request-message']))),
591 dbesc(datetime_convert())
595 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
598 info( t('Your introduction has been sent.') . EOL );
600 // "Homecoming" - send the requestor back to their site to record the introduction.
602 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
603 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
605 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
606 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
607 . '&confirm_key=' . $hash
608 . (($aes_allow) ? "&aes_allow=1" : "")
611 // END $network === NETWORK_DFRN
612 } elseif (($network != NETWORK_PHANTOM) AND ($url != "")) {
616 * Substitute our user's feed URL into $url template
617 * Send the subscriber home to subscribe
621 // Diaspora needs the uri in the format user@domain.tld
622 // Diaspora will support the remote subscription in a future version
623 if ($network == NETWORK_DIASPORA) {
624 $uri = $nickname.'@'.$a->get_hostname();
627 $uri .= '/'.$a->get_path();
629 $uri = urlencode($uri);
631 $uri = $a->get_baseurl().'/profile/'.$nickname;
633 $url = str_replace('{uri}', $uri, $url);
636 // END $network != NETWORK_PHANTOM
638 notice(t("Remote subscription can't be done for your network. Please subscribe directly on your system.").EOL);
648 if(! function_exists('dfrn_request_content')) {
649 function dfrn_request_content(&$a) {
651 if(($a->argc != 2) || (! count($a->profile)))
655 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
656 // to send us to the post section to record the introduction.
658 if(x($_GET,'dfrn_url')) {
661 info( t("Please login to confirm introduction.") . EOL );
662 /* setup the return URL to come back to this page if they use openid */
663 $_SESSION['return_url'] = $a->query_string;
667 // Edge case, but can easily happen in the wild. This person is authenticated,
668 // but not as the person who needs to deal with this request.
670 if ($a->user['nickname'] != $a->argv[1]) {
671 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
675 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
676 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
677 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
679 // Checking fastlane for validity
680 if (x($_SESSION, "fastlane") AND (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
681 $_POST["dfrn_url"] = $dfrn_url;
682 $_POST["confirm_key"] = $confirm_key;
683 $_POST["localconfirm"] = 1;
684 $_POST["hidden-contact"] = 0;
685 $_POST["submit"] = t('Confirm');
687 dfrn_request_post($a);
690 return; // NOTREACHED
693 $tpl = get_markup_template("dfrn_req_confirm.tpl");
694 $o = replace_macros($tpl,array(
695 '$dfrn_url' => $dfrn_url,
696 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
697 '$hidethem' => t('Hide this contact'),
698 '$hidechecked' => '',
699 '$confirm_key' => $confirm_key,
700 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
701 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
702 '$submit' => t('Confirm'),
703 '$uid' => $_SESSION['uid'],
704 '$nickname' => $a->user['nickname'],
705 'dfrn_rawurl' => $_GET['dfrn_url']
710 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
712 // we are the requestee and it is now safe to send our user their introduction,
713 // We could just unblock it, but first we have to jump through a few hoops to
714 // send an email, or even to find out if we need to send an email.
716 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
717 dbesc($_GET['confirm_key'])
722 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
723 WHERE `contact`.`id` = %d LIMIT 1",
724 intval($intro[0]['contact-id'])
727 $auto_confirm = false;
730 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
731 $auto_confirm = true;
733 if(! $auto_confirm) {
736 'type' => NOTIFY_INTRO,
737 'notify_flags' => $r[0]['notify-flags'],
738 'language' => $r[0]['language'],
739 'to_name' => $r[0]['username'],
740 'to_email' => $r[0]['email'],
741 'uid' => $r[0]['uid'],
742 'link' => $a->get_baseurl() . '/notifications/intros',
743 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
744 'source_link' => $r[0]['url'],
745 'source_photo' => $r[0]['photo'],
746 'verb' => ACTIVITY_REQ_FRIEND,
752 require_once('mod/dfrn_confirm.php');
754 'uid' => $r[0]['uid'],
755 'node' => $r[0]['nickname'],
756 'dfrn_id' => $r[0]['issued-id'],
757 'intro_id' => $intro[0]['id'],
758 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
759 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
761 dfrn_confirm_post($a,$handsfree);
766 if(! $auto_confirm) {
768 // If we are auto_confirming, this record will have already been nuked
769 // in dfrn_confirm_post()
771 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
772 dbesc($_GET['confirm_key'])
778 return; // NOTREACHED
783 * Normal web request. Display our user's introduction form.
786 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
787 if(! get_config('system','local_block')) {
788 notice( t('Public access denied.') . EOL);
795 * Try to auto-fill the profile address
798 // At first look if an address was provided
799 // Otherwise take the local address
800 if (x($_GET,'addr') AND ($_GET['addr'] != ""))
801 $myaddr = hex2bin($_GET['addr']);
802 elseif (x($_GET,'address') AND ($_GET['address'] != ""))
803 $myaddr = $_GET['address'];
804 elseif(local_user()) {
805 if(strlen($a->path)) {
806 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
809 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
811 } else // last, try a zrl
812 $myaddr = get_my_url();
814 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
819 * The auto_request form only has the profile address
820 * because nobody is going to read the comments and
821 * it doesn't matter if they know you or not.
825 if($a->profile['page-flags'] == PAGE_NORMAL)
826 $tpl = get_markup_template('dfrn_request.tpl');
828 $tpl = get_markup_template('auto_request.tpl');
830 // TODO This .= triggers an E_NOTICE, really needed?
831 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported communications networks:");
833 // see if we are allowed to have NETWORK_MAIL2 contacts
835 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
836 if(get_config('system','dfrn_only'))
839 if(! $mail_disabled) {
840 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
841 intval($a->profile['uid'])
847 // "coming soon" is disabled for now
848 //$emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
851 $invite_desc = sprintf(
852 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>.'),
856 // TODO This .= triggers an E_NOTICE, really needed?
857 $o .= replace_macros($tpl,array(
858 '$header' => t('Friend/Connection Request'),
859 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
860 '$pls_answer' => t('Please answer the following:'),
861 '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'),$a->profile['name']), false, '', array(t('No'),t('Yes'))),
862 /*'$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
865 '$add_note' => t('Add a personal note:'),
866 '$page_desc' => $page_desc,
867 '$friendica' => t('Friendica'),
868 '$statusnet' => t('StatusNet/Federated Social Web'),
869 '$diaspora' => t('Diaspora'),
870 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
871 '$your_address' => t('Your Identity Address:'),
872 '$invite_desc' => $invite_desc,
873 '$emailnet' => $emailnet,
874 '$submit' => t('Submit Request'),
875 '$cancel' => t('Cancel'),
876 '$nickname' => $a->argv[1],
877 '$name' => $a->profile['name'],
883 return; // Somebody is fishing.