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);
174 * Allow the blocked remote notification to complete
177 if(is_array($contact_record))
178 $dfrn_request = $contact_record['request'];
180 if(strlen($dfrn_request) && strlen($confirm_key))
181 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
183 // (ignore reply, nothing we can do it failed)
185 goaway(zrl($dfrn_url));
186 return; // NOTREACHED
192 // invalid/bogus request
194 notice( t('Unrecoverable protocol error.') . EOL );
196 return; // NOTREACHED
203 * We are the requestee. A person from a remote cell has made an introduction
204 * on our profile web page and clicked submit. We will use their DFRN-URL to
205 * figure out how to contact their cell.
207 * Scrape the originating DFRN-URL for everything we need. Create a contact record
208 * and an introduction to show our user next time he/she logs in.
209 * Finally redirect back to the requestor so that their site can record the request.
210 * If our user (the requestee) later confirms this request, a record of it will need
211 * to exist on the requestor's cell in order for the confirmation process to complete..
213 * It's possible that neither the requestor or the requestee are logged in at the moment,
214 * and the requestor does not yet have any credentials to the requestee profile.
216 * Who is the requestee? We've already loaded their profile which means their nickname should be
217 * in $a->argv[1] and we should have their complete info in $a->profile.
221 if(! (is_array($a->profile) && count($a->profile))) {
222 notice( t('Profile unavailable.') . EOL);
226 $nickname = $a->profile['nickname'];
227 $notify_flags = $a->profile['notify-flags'];
228 $uid = $a->profile['uid'];
229 $maxreq = intval($a->profile['maxreq']);
230 $contact_record = null;
235 if( x($_POST,'dfrn_url')) {
238 * Block friend request spam
242 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
243 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
246 if(count($r) > $maxreq) {
247 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
248 notice( t('Spam protection measures have been invoked.') . EOL);
249 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
256 * Cleanup old introductions that remain blocked.
257 * Also remove the contact record, but only if there is no existing relationship
258 * Do not remove email contacts as these may be awaiting email verification
261 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
262 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
263 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
264 AND `contact`.`network` != '%s'
265 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ",
271 q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
275 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
283 * Cleanup any old email intros - which will have a greater lifetime
286 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
287 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
288 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
289 AND `contact`.`network` = '%s'
290 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ",
296 q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
300 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
306 $email_follow = (x($_POST,'email_follow') ? intval($_POST['email_follow']) : 0);
307 $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
309 $url = trim($_POST['dfrn_url']);
311 notice( t("Invalid locator") . EOL );
319 if(! validate_email($url)) {
320 notice( t('Invalid email address.') . EOL);
325 $name = ($realname) ? $realname : $addr;
326 $nick = substr($addr,0,strpos($addr,'@'));
327 $url = 'http://' . substr($addr,strpos($addr,'@') + 1);
328 $nurl = normalise_url($host);
329 $poll = 'email ' . random_string();
330 $notify = 'smtp ' . random_string();
333 $network = NETWORK_MAIL2;
334 $rel = CONTACT_IS_FOLLOWER;
336 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
337 if(get_config('system','dfrn_only'))
340 if(! $mail_disabled) {
342 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
346 notice( t('This account has not been configured for email. Request failed.') . EOL);
351 $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
352 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
354 dbesc(datetime_convert()),
368 $r = q("select id from contact where poll = '%s' and uid = %d limit 1",
373 $contact_id = $r[0]['id'];
375 $g = q("select def_gid from user where uid = %d limit 1",
378 if($g && intval($g[0]['def_gid'])) {
379 require_once('include/group.php');
380 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
383 $photo = avatar_img($addr);
385 $r = q("UPDATE `contact` SET
391 `avatar-date` = '%s',
393 WHERE `id` = %d LIMIT 1
398 dbesc(datetime_convert()),
399 dbesc(datetime_convert()),
400 dbesc(datetime_convert()),
405 // contact is created. Now create an introduction
407 $hash = random_string();
409 $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
410 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
413 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
414 dbesc(notags(trim($_POST['dfrn-request-message']))),
416 dbesc(datetime_convert()),
420 // Next send an email verify form to the requestor.
426 // Canonicalise email-style profile locator
428 $url = webfinger_dfrn($url,$hcard);
430 if(substr($url,0,5) === 'stat:') {
431 $network = NETWORK_OSTATUS;
432 $url = substr($url,5);
435 $network = NETWORK_DFRN;
439 logger('dfrn_request: url: ' . $url);
442 notice( t("Unable to resolve your name at the provided location.") . EOL);
447 if($network === NETWORK_DFRN) {
448 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
454 if(strlen($ret[0]['issued-id'])) {
455 notice( t('You have already introduced yourself here.') . EOL );
458 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
459 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
463 $contact_record = $ret[0];
464 $parms = array('dfrn-request' => $ret[0]['request']);
468 $issued_id = random_string();
470 if(is_array($contact_record)) {
471 // There is a contact record but no issued-id, so this
472 // is a reciprocal introduction from a known contact
473 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1",
475 intval($contact_record['id'])
479 if(! validate_url($url)) {
480 notice( t('Invalid profile URL.') . EOL);
481 goaway($a->get_baseurl() . '/' . $a->cmd);
482 return; // NOTREACHED
485 if(! allowed_url($url)) {
486 notice( t('Disallowed profile URL.') . EOL);
487 goaway($a->get_baseurl() . '/' . $a->cmd);
488 return; // NOTREACHED
492 require_once('Scrape.php');
494 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
496 if(! count($parms)) {
497 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
498 goaway($a->get_baseurl() . '/' . $a->cmd);
502 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
503 if(! x($parms,'photo'))
504 notice( t('Warning: profile location has no profile photo.') . EOL );
505 $invalid = validate_dfrn($parms);
507 notice( sprintf( tt("%d required parameter was not found at the given location",
508 "%d required parameters were not found at the given location",
509 $invalid), $invalid) . EOL );
516 $parms['url'] = $url;
517 $parms['issued-id'] = $issued_id;
521 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`,`name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
522 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
523 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
525 dbesc(datetime_convert()),
527 dbesc(normalise_link($parms['url'])),
533 $parms['dfrn-request'],
534 $parms['dfrn-confirm'],
535 $parms['dfrn-notify'],
541 // find the contact record we just created
543 $r = q("SELECT `id` FROM `contact`
544 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
550 $contact_record = $r[0];
555 notice( t('Failed to update contact record.') . EOL );
559 $hash = random_string() . (string) time(); // Generate a confirm_key
561 if(is_array($contact_record)) {
562 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
563 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
565 intval($contact_record['id']),
566 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
567 dbesc(notags(trim($_POST['dfrn-request-message']))),
569 dbesc(datetime_convert())
573 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
576 info( t('Your introduction has been sent.') . EOL );
578 // "Homecoming" - send the requestor back to their site to record the introduction.
580 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
581 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
583 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
584 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
585 . '&confirm_key=' . $hash
586 . (($aes_allow) ? "&aes_allow=1" : "")
589 // END $network === NETWORK_DFRN
591 elseif($network === NETWORK_OSTATUS) {
596 * Check contact existence
597 * Try and scrape together enough information to create a contact record,
598 * with us as CONTACT_IS_FOLLOWER
599 * Substitute our user's feed URL into $url template
600 * Send the subscriber home to subscribe
604 $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url);
607 // END $network === NETWORK_OSTATUS
616 if(! function_exists('dfrn_request_content')) {
617 function dfrn_request_content(&$a) {
619 if(($a->argc != 2) || (! count($a->profile)))
623 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
624 // to send us to the post section to record the introduction.
626 if(x($_GET,'dfrn_url')) {
629 info( t("Please login to confirm introduction.") . EOL );
631 /* setup the return URL to come back to this page if they use openid */
633 $stripped = str_replace('q=','',$a->query_string);
634 $_SESSION['return_url'] = trim($stripped,'/');
639 // Edge case, but can easily happen in the wild. This person is authenticated,
640 // but not as the person who needs to deal with this request.
642 if ($a->user['nickname'] != $a->argv[1]) {
643 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
647 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
648 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
649 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
650 $tpl = get_markup_template("dfrn_req_confirm.tpl");
651 $o = replace_macros($tpl,array(
652 '$dfrn_url' => $dfrn_url,
653 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
654 '$hidethem' => t('Hide this contact'),
655 '$hidechecked' => '',
656 '$confirm_key' => $confirm_key,
657 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
658 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
659 '$submit' => t('Confirm'),
660 '$uid' => $_SESSION['uid'],
661 '$nickname' => $a->user['nickname'],
662 'dfrn_rawurl' => $_GET['dfrn_url']
667 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
669 // we are the requestee and it is now safe to send our user their introduction,
670 // We could just unblock it, but first we have to jump through a few hoops to
671 // send an email, or even to find out if we need to send an email.
673 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
674 dbesc($_GET['confirm_key'])
679 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
680 WHERE `contact`.`id` = %d LIMIT 1",
681 intval($intro[0]['contact-id'])
684 $auto_confirm = false;
687 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
688 $auto_confirm = true;
690 if(! $auto_confirm) {
691 require_once('include/enotify.php');
693 'type' => NOTIFY_INTRO,
694 'notify_flags' => $r[0]['notify-flags'],
695 'language' => $r[0]['language'],
696 'to_name' => $r[0]['username'],
697 'to_email' => $r[0]['email'],
698 'uid' => $r[0]['uid'],
699 'link' => $a->get_baseurl() . '/notifications/intros',
700 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
701 'source_link' => $r[0]['url'],
702 'source_photo' => $r[0]['photo'],
703 'verb' => ACTIVITY_REQ_FRIEND,
709 require_once('mod/dfrn_confirm.php');
711 'uid' => $r[0]['uid'],
712 'node' => $r[0]['nickname'],
713 'dfrn_id' => $r[0]['issued-id'],
714 'intro_id' => $intro[0]['id'],
715 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
716 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
718 dfrn_confirm_post($a,$handsfree);
723 if(! $auto_confirm) {
725 // If we are auto_confirming, this record will have already been nuked
726 // in dfrn_confirm_post()
728 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s' LIMIT 1",
729 dbesc($_GET['confirm_key'])
735 return; // NOTREACHED
740 * Normal web request. Display our user's introduction form.
743 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
744 notice( t('Public access denied.') . EOL);
750 * Try to auto-fill the profile address
754 if(strlen($a->path)) {
755 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
758 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
761 elseif(x($_GET,'addr')) {
762 $myaddr = hex2bin($_GET['addr']);
765 /* $_GET variables are already urldecoded */
766 $myaddr = ((x($_GET,'address')) ? $_GET['address'] : '');
770 if(! strlen($myaddr))
771 $myaddr = get_my_url();
774 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
779 * The auto_request form only has the profile address
780 * because nobody is going to read the comments and
781 * it doesn't matter if they know you or not.
785 if($a->profile['page-flags'] == PAGE_NORMAL)
786 $tpl = get_markup_template('dfrn_request.tpl');
788 $tpl = get_markup_template('auto_request.tpl');
790 # $page_desc = sprintf( t('Diaspora members: Please do not use this form. Instead, enter "%s" into your Diaspora search bar.'),
791 # $target_addr) . EOL . EOL;
793 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported communications networks:");
795 // see if we are allowed to have NETWORK_MAIL2 contacts
797 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
798 if(get_config('system','dfrn_only'))
801 if(! $mail_disabled) {
802 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
803 intval($a->profile['uid'])
809 $emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
811 $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>.');
813 $o .= replace_macros($tpl,array(
814 '$header' => t('Friend/Connection Request'),
815 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
816 '$pls_answer' => t('Please answer the following:'),
817 '$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
820 '$add_note' => t('Add a personal note:'),
821 '$page_desc' => $page_desc,
822 '$friendica' => t('Friendica'),
823 '$statusnet' => t('StatusNet/Federated Social Web'),
824 '$diaspora' => t('Diaspora'),
825 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
826 '$your_address' => t('Your Identity Address:'),
827 '$invite_desc' => $invite_desc,
828 '$emailnet' => $emailnet,
829 '$submit' => t('Submit Request'),
830 '$cancel' => t('Cancel'),
831 '$nickname' => $a->argv[1],
832 '$name' => $a->profile['name'],
838 return; // Somebody is fishing.