7 * Purpose: Handles communication associated with the issuance of
12 if(! function_exists('dfrn_request_init')) {
13 function dfrn_request_init(&$a) {
18 profile_load($a,$which);
24 * Function: dfrn_request_post
27 * Handles multiple scenarios.
30 * Clicking 'submit' on a friend request page.
33 * Following Scenario 1, we are brought back to our home site
34 * in order to link our friend request with our own server cell.
35 * After logging in, we click 'submit' to approve the linkage.
39 if(! function_exists('dfrn_request_post')) {
40 function dfrn_request_post(&$a) {
42 if(($a->argc != 2) || (! count($a->profile)))
46 if(x($_POST, 'cancel')) {
53 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
54 * to confirm the request, and then we've clicked submit (perhaps after logging in).
55 * That brings us here:
59 if((x($_POST,'localconfirm')) && ($_POST['localconfirm'] == 1)) {
62 * Ensure this is a valid request
65 if(local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST,'dfrn_url'))) {
68 $dfrn_url = notags(trim($_POST['dfrn_url']));
69 $aes_allow = (((x($_POST,'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
70 $confirm_key = ((x($_POST,'confirm_key')) ? $_POST['confirm_key'] : "");
71 $hidden = ((x($_POST,'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
72 $contact_record = null;
77 * 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 (`url` = '%s' OR `nurl` = '%s') AND `self` = 0 LIMIT 1",
83 dbesc(normalise_link($dfrn_url))
87 if(strlen($r[0]['dfrn-id'])) {
90 * We don't need to be here. It has already happened.
93 notice( t("This introduction has already been accepted.") . EOL );
97 $contact_record = $r[0];
100 if(is_array($contact_record)) {
101 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d LIMIT 1",
104 intval($contact_record['id'])
110 * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
113 require_once('Scrape.php');
115 $parms = scrape_dfrn($dfrn_url);
117 if(! count($parms)) {
118 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
123 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
124 if(! x($parms,'photo'))
125 notice( t('Warning: profile location has no profile photo.') . EOL );
126 $invalid = validate_dfrn($parms);
128 notice( sprintf( tt("%d required parameter was not found at the given location",
129 "%d required parameters were not found at the given location",
130 $invalid), $invalid) . EOL );
135 $dfrn_request = $parms['dfrn-request'];
137 /********* Escape the entire array ********/
141 /******************************************/
144 * Create a contact record on our site for the other person
147 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `name`, `nick`, `photo`, `site-pubkey`,
148 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`)
149 VALUES ( %d, '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
150 intval(local_user()),
153 dbesc(normalise_link($dfrn_url)),
158 $parms['dfrn-request'],
159 $parms['dfrn-confirm'],
160 $parms['dfrn-notify'],
170 info( t("Introduction complete.") . EOL);
173 $r = q("select id from contact where uid = %d and url = '%s' and `site-pubkey` = '%s' limit 1",
174 intval(local_user()),
176 $parms['key'] // this was already escaped
179 $g = q("select def_gid from user where uid = %d limit 1",
182 if($g && intval($g[0]['def_gid'])) {
183 require_once('include/group.php');
184 group_add_member(local_user(),'',$r[0]['id'],$g[0]['def_gid']);
189 * Allow the blocked remote notification to complete
192 if(is_array($contact_record))
193 $dfrn_request = $contact_record['request'];
195 if(strlen($dfrn_request) && strlen($confirm_key))
196 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
198 // (ignore reply, nothing we can do it failed)
200 goaway(zrl($dfrn_url));
201 return; // NOTREACHED
207 // invalid/bogus request
209 notice( t('Unrecoverable protocol error.') . EOL );
211 return; // NOTREACHED
218 * We are the requestee. A person from a remote cell has made an introduction
219 * on our profile web page and clicked submit. We will use their DFRN-URL to
220 * figure out how to contact their cell.
222 * Scrape the originating DFRN-URL for everything we need. Create a contact record
223 * and an introduction to show our user next time he/she logs in.
224 * Finally redirect back to the requestor so that their site can record the request.
225 * If our user (the requestee) later confirms this request, a record of it will need
226 * to exist on the requestor's cell in order for the confirmation process to complete..
228 * It's possible that neither the requestor or the requestee are logged in at the moment,
229 * and the requestor does not yet have any credentials to the requestee profile.
231 * Who is the requestee? We've already loaded their profile which means their nickname should be
232 * in $a->argv[1] and we should have their complete info in $a->profile.
236 if(! (is_array($a->profile) && count($a->profile))) {
237 notice( t('Profile unavailable.') . EOL);
241 $nickname = $a->profile['nickname'];
242 $notify_flags = $a->profile['notify-flags'];
243 $uid = $a->profile['uid'];
244 $maxreq = intval($a->profile['maxreq']);
245 $contact_record = null;
250 if( x($_POST,'dfrn_url')) {
253 * Block friend request spam
257 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
258 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
261 if(count($r) > $maxreq) {
262 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
263 notice( t('Spam protection measures have been invoked.') . EOL);
264 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
271 * Cleanup old introductions that remain blocked.
272 * Also remove the contact record, but only if there is no existing relationship
273 * Do not remove email contacts as these may be awaiting email verification
276 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
277 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
278 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
279 AND `contact`.`network` != '%s'
280 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ",
286 q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
290 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
298 * Cleanup any old email intros - which will have a greater lifetime
301 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
302 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
303 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
304 AND `contact`.`network` = '%s'
305 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ",
311 q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
315 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
321 $email_follow = (x($_POST,'email_follow') ? intval($_POST['email_follow']) : 0);
322 $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
324 $url = trim($_POST['dfrn_url']);
326 notice( t("Invalid locator") . EOL );
334 if(! validate_email($url)) {
335 notice( t('Invalid email address.') . EOL);
340 $name = ($realname) ? $realname : $addr;
341 $nick = substr($addr,0,strpos($addr,'@'));
342 $url = 'http://' . substr($addr,strpos($addr,'@') + 1);
343 $nurl = normalise_url($host);
344 $poll = 'email ' . random_string();
345 $notify = 'smtp ' . random_string();
348 $network = NETWORK_MAIL2;
349 $rel = CONTACT_IS_FOLLOWER;
351 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
352 if(get_config('system','dfrn_only'))
355 if(! $mail_disabled) {
357 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
361 notice( t('This account has not been configured for email. Request failed.') . EOL);
366 $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
367 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
369 dbesc(datetime_convert()),
383 $r = q("select id from contact where poll = '%s' and uid = %d limit 1",
388 $contact_id = $r[0]['id'];
390 $g = q("select def_gid from user where uid = %d limit 1",
393 if($g && intval($g[0]['def_gid'])) {
394 require_once('include/group.php');
395 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
398 $photo = avatar_img($addr);
400 $r = q("UPDATE `contact` SET
406 `avatar-date` = '%s',
408 WHERE `id` = %d LIMIT 1
413 dbesc(datetime_convert()),
414 dbesc(datetime_convert()),
415 dbesc(datetime_convert()),
420 // contact is created. Now create an introduction
422 $hash = random_string();
424 $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
425 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
428 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
429 dbesc(notags(trim($_POST['dfrn-request-message']))),
431 dbesc(datetime_convert()),
435 // Next send an email verify form to the requestor.
441 // Canonicalise email-style profile locator
443 $url = webfinger_dfrn($url,$hcard);
445 if(substr($url,0,5) === 'stat:') {
446 $network = NETWORK_OSTATUS;
447 $url = substr($url,5);
450 $network = NETWORK_DFRN;
454 logger('dfrn_request: url: ' . $url);
457 notice( t("Unable to resolve your name at the provided location.") . EOL);
462 if($network === NETWORK_DFRN) {
463 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
469 if(strlen($ret[0]['issued-id'])) {
470 notice( t('You have already introduced yourself here.') . EOL );
473 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
474 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
478 $contact_record = $ret[0];
479 $parms = array('dfrn-request' => $ret[0]['request']);
483 $issued_id = random_string();
485 if(is_array($contact_record)) {
486 // There is a contact record but no issued-id, so this
487 // is a reciprocal introduction from a known contact
488 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1",
490 intval($contact_record['id'])
494 if(! validate_url($url)) {
495 notice( t('Invalid profile URL.') . EOL);
496 goaway($a->get_baseurl() . '/' . $a->cmd);
497 return; // NOTREACHED
500 if(! allowed_url($url)) {
501 notice( t('Disallowed profile URL.') . EOL);
502 goaway($a->get_baseurl() . '/' . $a->cmd);
503 return; // NOTREACHED
507 require_once('Scrape.php');
509 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
511 if(! count($parms)) {
512 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
513 goaway($a->get_baseurl() . '/' . $a->cmd);
517 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
518 if(! x($parms,'photo'))
519 notice( t('Warning: profile location has no profile photo.') . EOL );
520 $invalid = validate_dfrn($parms);
522 notice( sprintf( tt("%d required parameter was not found at the given location",
523 "%d required parameters were not found at the given location",
524 $invalid), $invalid) . EOL );
531 $parms['url'] = $url;
532 $parms['issued-id'] = $issued_id;
536 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`,`name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
537 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
538 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
540 dbesc(datetime_convert()),
542 dbesc(normalise_link($parms['url'])),
548 $parms['dfrn-request'],
549 $parms['dfrn-confirm'],
550 $parms['dfrn-notify'],
556 // find the contact record we just created
558 $r = q("SELECT `id` FROM `contact`
559 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
565 $contact_record = $r[0];
570 notice( t('Failed to update contact record.') . EOL );
574 $hash = random_string() . (string) time(); // Generate a confirm_key
576 if(is_array($contact_record)) {
577 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
578 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
580 intval($contact_record['id']),
581 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
582 dbesc(notags(trim($_POST['dfrn-request-message']))),
584 dbesc(datetime_convert())
588 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
591 info( t('Your introduction has been sent.') . EOL );
593 // "Homecoming" - send the requestor back to their site to record the introduction.
595 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
596 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
598 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
599 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
600 . '&confirm_key=' . $hash
601 . (($aes_allow) ? "&aes_allow=1" : "")
604 // END $network === NETWORK_DFRN
606 elseif($network === NETWORK_OSTATUS) {
611 * Check contact existence
612 * Try and scrape together enough information to create a contact record,
613 * with us as CONTACT_IS_FOLLOWER
614 * Substitute our user's feed URL into $url template
615 * Send the subscriber home to subscribe
619 $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url);
622 // END $network === NETWORK_OSTATUS
631 if(! function_exists('dfrn_request_content')) {
632 function dfrn_request_content(&$a) {
634 if(($a->argc != 2) || (! count($a->profile)))
638 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
639 // to send us to the post section to record the introduction.
641 if(x($_GET,'dfrn_url')) {
644 info( t("Please login to confirm introduction.") . EOL );
646 /* setup the return URL to come back to this page if they use openid */
648 $stripped = str_replace('q=','',$a->query_string);
649 $_SESSION['return_url'] = trim($stripped,'/');
654 // Edge case, but can easily happen in the wild. This person is authenticated,
655 // but not as the person who needs to deal with this request.
657 if ($a->user['nickname'] != $a->argv[1]) {
658 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
662 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
663 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
664 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
665 $tpl = get_markup_template("dfrn_req_confirm.tpl");
666 $o = replace_macros($tpl,array(
667 '$dfrn_url' => $dfrn_url,
668 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
669 '$hidethem' => t('Hide this contact'),
670 '$hidechecked' => '',
671 '$confirm_key' => $confirm_key,
672 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
673 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
674 '$submit' => t('Confirm'),
675 '$uid' => $_SESSION['uid'],
676 '$nickname' => $a->user['nickname'],
677 'dfrn_rawurl' => $_GET['dfrn_url']
682 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
684 // we are the requestee and it is now safe to send our user their introduction,
685 // We could just unblock it, but first we have to jump through a few hoops to
686 // send an email, or even to find out if we need to send an email.
688 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
689 dbesc($_GET['confirm_key'])
694 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
695 WHERE `contact`.`id` = %d LIMIT 1",
696 intval($intro[0]['contact-id'])
699 $auto_confirm = false;
702 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
703 $auto_confirm = true;
705 if(! $auto_confirm) {
706 require_once('include/enotify.php');
708 'type' => NOTIFY_INTRO,
709 'notify_flags' => $r[0]['notify-flags'],
710 'language' => $r[0]['language'],
711 'to_name' => $r[0]['username'],
712 'to_email' => $r[0]['email'],
713 'uid' => $r[0]['uid'],
714 'link' => $a->get_baseurl() . '/notifications/intros',
715 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
716 'source_link' => $r[0]['url'],
717 'source_photo' => $r[0]['photo'],
718 'verb' => ACTIVITY_REQ_FRIEND,
724 require_once('mod/dfrn_confirm.php');
726 'uid' => $r[0]['uid'],
727 'node' => $r[0]['nickname'],
728 'dfrn_id' => $r[0]['issued-id'],
729 'intro_id' => $intro[0]['id'],
730 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
731 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
733 dfrn_confirm_post($a,$handsfree);
738 if(! $auto_confirm) {
740 // If we are auto_confirming, this record will have already been nuked
741 // in dfrn_confirm_post()
743 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s' LIMIT 1",
744 dbesc($_GET['confirm_key'])
750 return; // NOTREACHED
755 * Normal web request. Display our user's introduction form.
758 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
759 if(! get_config('system','local_block')) {
760 notice( t('Public access denied.') . EOL);
767 * Try to auto-fill the profile address
771 if(strlen($a->path)) {
772 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
775 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
778 elseif(x($_GET,'addr')) {
779 $myaddr = hex2bin($_GET['addr']);
782 /* $_GET variables are already urldecoded */
783 $myaddr = ((x($_GET,'address')) ? $_GET['address'] : '');
787 if(! strlen($myaddr))
788 $myaddr = get_my_url();
791 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
796 * The auto_request form only has the profile address
797 * because nobody is going to read the comments and
798 * it doesn't matter if they know you or not.
802 if($a->profile['page-flags'] == PAGE_NORMAL)
803 $tpl = get_markup_template('dfrn_request.tpl');
805 $tpl = get_markup_template('auto_request.tpl');
807 # $page_desc = sprintf( t('Diaspora members: Please do not use this form. Instead, enter "%s" into your Diaspora search bar.'),
808 # $target_addr) . EOL . EOL;
810 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported communications networks:");
812 // see if we are allowed to have NETWORK_MAIL2 contacts
814 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
815 if(get_config('system','dfrn_only'))
818 if(! $mail_disabled) {
819 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
820 intval($a->profile['uid'])
826 $emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
828 $invite_desc = t('If you are not yet a member of the free social web, <a href="http://dir.friendica.com/siteinfo">follow this link to find a public Friendica site and join us today</a>.');
830 $o .= replace_macros($tpl,array(
831 '$header' => t('Friend/Connection Request'),
832 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
833 '$pls_answer' => t('Please answer the following:'),
834 '$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
837 '$add_note' => t('Add a personal note:'),
838 '$page_desc' => $page_desc,
839 '$friendica' => t('Friendica'),
840 '$statusnet' => t('StatusNet/Federated Social Web'),
841 '$diaspora' => t('Diaspora'),
842 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
843 '$your_address' => t('Your Identity Address:'),
844 '$invite_desc' => $invite_desc,
845 '$emailnet' => $emailnet,
846 '$submit' => t('Submit Request'),
847 '$cancel' => t('Cancel'),
848 '$nickname' => $a->argv[1],
849 '$name' => $a->profile['name'],
855 return; // Somebody is fishing.