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",
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('include/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']);
186 $forwardurl = $a->get_baseurl()."/contacts/".$r[0]['id'];
188 $forwardurl = $a->get_baseurl()."/contacts";
191 * Allow the blocked remote notification to complete
194 if(is_array($contact_record))
195 $dfrn_request = $contact_record['request'];
197 if(strlen($dfrn_request) && strlen($confirm_key))
198 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
200 // (ignore reply, nothing we can do it failed)
202 // Old: goaway(zrl($dfrn_url));
204 return; // NOTREACHED
210 // invalid/bogus request
212 notice( t('Unrecoverable protocol error.') . EOL );
214 return; // NOTREACHED
221 * We are the requestee. A person from a remote cell has made an introduction
222 * on our profile web page and clicked submit. We will use their DFRN-URL to
223 * figure out how to contact their cell.
225 * Scrape the originating DFRN-URL for everything we need. Create a contact record
226 * and an introduction to show our user next time he/she logs in.
227 * Finally redirect back to the requestor so that their site can record the request.
228 * If our user (the requestee) later confirms this request, a record of it will need
229 * to exist on the requestor's cell in order for the confirmation process to complete..
231 * It's possible that neither the requestor or the requestee are logged in at the moment,
232 * and the requestor does not yet have any credentials to the requestee profile.
234 * Who is the requestee? We've already loaded their profile which means their nickname should be
235 * in $a->argv[1] and we should have their complete info in $a->profile.
239 if(! (is_array($a->profile) && count($a->profile))) {
240 notice( t('Profile unavailable.') . EOL);
244 $nickname = $a->profile['nickname'];
245 $notify_flags = $a->profile['notify-flags'];
246 $uid = $a->profile['uid'];
247 $maxreq = intval($a->profile['maxreq']);
248 $contact_record = null;
253 if( x($_POST,'dfrn_url')) {
256 * Block friend request spam
260 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
261 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
264 if(count($r) > $maxreq) {
265 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
266 notice( t('Spam protection measures have been invoked.') . EOL);
267 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
274 * Cleanup old introductions that remain blocked.
275 * Also remove the contact record, but only if there is no existing relationship
276 * Do not remove email contacts as these may be awaiting email verification
279 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
280 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
281 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
282 AND `contact`.`network` != '%s'
283 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ",
289 q("DELETE FROM `contact` WHERE `id` = %d",
293 q("DELETE FROM `intro` WHERE `id` = %d",
301 * Cleanup any old email intros - which will have a greater lifetime
304 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
305 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
306 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
307 AND `contact`.`network` = '%s'
308 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ",
314 q("DELETE FROM `contact` WHERE `id` = %d",
318 q("DELETE FROM `intro` WHERE `id` = %d",
324 $email_follow = (x($_POST,'email_follow') ? intval($_POST['email_follow']) : 0);
325 $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
327 $url = trim($_POST['dfrn_url']);
329 notice( t("Invalid locator") . EOL );
337 if(! validate_email($url)) {
338 notice( t('Invalid email address.') . EOL);
343 $name = ($realname) ? $realname : $addr;
344 $nick = substr($addr,0,strpos($addr,'@'));
345 $url = 'http://' . substr($addr,strpos($addr,'@') + 1);
346 $nurl = normalise_url($host);
347 $poll = 'email ' . random_string();
348 $notify = 'smtp ' . random_string();
351 $network = NETWORK_MAIL2;
352 $rel = CONTACT_IS_FOLLOWER;
354 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
355 if(get_config('system','dfrn_only'))
358 if(! $mail_disabled) {
360 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
365 notice( t('This account has not been configured for email. Request failed.') . EOL);
370 $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
371 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
373 dbesc(datetime_convert()),
387 $r = q("select id from contact where poll = '%s' and uid = %d limit 1",
392 $contact_id = $r[0]['id'];
394 $g = q("select def_gid from user where uid = %d limit 1",
397 if($g && intval($g[0]['def_gid'])) {
398 require_once('include/group.php');
399 group_add_member($uid,'',$contact_id,$g[0]['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.
445 // Canonicalise email-style profile locator
447 $url = webfinger_dfrn($url,$hcard);
449 if(substr($url,0,5) === 'stat:') {
450 $network = NETWORK_OSTATUS;
451 $url = substr($url,5);
454 $network = NETWORK_DFRN;
458 logger('dfrn_request: url: ' . $url);
461 notice( t("Unable to resolve your name at the provided location.") . EOL);
466 if($network === NETWORK_DFRN) {
467 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
473 if(strlen($ret[0]['issued-id'])) {
474 notice( t('You have already introduced yourself here.') . EOL );
477 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
478 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
482 $contact_record = $ret[0];
483 $parms = array('dfrn-request' => $ret[0]['request']);
487 $issued_id = random_string();
489 if(is_array($contact_record)) {
490 // There is a contact record but no issued-id, so this
491 // is a reciprocal introduction from a known contact
492 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
494 intval($contact_record['id'])
498 if(! validate_url($url)) {
499 notice( t('Invalid profile URL.') . EOL);
500 goaway($a->get_baseurl() . '/' . $a->cmd);
501 return; // NOTREACHED
504 if(! allowed_url($url)) {
505 notice( t('Disallowed profile URL.') . EOL);
506 goaway($a->get_baseurl() . '/' . $a->cmd);
507 return; // NOTREACHED
511 require_once('include/Scrape.php');
513 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
515 if(! count($parms)) {
516 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
517 goaway($a->get_baseurl() . '/' . $a->cmd);
521 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
522 if(! x($parms,'photo'))
523 notice( t('Warning: profile location has no profile photo.') . EOL );
524 $invalid = validate_dfrn($parms);
526 notice( sprintf( tt("%d required parameter was not found at the given location",
527 "%d required parameters were not found at the given location",
528 $invalid), $invalid) . EOL );
535 $parms['url'] = $url;
536 $parms['issued-id'] = $issued_id;
540 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`,`name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
541 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
542 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
544 dbesc(datetime_convert()),
546 dbesc(normalise_link($parms['url'])),
552 $parms['dfrn-request'],
553 $parms['dfrn-confirm'],
554 $parms['dfrn-notify'],
560 // find the contact record we just created
562 $r = q("SELECT `id` FROM `contact`
563 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
569 $contact_record = $r[0];
574 notice( t('Failed to update contact record.') . EOL );
578 $hash = random_string() . (string) time(); // Generate a confirm_key
580 if(is_array($contact_record)) {
581 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
582 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
584 intval($contact_record['id']),
585 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
586 dbesc(notags(trim($_POST['dfrn-request-message']))),
588 dbesc(datetime_convert())
592 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
595 info( t('Your introduction has been sent.') . EOL );
597 // "Homecoming" - send the requestor back to their site to record the introduction.
599 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
600 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
602 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
603 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
604 . '&confirm_key=' . $hash
605 . (($aes_allow) ? "&aes_allow=1" : "")
608 // END $network === NETWORK_DFRN
610 elseif($network === NETWORK_OSTATUS) {
615 * Check contact existence
616 * Try and scrape together enough information to create a contact record,
617 * with us as CONTACT_IS_FOLLOWER
618 * Substitute our user's feed URL into $url template
619 * Send the subscriber home to subscribe
623 $url = str_replace('{uri}', $a->get_baseurl() . '/profile/' . $nickname, $url);
626 // END $network === NETWORK_OSTATUS
635 if(! function_exists('dfrn_request_content')) {
636 function dfrn_request_content(&$a) {
638 if(($a->argc != 2) || (! count($a->profile)))
642 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
643 // to send us to the post section to record the introduction.
645 if(x($_GET,'dfrn_url')) {
648 info( t("Please login to confirm introduction.") . EOL );
650 /* setup the return URL to come back to this page if they use openid */
652 $stripped = str_replace('q=','',$a->query_string);
653 $_SESSION['return_url'] = trim($stripped,'/');
658 // Edge case, but can easily happen in the wild. This person is authenticated,
659 // but not as the person who needs to deal with this request.
661 if ($a->user['nickname'] != $a->argv[1]) {
662 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
666 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
667 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
668 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
669 $tpl = get_markup_template("dfrn_req_confirm.tpl");
670 $o = replace_macros($tpl,array(
671 '$dfrn_url' => $dfrn_url,
672 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
673 '$hidethem' => t('Hide this contact'),
674 '$hidechecked' => '',
675 '$confirm_key' => $confirm_key,
676 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
677 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
678 '$submit' => t('Confirm'),
679 '$uid' => $_SESSION['uid'],
680 '$nickname' => $a->user['nickname'],
681 'dfrn_rawurl' => $_GET['dfrn_url']
686 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
688 // we are the requestee and it is now safe to send our user their introduction,
689 // We could just unblock it, but first we have to jump through a few hoops to
690 // send an email, or even to find out if we need to send an email.
692 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
693 dbesc($_GET['confirm_key'])
698 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
699 WHERE `contact`.`id` = %d LIMIT 1",
700 intval($intro[0]['contact-id'])
703 $auto_confirm = false;
706 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
707 $auto_confirm = true;
709 if(! $auto_confirm) {
710 require_once('include/enotify.php');
712 'type' => NOTIFY_INTRO,
713 'notify_flags' => $r[0]['notify-flags'],
714 'language' => $r[0]['language'],
715 'to_name' => $r[0]['username'],
716 'to_email' => $r[0]['email'],
717 'uid' => $r[0]['uid'],
718 'link' => $a->get_baseurl() . '/notifications/intros',
719 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
720 'source_link' => $r[0]['url'],
721 'source_photo' => $r[0]['photo'],
722 'verb' => ACTIVITY_REQ_FRIEND,
728 require_once('mod/dfrn_confirm.php');
730 'uid' => $r[0]['uid'],
731 'node' => $r[0]['nickname'],
732 'dfrn_id' => $r[0]['issued-id'],
733 'intro_id' => $intro[0]['id'],
734 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
735 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
737 dfrn_confirm_post($a,$handsfree);
742 if(! $auto_confirm) {
744 // If we are auto_confirming, this record will have already been nuked
745 // in dfrn_confirm_post()
747 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
748 dbesc($_GET['confirm_key'])
754 return; // NOTREACHED
759 * Normal web request. Display our user's introduction form.
762 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
763 if(! get_config('system','local_block')) {
764 notice( t('Public access denied.') . EOL);
771 * Try to auto-fill the profile address
774 // At first look if an address was provided
775 // Otherwise take the local address
776 if (x($_GET,'addr') AND ($_GET['addr'] != ""))
777 $myaddr = hex2bin($_GET['addr']);
778 elseif (x($_GET,'address') AND ($_GET['address'] != ""))
779 $myaddr = $_GET['address'];
780 elseif(local_user()) {
781 if(strlen($a->path)) {
782 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
785 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
787 } else // last, try a zrl
788 $myaddr = get_my_url();
790 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
795 * The auto_request form only has the profile address
796 * because nobody is going to read the comments and
797 * it doesn't matter if they know you or not.
801 if($a->profile['page-flags'] == PAGE_NORMAL)
802 $tpl = get_markup_template('dfrn_request.tpl');
804 $tpl = get_markup_template('auto_request.tpl');
806 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported communications networks:");
808 // see if we are allowed to have NETWORK_MAIL2 contacts
810 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
811 if(get_config('system','dfrn_only'))
814 if(! $mail_disabled) {
815 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
816 intval($a->profile['uid'])
822 // "coming soon" is disabled for now
823 //$emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
826 $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>.');
828 $o .= replace_macros($tpl,array(
829 '$header' => t('Friend/Connection Request'),
830 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
831 '$pls_answer' => t('Please answer the following:'),
832 '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'),$a->profile['name']), false, '', array(t('No'),t('Yes'))),
833 /*'$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
836 '$add_note' => t('Add a personal note:'),
837 '$page_desc' => $page_desc,
838 '$friendica' => t('Friendica'),
839 '$statusnet' => t('StatusNet/Federated Social Web'),
840 '$diaspora' => t('Diaspora'),
841 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
842 '$your_address' => t('Your Identity Address:'),
843 '$invite_desc' => $invite_desc,
844 '$emailnet' => $emailnet,
845 '$submit' => t('Submit Request'),
846 '$cancel' => t('Cancel'),
847 '$nickname' => $a->argv[1],
848 '$name' => $a->profile['name'],
854 return; // Somebody is fishing.