7 * Purpose: Handles communication associated with the issuance of
12 require_once('include/enotify.php');
14 if(! function_exists('dfrn_request_init')) {
15 function dfrn_request_init(&$a) {
20 profile_load($a,$which);
26 * Function: dfrn_request_post
29 * Handles multiple scenarios.
32 * Clicking 'submit' on a friend request page.
35 * Following Scenario 1, we are brought back to our home site
36 * in order to link our friend request with our own server cell.
37 * After logging in, we click 'submit' to approve the linkage.
41 if(! function_exists('dfrn_request_post')) {
42 function dfrn_request_post(&$a) {
44 if(($a->argc != 2) || (! count($a->profile)))
48 if(x($_POST, 'cancel')) {
55 * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
56 * to confirm the request, and then we've clicked submit (perhaps after logging in).
57 * That brings us here:
61 if((x($_POST,'localconfirm')) && ($_POST['localconfirm'] == 1)) {
64 * Ensure this is a valid request
67 if(local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST,'dfrn_url'))) {
70 $dfrn_url = notags(trim($_POST['dfrn_url']));
71 $aes_allow = (((x($_POST,'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
72 $confirm_key = ((x($_POST,'confirm_key')) ? $_POST['confirm_key'] : "");
73 $hidden = ((x($_POST,'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
74 $contact_record = null;
79 * Lookup the contact based on their URL (which is the only unique thing we have at the moment)
82 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND (`url` = '%s' OR `nurl` = '%s') AND `self` = 0 LIMIT 1",
85 dbesc(normalise_link($dfrn_url))
89 if(strlen($r[0]['dfrn-id'])) {
92 * We don't need to be here. It has already happened.
95 notice( t("This introduction has already been accepted.") . EOL );
99 $contact_record = $r[0];
102 if(is_array($contact_record)) {
103 $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
106 intval($contact_record['id'])
112 * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
115 require_once('include/Scrape.php');
117 $parms = scrape_dfrn($dfrn_url);
119 if(! count($parms)) {
120 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
125 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
126 if(! x($parms,'photo'))
127 notice( t('Warning: profile location has no profile photo.') . EOL );
128 $invalid = validate_dfrn($parms);
130 notice( sprintf( tt("%d required parameter was not found at the given location",
131 "%d required parameters were not found at the given location",
132 $invalid), $invalid) . EOL );
137 $dfrn_request = $parms['dfrn-request'];
139 /********* Escape the entire array ********/
143 /******************************************/
146 * Create a contact record on our site for the other person
149 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
150 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`)
151 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
152 intval(local_user()),
155 dbesc(normalise_link($dfrn_url)),
161 $parms['dfrn-request'],
162 $parms['dfrn-confirm'],
163 $parms['dfrn-notify'],
173 info( t("Introduction complete.") . EOL);
176 $r = q("select id from contact where uid = %d and url = '%s' and `site-pubkey` = '%s' limit 1",
177 intval(local_user()),
179 $parms['key'] // this was already escaped
182 $g = q("select def_gid from user where uid = %d limit 1",
185 if($g && intval($g[0]['def_gid'])) {
186 require_once('include/group.php');
187 group_add_member(local_user(),'',$r[0]['id'],$g[0]['def_gid']);
189 $forwardurl = $a->get_baseurl()."/contacts/".$r[0]['id'];
191 $forwardurl = $a->get_baseurl()."/contacts";
194 * Allow the blocked remote notification to complete
197 if(is_array($contact_record))
198 $dfrn_request = $contact_record['request'];
200 if(strlen($dfrn_request) && strlen($confirm_key))
201 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
203 // (ignore reply, nothing we can do it failed)
205 // Old: goaway(zrl($dfrn_url));
207 return; // NOTREACHED
213 // invalid/bogus request
215 notice( t('Unrecoverable protocol error.') . EOL );
217 return; // NOTREACHED
224 * We are the requestee. A person from a remote cell has made an introduction
225 * on our profile web page and clicked submit. We will use their DFRN-URL to
226 * figure out how to contact their cell.
228 * Scrape the originating DFRN-URL for everything we need. Create a contact record
229 * and an introduction to show our user next time he/she logs in.
230 * Finally redirect back to the requestor so that their site can record the request.
231 * If our user (the requestee) later confirms this request, a record of it will need
232 * to exist on the requestor's cell in order for the confirmation process to complete..
234 * It's possible that neither the requestor or the requestee are logged in at the moment,
235 * and the requestor does not yet have any credentials to the requestee profile.
237 * Who is the requestee? We've already loaded their profile which means their nickname should be
238 * in $a->argv[1] and we should have their complete info in $a->profile.
242 if(! (is_array($a->profile) && count($a->profile))) {
243 notice( t('Profile unavailable.') . EOL);
247 $nickname = $a->profile['nickname'];
248 $notify_flags = $a->profile['notify-flags'];
249 $uid = $a->profile['uid'];
250 $maxreq = intval($a->profile['maxreq']);
251 $contact_record = null;
256 if( x($_POST,'dfrn_url')) {
259 * Block friend request spam
263 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
264 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
267 if(count($r) > $maxreq) {
268 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
269 notice( t('Spam protection measures have been invoked.') . EOL);
270 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
277 * Cleanup old introductions that remain blocked.
278 * Also remove the contact record, but only if there is no existing relationship
279 * Do not remove email contacts as these may be awaiting email verification
282 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
283 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
284 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
285 AND `contact`.`network` != '%s'
286 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ",
292 q("DELETE FROM `contact` WHERE `id` = %d",
296 q("DELETE FROM `intro` WHERE `id` = %d",
304 * Cleanup any old email intros - which will have a greater lifetime
307 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
308 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
309 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
310 AND `contact`.`network` = '%s'
311 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ",
317 q("DELETE FROM `contact` WHERE `id` = %d",
321 q("DELETE FROM `intro` WHERE `id` = %d",
327 $email_follow = (x($_POST,'email_follow') ? intval($_POST['email_follow']) : 0);
328 $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
330 $url = trim($_POST['dfrn_url']);
332 notice( t("Invalid locator") . EOL );
340 if(! validate_email($url)) {
341 notice( t('Invalid email address.') . EOL);
346 $name = ($realname) ? $realname : $addr;
347 $nick = substr($addr,0,strpos($addr,'@'));
348 $url = 'http://' . substr($addr,strpos($addr,'@') + 1);
349 $nurl = normalise_url($host);
350 $poll = 'email ' . random_string();
351 $notify = 'smtp ' . random_string();
354 $network = NETWORK_MAIL2;
355 $rel = CONTACT_IS_FOLLOWER;
357 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
358 if(get_config('system','dfrn_only'))
361 if(! $mail_disabled) {
363 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
368 notice( t('This account has not been configured for email. Request failed.') . EOL);
373 $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
374 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
376 dbesc(datetime_convert()),
390 $r = q("select id from contact where poll = '%s' and uid = %d limit 1",
395 $contact_id = $r[0]['id'];
397 $g = q("select def_gid from user where uid = %d limit 1",
400 if($g && intval($g[0]['def_gid'])) {
401 require_once('include/group.php');
402 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
405 $photo = avatar_img($addr);
407 $r = q("UPDATE `contact` SET
413 `avatar-date` = '%s',
420 dbesc(datetime_convert()),
421 dbesc(datetime_convert()),
422 dbesc(datetime_convert()),
427 // contact is created. Now create an introduction
429 $hash = random_string();
431 $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
432 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
435 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
436 dbesc(notags(trim($_POST['dfrn-request-message']))),
438 dbesc(datetime_convert()),
442 // Next send an email verify form to the requestor.
448 // Canonicalise email-style profile locator
450 $url = webfinger_dfrn($url,$hcard);
452 if(substr($url,0,5) === 'stat:') {
453 $network = NETWORK_OSTATUS;
454 $url = substr($url,5);
457 $network = NETWORK_DFRN;
461 logger('dfrn_request: url: ' . $url);
464 notice( t("Unable to resolve your name at the provided location.") . EOL);
469 if($network === NETWORK_DFRN) {
470 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
476 if(strlen($ret[0]['issued-id'])) {
477 notice( t('You have already introduced yourself here.') . EOL );
480 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
481 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
485 $contact_record = $ret[0];
486 $parms = array('dfrn-request' => $ret[0]['request']);
490 $issued_id = random_string();
492 if(is_array($contact_record)) {
493 // There is a contact record but no issued-id, so this
494 // is a reciprocal introduction from a known contact
495 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
497 intval($contact_record['id'])
501 if(! validate_url($url)) {
502 notice( t('Invalid profile URL.') . EOL);
503 goaway($a->get_baseurl() . '/' . $a->cmd);
504 return; // NOTREACHED
507 if(! allowed_url($url)) {
508 notice( t('Disallowed profile URL.') . EOL);
509 goaway($a->get_baseurl() . '/' . $a->cmd);
510 return; // NOTREACHED
514 require_once('include/Scrape.php');
516 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
518 if(! count($parms)) {
519 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
520 goaway($a->get_baseurl() . '/' . $a->cmd);
524 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
525 if(! x($parms,'photo'))
526 notice( t('Warning: profile location has no profile photo.') . EOL );
527 $invalid = validate_dfrn($parms);
529 notice( sprintf( tt("%d required parameter was not found at the given location",
530 "%d required parameters were not found at the given location",
531 $invalid), $invalid) . EOL );
538 $parms['url'] = $url;
539 $parms['issued-id'] = $issued_id;
543 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
544 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
545 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
547 dbesc(datetime_convert()),
549 dbesc(normalise_link($parms['url'])),
556 $parms['dfrn-request'],
557 $parms['dfrn-confirm'],
558 $parms['dfrn-notify'],
564 // find the contact record we just created
566 $r = q("SELECT `id` FROM `contact`
567 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
573 $contact_record = $r[0];
578 notice( t('Failed to update contact record.') . EOL );
582 $hash = random_string() . (string) time(); // Generate a confirm_key
584 if(is_array($contact_record)) {
585 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
586 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
588 intval($contact_record['id']),
589 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
590 dbesc(notags(trim($_POST['dfrn-request-message']))),
592 dbesc(datetime_convert())
596 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
599 info( t('Your introduction has been sent.') . EOL );
601 // "Homecoming" - send the requestor back to their site to record the introduction.
603 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
604 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
606 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
607 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
608 . '&confirm_key=' . $hash
609 . (($aes_allow) ? "&aes_allow=1" : "")
612 // END $network === NETWORK_DFRN
614 elseif($network === NETWORK_OSTATUS) {
619 * Check contact existence
620 * Try and scrape together enough information to create a contact record,
621 * with us as CONTACT_IS_FOLLOWER
622 * Substitute our user's feed URL into $url template
623 * Send the subscriber home to subscribe
627 $url = str_replace('{uri}', $a->get_baseurl() . '/profile/' . $nickname, $url);
630 // END $network === NETWORK_OSTATUS
639 if(! function_exists('dfrn_request_content')) {
640 function dfrn_request_content(&$a) {
642 if(($a->argc != 2) || (! count($a->profile)))
646 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
647 // to send us to the post section to record the introduction.
649 if(x($_GET,'dfrn_url')) {
652 info( t("Please login to confirm introduction.") . EOL );
653 /* setup the return URL to come back to this page if they use openid */
654 $_SESSION['return_url'] = $a->query_string;
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'] : "");
670 // Checking fastlane for validity
671 if (x($_SESSION, "fastlane") AND (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
672 $_POST["dfrn_url"] = $dfrn_url;
673 $_POST["confirm_key"] = $confirm_key;
674 $_POST["localconfirm"] = 1;
675 $_POST["hidden-contact"] = 0;
676 $_POST["submit"] = t('Confirm');
678 dfrn_request_post($a);
681 return; // NOTREACHED
684 $tpl = get_markup_template("dfrn_req_confirm.tpl");
685 $o = replace_macros($tpl,array(
686 '$dfrn_url' => $dfrn_url,
687 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
688 '$hidethem' => t('Hide this contact'),
689 '$hidechecked' => '',
690 '$confirm_key' => $confirm_key,
691 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
692 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
693 '$submit' => t('Confirm'),
694 '$uid' => $_SESSION['uid'],
695 '$nickname' => $a->user['nickname'],
696 'dfrn_rawurl' => $_GET['dfrn_url']
701 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
703 // we are the requestee and it is now safe to send our user their introduction,
704 // We could just unblock it, but first we have to jump through a few hoops to
705 // send an email, or even to find out if we need to send an email.
707 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
708 dbesc($_GET['confirm_key'])
713 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
714 WHERE `contact`.`id` = %d LIMIT 1",
715 intval($intro[0]['contact-id'])
718 $auto_confirm = false;
721 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
722 $auto_confirm = true;
724 if(! $auto_confirm) {
727 'type' => NOTIFY_INTRO,
728 'notify_flags' => $r[0]['notify-flags'],
729 'language' => $r[0]['language'],
730 'to_name' => $r[0]['username'],
731 'to_email' => $r[0]['email'],
732 'uid' => $r[0]['uid'],
733 'link' => $a->get_baseurl() . '/notifications/intros',
734 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
735 'source_link' => $r[0]['url'],
736 'source_photo' => $r[0]['photo'],
737 'verb' => ACTIVITY_REQ_FRIEND,
743 require_once('mod/dfrn_confirm.php');
745 'uid' => $r[0]['uid'],
746 'node' => $r[0]['nickname'],
747 'dfrn_id' => $r[0]['issued-id'],
748 'intro_id' => $intro[0]['id'],
749 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
750 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
752 dfrn_confirm_post($a,$handsfree);
757 if(! $auto_confirm) {
759 // If we are auto_confirming, this record will have already been nuked
760 // in dfrn_confirm_post()
762 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
763 dbesc($_GET['confirm_key'])
769 return; // NOTREACHED
774 * Normal web request. Display our user's introduction form.
777 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
778 if(! get_config('system','local_block')) {
779 notice( t('Public access denied.') . EOL);
786 * Try to auto-fill the profile address
789 // At first look if an address was provided
790 // Otherwise take the local address
791 if (x($_GET,'addr') AND ($_GET['addr'] != ""))
792 $myaddr = hex2bin($_GET['addr']);
793 elseif (x($_GET,'address') AND ($_GET['address'] != ""))
794 $myaddr = $_GET['address'];
795 elseif(local_user()) {
796 if(strlen($a->path)) {
797 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
800 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
802 } else // last, try a zrl
803 $myaddr = get_my_url();
805 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
810 * The auto_request form only has the profile address
811 * because nobody is going to read the comments and
812 * it doesn't matter if they know you or not.
816 if($a->profile['page-flags'] == PAGE_NORMAL)
817 $tpl = get_markup_template('dfrn_request.tpl');
819 $tpl = get_markup_template('auto_request.tpl');
821 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported communications networks:");
823 // see if we are allowed to have NETWORK_MAIL2 contacts
825 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
826 if(get_config('system','dfrn_only'))
829 if(! $mail_disabled) {
830 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
831 intval($a->profile['uid'])
837 // "coming soon" is disabled for now
838 //$emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
841 $invite_desc = sprintf(
842 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>.'),
846 $o .= replace_macros($tpl,array(
847 '$header' => t('Friend/Connection Request'),
848 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
849 '$pls_answer' => t('Please answer the following:'),
850 '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'),$a->profile['name']), false, '', array(t('No'),t('Yes'))),
851 /*'$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
854 '$add_note' => t('Add a personal note:'),
855 '$page_desc' => $page_desc,
856 '$friendica' => t('Friendica'),
857 '$statusnet' => t('StatusNet/Federated Social Web'),
858 '$diaspora' => t('Diaspora'),
859 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
860 '$your_address' => t('Your Identity Address:'),
861 '$invite_desc' => $invite_desc,
862 '$emailnet' => $emailnet,
863 '$submit' => t('Submit Request'),
864 '$cancel' => t('Cancel'),
865 '$nickname' => $a->argv[1],
866 '$name' => $a->profile['name'],
872 return; // Somebody is fishing.