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('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']);
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",
362 notice( t('This account has not been configured for email. Request failed.') . EOL);
367 $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
368 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
370 dbesc(datetime_convert()),
384 $r = q("select id from contact where poll = '%s' and uid = %d limit 1",
389 $contact_id = $r[0]['id'];
391 $g = q("select def_gid from user where uid = %d limit 1",
394 if($g && intval($g[0]['def_gid'])) {
395 require_once('include/group.php');
396 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
399 $photo = avatar_img($addr);
401 $r = q("UPDATE `contact` SET
407 `avatar-date` = '%s',
409 WHERE `id` = %d LIMIT 1
414 dbesc(datetime_convert()),
415 dbesc(datetime_convert()),
416 dbesc(datetime_convert()),
421 // contact is created. Now create an introduction
423 $hash = random_string();
425 $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
426 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
429 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
430 dbesc(notags(trim($_POST['dfrn-request-message']))),
432 dbesc(datetime_convert()),
436 // Next send an email verify form to the requestor.
442 // Canonicalise email-style profile locator
444 $url = webfinger_dfrn($url,$hcard);
446 if(substr($url,0,5) === 'stat:') {
447 $network = NETWORK_OSTATUS;
448 $url = substr($url,5);
451 $network = NETWORK_DFRN;
455 logger('dfrn_request: url: ' . $url);
458 notice( t("Unable to resolve your name at the provided location.") . EOL);
463 if($network === NETWORK_DFRN) {
464 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
470 if(strlen($ret[0]['issued-id'])) {
471 notice( t('You have already introduced yourself here.') . EOL );
474 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
475 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
479 $contact_record = $ret[0];
480 $parms = array('dfrn-request' => $ret[0]['request']);
484 $issued_id = random_string();
486 if(is_array($contact_record)) {
487 // There is a contact record but no issued-id, so this
488 // is a reciprocal introduction from a known contact
489 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1",
491 intval($contact_record['id'])
495 if(! validate_url($url)) {
496 notice( t('Invalid profile URL.') . EOL);
497 goaway($a->get_baseurl() . '/' . $a->cmd);
498 return; // NOTREACHED
501 if(! allowed_url($url)) {
502 notice( t('Disallowed profile URL.') . EOL);
503 goaway($a->get_baseurl() . '/' . $a->cmd);
504 return; // NOTREACHED
508 require_once('include/Scrape.php');
510 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
512 if(! count($parms)) {
513 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
514 goaway($a->get_baseurl() . '/' . $a->cmd);
518 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
519 if(! x($parms,'photo'))
520 notice( t('Warning: profile location has no profile photo.') . EOL );
521 $invalid = validate_dfrn($parms);
523 notice( sprintf( tt("%d required parameter was not found at the given location",
524 "%d required parameters were not found at the given location",
525 $invalid), $invalid) . EOL );
532 $parms['url'] = $url;
533 $parms['issued-id'] = $issued_id;
537 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`,`name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
538 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
539 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
541 dbesc(datetime_convert()),
543 dbesc(normalise_link($parms['url'])),
549 $parms['dfrn-request'],
550 $parms['dfrn-confirm'],
551 $parms['dfrn-notify'],
557 // find the contact record we just created
559 $r = q("SELECT `id` FROM `contact`
560 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
566 $contact_record = $r[0];
571 notice( t('Failed to update contact record.') . EOL );
575 $hash = random_string() . (string) time(); // Generate a confirm_key
577 if(is_array($contact_record)) {
578 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
579 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
581 intval($contact_record['id']),
582 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
583 dbesc(notags(trim($_POST['dfrn-request-message']))),
585 dbesc(datetime_convert())
589 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
592 info( t('Your introduction has been sent.') . EOL );
594 // "Homecoming" - send the requestor back to their site to record the introduction.
596 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
597 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
599 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
600 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
601 . '&confirm_key=' . $hash
602 . (($aes_allow) ? "&aes_allow=1" : "")
605 // END $network === NETWORK_DFRN
607 elseif($network === NETWORK_OSTATUS) {
612 * Check contact existence
613 * Try and scrape together enough information to create a contact record,
614 * with us as CONTACT_IS_FOLLOWER
615 * Substitute our user's feed URL into $url template
616 * Send the subscriber home to subscribe
620 $url = str_replace('{uri}', $a->get_baseurl() . '/profile/' . $nickname, $url);
623 // END $network === NETWORK_OSTATUS
632 if(! function_exists('dfrn_request_content')) {
633 function dfrn_request_content(&$a) {
635 if(($a->argc != 2) || (! count($a->profile)))
639 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
640 // to send us to the post section to record the introduction.
642 if(x($_GET,'dfrn_url')) {
645 info( t("Please login to confirm introduction.") . EOL );
647 /* setup the return URL to come back to this page if they use openid */
649 $stripped = str_replace('q=','',$a->query_string);
650 $_SESSION['return_url'] = trim($stripped,'/');
655 // Edge case, but can easily happen in the wild. This person is authenticated,
656 // but not as the person who needs to deal with this request.
658 if ($a->user['nickname'] != $a->argv[1]) {
659 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
663 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
664 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
665 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
666 $tpl = get_markup_template("dfrn_req_confirm.tpl");
667 $o = replace_macros($tpl,array(
668 '$dfrn_url' => $dfrn_url,
669 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
670 '$hidethem' => t('Hide this contact'),
671 '$hidechecked' => '',
672 '$confirm_key' => $confirm_key,
673 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
674 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
675 '$submit' => t('Confirm'),
676 '$uid' => $_SESSION['uid'],
677 '$nickname' => $a->user['nickname'],
678 'dfrn_rawurl' => $_GET['dfrn_url']
683 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
685 // we are the requestee and it is now safe to send our user their introduction,
686 // We could just unblock it, but first we have to jump through a few hoops to
687 // send an email, or even to find out if we need to send an email.
689 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
690 dbesc($_GET['confirm_key'])
695 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
696 WHERE `contact`.`id` = %d LIMIT 1",
697 intval($intro[0]['contact-id'])
700 $auto_confirm = false;
703 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
704 $auto_confirm = true;
706 if(! $auto_confirm) {
707 require_once('include/enotify.php');
709 'type' => NOTIFY_INTRO,
710 'notify_flags' => $r[0]['notify-flags'],
711 'language' => $r[0]['language'],
712 'to_name' => $r[0]['username'],
713 'to_email' => $r[0]['email'],
714 'uid' => $r[0]['uid'],
715 'link' => $a->get_baseurl() . '/notifications/intros',
716 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
717 'source_link' => $r[0]['url'],
718 'source_photo' => $r[0]['photo'],
719 'verb' => ACTIVITY_REQ_FRIEND,
725 require_once('mod/dfrn_confirm.php');
727 'uid' => $r[0]['uid'],
728 'node' => $r[0]['nickname'],
729 'dfrn_id' => $r[0]['issued-id'],
730 'intro_id' => $intro[0]['id'],
731 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
732 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
734 dfrn_confirm_post($a,$handsfree);
739 if(! $auto_confirm) {
741 // If we are auto_confirming, this record will have already been nuked
742 // in dfrn_confirm_post()
744 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s' LIMIT 1",
745 dbesc($_GET['confirm_key'])
751 return; // NOTREACHED
756 * Normal web request. Display our user's introduction form.
759 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
760 if(! get_config('system','local_block')) {
761 notice( t('Public access denied.') . EOL);
768 * Try to auto-fill the profile address
772 if(strlen($a->path)) {
773 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
776 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
779 elseif(x($_GET,'addr')) {
780 $myaddr = hex2bin($_GET['addr']);
783 /* $_GET variables are already urldecoded */
784 $myaddr = ((x($_GET,'address')) ? $_GET['address'] : '');
788 if(! strlen($myaddr))
789 $myaddr = get_my_url();
792 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
797 * The auto_request form only has the profile address
798 * because nobody is going to read the comments and
799 * it doesn't matter if they know you or not.
803 if($a->profile['page-flags'] == PAGE_NORMAL)
804 $tpl = get_markup_template('dfrn_request.tpl');
806 $tpl = get_markup_template('auto_request.tpl');
808 # $page_desc = sprintf( t('Diaspora members: Please do not use this form. Instead, enter "%s" into your Diaspora search bar.'),
809 # $target_addr) . EOL . EOL;
811 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported communications networks:");
813 // see if we are allowed to have NETWORK_MAIL2 contacts
815 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
816 if(get_config('system','dfrn_only'))
819 if(! $mail_disabled) {
820 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
821 intval($a->profile['uid'])
827 $emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
829 $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>.');
831 $o .= replace_macros($tpl,array(
832 '$header' => t('Friend/Connection Request'),
833 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
834 '$pls_answer' => t('Please answer the following:'),
835 '$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
838 '$add_note' => t('Add a personal note:'),
839 '$page_desc' => $page_desc,
840 '$friendica' => t('Friendica'),
841 '$statusnet' => t('StatusNet/Federated Social Web'),
842 '$diaspora' => t('Diaspora'),
843 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
844 '$your_address' => t('Your Identity Address:'),
845 '$invite_desc' => $invite_desc,
846 '$emailnet' => $emailnet,
847 '$submit' => t('Submit Request'),
848 '$cancel' => t('Cancel'),
849 '$nickname' => $a->argv[1],
850 '$name' => $a->profile['name'],
856 return; // Somebody is fishing.