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`, `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', %d, %d)",
152 intval(local_user()),
155 dbesc(normalise_link($dfrn_url)),
160 $parms['dfrn-request'],
161 $parms['dfrn-confirm'],
162 $parms['dfrn-notify'],
172 info( t("Introduction complete.") . EOL);
175 $r = q("select id from contact where uid = %d and url = '%s' and `site-pubkey` = '%s' limit 1",
176 intval(local_user()),
178 $parms['key'] // this was already escaped
181 $g = q("select def_gid from user where uid = %d limit 1",
184 if($g && intval($g[0]['def_gid'])) {
185 require_once('include/group.php');
186 group_add_member(local_user(),'',$r[0]['id'],$g[0]['def_gid']);
188 $forwardurl = $a->get_baseurl()."/contacts/".$r[0]['id'];
190 $forwardurl = $a->get_baseurl()."/contacts";
193 * Allow the blocked remote notification to complete
196 if(is_array($contact_record))
197 $dfrn_request = $contact_record['request'];
199 if(strlen($dfrn_request) && strlen($confirm_key))
200 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
202 // (ignore reply, nothing we can do it failed)
204 // Old: goaway(zrl($dfrn_url));
206 return; // NOTREACHED
212 // invalid/bogus request
214 notice( t('Unrecoverable protocol error.') . EOL );
216 return; // NOTREACHED
223 * We are the requestee. A person from a remote cell has made an introduction
224 * on our profile web page and clicked submit. We will use their DFRN-URL to
225 * figure out how to contact their cell.
227 * Scrape the originating DFRN-URL for everything we need. Create a contact record
228 * and an introduction to show our user next time he/she logs in.
229 * Finally redirect back to the requestor so that their site can record the request.
230 * If our user (the requestee) later confirms this request, a record of it will need
231 * to exist on the requestor's cell in order for the confirmation process to complete..
233 * It's possible that neither the requestor or the requestee are logged in at the moment,
234 * and the requestor does not yet have any credentials to the requestee profile.
236 * Who is the requestee? We've already loaded their profile which means their nickname should be
237 * in $a->argv[1] and we should have their complete info in $a->profile.
241 if(! (is_array($a->profile) && count($a->profile))) {
242 notice( t('Profile unavailable.') . EOL);
246 $nickname = $a->profile['nickname'];
247 $notify_flags = $a->profile['notify-flags'];
248 $uid = $a->profile['uid'];
249 $maxreq = intval($a->profile['maxreq']);
250 $contact_record = null;
255 if( x($_POST,'dfrn_url')) {
258 * Block friend request spam
262 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
263 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
266 if(count($r) > $maxreq) {
267 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
268 notice( t('Spam protection measures have been invoked.') . EOL);
269 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
276 * Cleanup old introductions that remain blocked.
277 * Also remove the contact record, but only if there is no existing relationship
278 * Do not remove email contacts as these may be awaiting email verification
281 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
282 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
283 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
284 AND `contact`.`network` != '%s'
285 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ",
291 q("DELETE FROM `contact` WHERE `id` = %d",
295 q("DELETE FROM `intro` WHERE `id` = %d",
303 * Cleanup any old email intros - which will have a greater lifetime
306 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
307 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
308 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
309 AND `contact`.`network` = '%s'
310 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ",
316 q("DELETE FROM `contact` WHERE `id` = %d",
320 q("DELETE FROM `intro` WHERE `id` = %d",
326 $email_follow = (x($_POST,'email_follow') ? intval($_POST['email_follow']) : 0);
327 $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
329 $url = trim($_POST['dfrn_url']);
331 notice( t("Invalid locator") . EOL );
339 if(! validate_email($url)) {
340 notice( t('Invalid email address.') . EOL);
345 $name = ($realname) ? $realname : $addr;
346 $nick = substr($addr,0,strpos($addr,'@'));
347 $url = 'http://' . substr($addr,strpos($addr,'@') + 1);
348 $nurl = normalise_url($host);
349 $poll = 'email ' . random_string();
350 $notify = 'smtp ' . random_string();
353 $network = NETWORK_MAIL2;
354 $rel = CONTACT_IS_FOLLOWER;
356 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
357 if(get_config('system','dfrn_only'))
360 if(! $mail_disabled) {
362 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
367 notice( t('This account has not been configured for email. Request failed.') . EOL);
372 $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
373 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
375 dbesc(datetime_convert()),
389 $r = q("select id from contact where poll = '%s' and uid = %d limit 1",
394 $contact_id = $r[0]['id'];
396 $g = q("select def_gid from user where uid = %d limit 1",
399 if($g && intval($g[0]['def_gid'])) {
400 require_once('include/group.php');
401 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
404 $photo = avatar_img($addr);
406 $r = q("UPDATE `contact` SET
412 `avatar-date` = '%s',
419 dbesc(datetime_convert()),
420 dbesc(datetime_convert()),
421 dbesc(datetime_convert()),
426 // contact is created. Now create an introduction
428 $hash = random_string();
430 $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
431 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
434 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
435 dbesc(notags(trim($_POST['dfrn-request-message']))),
437 dbesc(datetime_convert()),
441 // Next send an email verify form to the requestor.
447 // Canonicalise email-style profile locator
449 $url = webfinger_dfrn($url,$hcard);
451 if(substr($url,0,5) === 'stat:') {
452 $network = NETWORK_OSTATUS;
453 $url = substr($url,5);
456 $network = NETWORK_DFRN;
460 logger('dfrn_request: url: ' . $url);
463 notice( t("Unable to resolve your name at the provided location.") . EOL);
468 if($network === NETWORK_DFRN) {
469 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
475 if(strlen($ret[0]['issued-id'])) {
476 notice( t('You have already introduced yourself here.') . EOL );
479 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
480 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
484 $contact_record = $ret[0];
485 $parms = array('dfrn-request' => $ret[0]['request']);
489 $issued_id = random_string();
491 if(is_array($contact_record)) {
492 // There is a contact record but no issued-id, so this
493 // is a reciprocal introduction from a known contact
494 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
496 intval($contact_record['id'])
500 if(! validate_url($url)) {
501 notice( t('Invalid profile URL.') . EOL);
502 goaway($a->get_baseurl() . '/' . $a->cmd);
503 return; // NOTREACHED
506 if(! allowed_url($url)) {
507 notice( t('Disallowed profile URL.') . EOL);
508 goaway($a->get_baseurl() . '/' . $a->cmd);
509 return; // NOTREACHED
513 require_once('include/Scrape.php');
515 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
517 if(! count($parms)) {
518 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
519 goaway($a->get_baseurl() . '/' . $a->cmd);
523 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
524 if(! x($parms,'photo'))
525 notice( t('Warning: profile location has no profile photo.') . EOL );
526 $invalid = validate_dfrn($parms);
528 notice( sprintf( tt("%d required parameter was not found at the given location",
529 "%d required parameters were not found at the given location",
530 $invalid), $invalid) . EOL );
537 $parms['url'] = $url;
538 $parms['issued-id'] = $issued_id;
542 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`,`name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
543 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
544 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
546 dbesc(datetime_convert()),
548 dbesc(normalise_link($parms['url'])),
554 $parms['dfrn-request'],
555 $parms['dfrn-confirm'],
556 $parms['dfrn-notify'],
562 // find the contact record we just created
564 $r = q("SELECT `id` FROM `contact`
565 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
571 $contact_record = $r[0];
576 notice( t('Failed to update contact record.') . EOL );
580 $hash = random_string() . (string) time(); // Generate a confirm_key
582 if(is_array($contact_record)) {
583 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
584 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
586 intval($contact_record['id']),
587 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
588 dbesc(notags(trim($_POST['dfrn-request-message']))),
590 dbesc(datetime_convert())
594 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
597 info( t('Your introduction has been sent.') . EOL );
599 // "Homecoming" - send the requestor back to their site to record the introduction.
601 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
602 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
604 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
605 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
606 . '&confirm_key=' . $hash
607 . (($aes_allow) ? "&aes_allow=1" : "")
610 // END $network === NETWORK_DFRN
612 elseif($network === NETWORK_OSTATUS) {
617 * Check contact existence
618 * Try and scrape together enough information to create a contact record,
619 * with us as CONTACT_IS_FOLLOWER
620 * Substitute our user's feed URL into $url template
621 * Send the subscriber home to subscribe
625 $url = str_replace('{uri}', $a->get_baseurl() . '/profile/' . $nickname, $url);
628 // END $network === NETWORK_OSTATUS
637 if(! function_exists('dfrn_request_content')) {
638 function dfrn_request_content(&$a) {
640 if(($a->argc != 2) || (! count($a->profile)))
644 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
645 // to send us to the post section to record the introduction.
647 if(x($_GET,'dfrn_url')) {
650 info( t("Please login to confirm introduction.") . EOL );
651 /* setup the return URL to come back to this page if they use openid */
652 $_SESSION['return_url'] = $a->query_string;
656 // Edge case, but can easily happen in the wild. This person is authenticated,
657 // but not as the person who needs to deal with this request.
659 if ($a->user['nickname'] != $a->argv[1]) {
660 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
664 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
665 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
666 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
667 $tpl = get_markup_template("dfrn_req_confirm.tpl");
668 $o = replace_macros($tpl,array(
669 '$dfrn_url' => $dfrn_url,
670 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
671 '$hidethem' => t('Hide this contact'),
672 '$hidechecked' => '',
673 '$confirm_key' => $confirm_key,
674 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
675 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
676 '$submit' => t('Confirm'),
677 '$uid' => $_SESSION['uid'],
678 '$nickname' => $a->user['nickname'],
679 'dfrn_rawurl' => $_GET['dfrn_url']
684 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
686 // we are the requestee and it is now safe to send our user their introduction,
687 // We could just unblock it, but first we have to jump through a few hoops to
688 // send an email, or even to find out if we need to send an email.
690 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
691 dbesc($_GET['confirm_key'])
696 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
697 WHERE `contact`.`id` = %d LIMIT 1",
698 intval($intro[0]['contact-id'])
701 $auto_confirm = false;
704 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
705 $auto_confirm = true;
707 if(! $auto_confirm) {
710 'type' => NOTIFY_INTRO,
711 'notify_flags' => $r[0]['notify-flags'],
712 'language' => $r[0]['language'],
713 'to_name' => $r[0]['username'],
714 'to_email' => $r[0]['email'],
715 'uid' => $r[0]['uid'],
716 'link' => $a->get_baseurl() . '/notifications/intros',
717 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
718 'source_link' => $r[0]['url'],
719 'source_photo' => $r[0]['photo'],
720 'verb' => ACTIVITY_REQ_FRIEND,
726 require_once('mod/dfrn_confirm.php');
728 'uid' => $r[0]['uid'],
729 'node' => $r[0]['nickname'],
730 'dfrn_id' => $r[0]['issued-id'],
731 'intro_id' => $intro[0]['id'],
732 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
733 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
735 dfrn_confirm_post($a,$handsfree);
740 if(! $auto_confirm) {
742 // If we are auto_confirming, this record will have already been nuked
743 // in dfrn_confirm_post()
745 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
746 dbesc($_GET['confirm_key'])
752 return; // NOTREACHED
757 * Normal web request. Display our user's introduction form.
760 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
761 if(! get_config('system','local_block')) {
762 notice( t('Public access denied.') . EOL);
769 * Try to auto-fill the profile address
772 // At first look if an address was provided
773 // Otherwise take the local address
774 if (x($_GET,'addr') AND ($_GET['addr'] != ""))
775 $myaddr = hex2bin($_GET['addr']);
776 elseif (x($_GET,'address') AND ($_GET['address'] != ""))
777 $myaddr = $_GET['address'];
778 elseif(local_user()) {
779 if(strlen($a->path)) {
780 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
783 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
785 } else // last, try a zrl
786 $myaddr = get_my_url();
788 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
793 * The auto_request form only has the profile address
794 * because nobody is going to read the comments and
795 * it doesn't matter if they know you or not.
799 if($a->profile['page-flags'] == PAGE_NORMAL)
800 $tpl = get_markup_template('dfrn_request.tpl');
802 $tpl = get_markup_template('auto_request.tpl');
804 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported communications networks:");
806 // see if we are allowed to have NETWORK_MAIL2 contacts
808 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
809 if(get_config('system','dfrn_only'))
812 if(! $mail_disabled) {
813 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
814 intval($a->profile['uid'])
820 // "coming soon" is disabled for now
821 //$emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
824 $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>.');
826 $o .= replace_macros($tpl,array(
827 '$header' => t('Friend/Connection Request'),
828 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
829 '$pls_answer' => t('Please answer the following:'),
830 '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'),$a->profile['name']), false, '', array(t('No'),t('Yes'))),
831 /*'$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
834 '$add_note' => t('Add a personal note:'),
835 '$page_desc' => $page_desc,
836 '$friendica' => t('Friendica'),
837 '$statusnet' => t('StatusNet/Federated Social Web'),
838 '$diaspora' => t('Diaspora'),
839 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
840 '$your_address' => t('Your Identity Address:'),
841 '$invite_desc' => $invite_desc,
842 '$emailnet' => $emailnet,
843 '$submit' => t('Submit Request'),
844 '$cancel' => t('Cancel'),
845 '$nickname' => $a->argv[1],
846 '$name' => $a->profile['name'],
852 return; // Somebody is fishing.