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'] : "");
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 WHERE `id` = %d LIMIT 1",
103 intval($contact_record['id'])
109 * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
112 require_once('Scrape.php');
114 $parms = scrape_dfrn($dfrn_url);
116 if(! count($parms)) {
117 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
122 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
123 if(! x($parms,'photo'))
124 notice( t('Warning: profile location has no profile photo.') . EOL );
125 $invalid = validate_dfrn($parms);
127 notice( sprintf( tt("%d required parameter was not found at the given location",
128 "%d required parameters were not found at the given location",
129 $invalid), $invalid) . EOL );
134 $dfrn_request = $parms['dfrn-request'];
136 /********* Escape the entire array ********/
140 /******************************************/
143 * Create a contact record on our site for the other person
146 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `name`, `nick`, `photo`, `site-pubkey`,
147 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`)
148 VALUES ( %d, '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
149 intval(local_user()),
152 dbesc(normalise_link($dfrn_url)),
157 $parms['dfrn-request'],
158 $parms['dfrn-confirm'],
159 $parms['dfrn-notify'],
168 info( t("Introduction complete.") . EOL);
172 * Allow the blocked remote notification to complete
175 if(is_array($contact_record))
176 $dfrn_request = $contact_record['request'];
178 if(strlen($dfrn_request) && strlen($confirm_key))
179 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
181 // (ignore reply, nothing we can do it failed)
183 goaway(zrl($dfrn_url));
184 return; // NOTREACHED
190 // invalid/bogus request
192 notice( t('Unrecoverable protocol error.') . EOL );
194 return; // NOTREACHED
201 * We are the requestee. A person from a remote cell has made an introduction
202 * on our profile web page and clicked submit. We will use their DFRN-URL to
203 * figure out how to contact their cell.
205 * Scrape the originating DFRN-URL for everything we need. Create a contact record
206 * and an introduction to show our user next time he/she logs in.
207 * Finally redirect back to the requestor so that their site can record the request.
208 * If our user (the requestee) later confirms this request, a record of it will need
209 * to exist on the requestor's cell in order for the confirmation process to complete..
211 * It's possible that neither the requestor or the requestee are logged in at the moment,
212 * and the requestor does not yet have any credentials to the requestee profile.
214 * Who is the requestee? We've already loaded their profile which means their nickname should be
215 * in $a->argv[1] and we should have their complete info in $a->profile.
219 if(! (is_array($a->profile) && count($a->profile))) {
220 notice( t('Profile unavailable.') . EOL);
224 $nickname = $a->profile['nickname'];
225 $notify_flags = $a->profile['notify-flags'];
226 $uid = $a->profile['uid'];
227 $maxreq = intval($a->profile['maxreq']);
228 $contact_record = null;
233 if( x($_POST,'dfrn_url')) {
236 * Block friend request spam
240 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
241 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
244 if(count($r) > $maxreq) {
245 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
246 notice( t('Spam protection measures have been invoked.') . EOL);
247 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
254 * Cleanup old introductions that remain blocked.
255 * Also remove the contact record, but only if there is no existing relationship
256 * Do not remove email contacts as these may be awaiting email verification
259 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
260 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
261 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
262 AND `contact`.`network` != '%s'
263 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ",
269 q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
273 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
281 * Cleanup any old email intros - which will have a greater lifetime
284 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
285 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
286 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
287 AND `contact`.`network` = '%s'
288 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ",
294 q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
298 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
304 $email_follow = (x($_POST,'email_follow') ? intval($_POST['email_follow']) : 0);
305 $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
307 $url = trim($_POST['dfrn_url']);
309 notice( t("Invalid locator") . EOL );
317 if(! validate_email($url)) {
318 notice( t('Invalid email address.') . EOL);
323 $name = ($realname) ? $realname : $addr;
324 $nick = substr($addr,0,strpos($addr,'@'));
325 $url = 'http://' . substr($addr,strpos($addr,'@') + 1);
326 $nurl = normalise_url($host);
327 $poll = 'email ' . random_string();
328 $notify = 'smtp ' . random_string();
331 $network = NETWORK_MAIL2;
332 $rel = CONTACT_IS_FOLLOWER;
334 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
335 if(get_config('system','dfrn_only'))
338 if(! $mail_disabled) {
340 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
344 notice( t('This account has not been configured for email. Request failed.') . EOL);
349 $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
350 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
352 dbesc(datetime_convert()),
366 $r = q("select id from contact where poll = '%s' and uid = %d limit 1",
371 $contact_id = $r[0]['id'];
373 $photo = avatar_img($addr);
375 $r = q("UPDATE `contact` SET
381 `avatar-date` = '%s',
383 WHERE `id` = %d LIMIT 1
388 dbesc(datetime_convert()),
389 dbesc(datetime_convert()),
390 dbesc(datetime_convert()),
395 // contact is created. Now create an introduction
397 $hash = random_string();
399 $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
400 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
403 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
404 dbesc(notags(trim($_POST['dfrn-request-message']))),
406 dbesc(datetime_convert()),
410 // Next send an email verify form to the requestor.
416 // Canonicalise email-style profile locator
418 $url = webfinger_dfrn($url,$hcard);
420 if(substr($url,0,5) === 'stat:') {
421 $network = NETWORK_OSTATUS;
422 $url = substr($url,5);
425 $network = NETWORK_DFRN;
429 logger('dfrn_request: url: ' . $url);
432 notice( t("Unable to resolve your name at the provided location.") . EOL);
437 if($network === NETWORK_DFRN) {
438 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
444 if(strlen($ret[0]['issued-id'])) {
445 notice( t('You have already introduced yourself here.') . EOL );
448 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
449 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
453 $contact_record = $ret[0];
454 $parms = array('dfrn-request' => $ret[0]['request']);
458 $issued_id = random_string();
460 if(is_array($contact_record)) {
461 // There is a contact record but no issued-id, so this
462 // is a reciprocal introduction from a known contact
463 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1",
465 intval($contact_record['id'])
469 if(! validate_url($url)) {
470 notice( t('Invalid profile URL.') . EOL);
471 goaway($a->get_baseurl() . '/' . $a->cmd);
472 return; // NOTREACHED
475 if(! allowed_url($url)) {
476 notice( t('Disallowed profile URL.') . EOL);
477 goaway($a->get_baseurl() . '/' . $a->cmd);
478 return; // NOTREACHED
482 require_once('Scrape.php');
484 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
486 if(! count($parms)) {
487 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
488 goaway($a->get_baseurl() . '/' . $a->cmd);
492 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
493 if(! x($parms,'photo'))
494 notice( t('Warning: profile location has no profile photo.') . EOL );
495 $invalid = validate_dfrn($parms);
497 notice( sprintf( tt("%d required parameter was not found at the given location",
498 "%d required parameters were not found at the given location",
499 $invalid), $invalid) . EOL );
506 $parms['url'] = $url;
507 $parms['issued-id'] = $issued_id;
511 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`,`name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
512 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
513 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
515 dbesc(datetime_convert()),
517 dbesc(normalise_link($parms['url'])),
523 $parms['dfrn-request'],
524 $parms['dfrn-confirm'],
525 $parms['dfrn-notify'],
531 // find the contact record we just created
533 $r = q("SELECT `id` FROM `contact`
534 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
540 $contact_record = $r[0];
545 notice( t('Failed to update contact record.') . EOL );
549 $hash = random_string() . (string) time(); // Generate a confirm_key
551 if(is_array($contact_record)) {
552 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
553 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
555 intval($contact_record['id']),
556 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
557 dbesc(notags(trim($_POST['dfrn-request-message']))),
559 dbesc(datetime_convert())
563 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
566 info( t('Your introduction has been sent.') . EOL );
568 // "Homecoming" - send the requestor back to their site to record the introduction.
570 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
571 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
573 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
574 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
575 . '&confirm_key=' . $hash
576 . (($aes_allow) ? "&aes_allow=1" : "")
579 // END $network === NETWORK_DFRN
581 elseif($network === NETWORK_OSTATUS) {
586 * Check contact existence
587 * Try and scrape together enough information to create a contact record,
588 * with us as CONTACT_IS_FOLLOWER
589 * Substitute our user's feed URL into $url template
590 * Send the subscriber home to subscribe
594 $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url);
597 // END $network === NETWORK_OSTATUS
606 if(! function_exists('dfrn_request_content')) {
607 function dfrn_request_content(&$a) {
609 if(($a->argc != 2) || (! count($a->profile)))
613 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
614 // to send us to the post section to record the introduction.
616 if(x($_GET,'dfrn_url')) {
619 info( t("Please login to confirm introduction.") . EOL );
621 /* setup the return URL to come back to this page if they use openid */
623 $stripped = str_replace('q=','',$a->query_string);
624 $_SESSION['return_url'] = trim($stripped,'/');
629 // Edge case, but can easily happen in the wild. This person is authenticated,
630 // but not as the person who needs to deal with this request.
632 if ($a->user['nickname'] != $a->argv[1]) {
633 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
637 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
638 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
639 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
640 $tpl = get_markup_template("dfrn_req_confirm.tpl");
641 $o = replace_macros($tpl,array(
642 '$dfrn_url' => $dfrn_url,
643 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
644 '$confirm_key' => $confirm_key,
645 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
646 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
647 '$submit' => t('Confirm'),
648 '$uid' => $_SESSION['uid'],
649 '$nickname' => $a->user['nickname'],
650 'dfrn_rawurl' => $_GET['dfrn_url']
655 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
657 // we are the requestee and it is now safe to send our user their introduction,
658 // We could just unblock it, but first we have to jump through a few hoops to
659 // send an email, or even to find out if we need to send an email.
661 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
662 dbesc($_GET['confirm_key'])
667 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
668 WHERE `contact`.`id` = %d LIMIT 1",
669 intval($intro[0]['contact-id'])
672 $auto_confirm = false;
675 if($r[0]['page-flags'] != PAGE_NORMAL)
676 $auto_confirm = true;
678 if(! $auto_confirm) {
679 require_once('include/enotify.php');
681 'type' => NOTIFY_INTRO,
682 'notify_flags' => $r[0]['notify-flags'],
683 'language' => $r[0]['language'],
684 'to_name' => $r[0]['username'],
685 'to_email' => $r[0]['email'],
686 'uid' => $r[0]['uid'],
687 'link' => $a->get_baseurl() . '/notifications/intros',
688 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
689 'source_link' => $r[0]['url'],
690 'source_photo' => $r[0]['photo'],
691 'verb' => ACTIVITY_REQ_FRIEND,
697 require_once('mod/dfrn_confirm.php');
699 'uid' => $r[0]['uid'],
700 'node' => $r[0]['nickname'],
701 'dfrn_id' => $r[0]['issued-id'],
702 'intro_id' => $intro[0]['id'],
703 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
704 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
706 dfrn_confirm_post($a,$handsfree);
711 if(! $auto_confirm) {
713 // If we are auto_confirming, this record will have already been nuked
714 // in dfrn_confirm_post()
716 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s' LIMIT 1",
717 dbesc($_GET['confirm_key'])
723 return; // NOTREACHED
728 * Normal web request. Display our user's introduction form.
731 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
732 notice( t('Public access denied.') . EOL);
738 * Try to auto-fill the profile address
742 if(strlen($a->path)) {
743 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
746 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
749 elseif(x($_GET,'addr')) {
750 $myaddr = hex2bin($_GET['addr']);
753 /* $_GET variables are already urldecoded */
754 $myaddr = ((x($_GET,'address')) ? $_GET['address'] : '');
758 if(! strlen($myaddr))
759 $myaddr = get_my_url();
762 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
767 * The auto_request form only has the profile address
768 * because nobody is going to read the comments and
769 * it doesn't matter if they know you or not.
773 if($a->profile['page-flags'] == PAGE_NORMAL)
774 $tpl = get_markup_template('dfrn_request.tpl');
776 $tpl = get_markup_template('auto_request.tpl');
778 # $page_desc = sprintf( t('Diaspora members: Please do not use this form. Instead, enter "%s" into your Diaspora search bar.'),
779 # $target_addr) . EOL . EOL;
781 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported communications networks:");
783 // see if we are allowed to have NETWORK_MAIL2 contacts
785 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
786 if(get_config('system','dfrn_only'))
789 if(! $mail_disabled) {
790 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
791 intval($a->profile['uid'])
797 $emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
799 $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>.');
801 $o .= replace_macros($tpl,array(
802 '$header' => t('Friend/Connection Request'),
803 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
804 '$pls_answer' => t('Please answer the following:'),
805 '$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
808 '$add_note' => t('Add a personal note:'),
809 '$page_desc' => $page_desc,
810 '$friendica' => t('Friendica'),
811 '$statusnet' => t('StatusNet/Federated Social Web'),
812 '$diaspora' => t('Diaspora'),
813 '$diasnote' => sprintf (t(' - please do not use this form. Instead, enter %s into your Diaspora search bar.'),$target_addr),
814 '$your_address' => t('Your Identity Address:'),
815 '$invite_desc' => $invite_desc,
816 '$emailnet' => $emailnet,
817 '$submit' => t('Submit Request'),
818 '$cancel' => t('Cancel'),
819 '$nickname' => $a->argv[1],
820 '$name' => $a->profile['name'],
826 return; // Somebody is fishing.