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($_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' AND `self` = 0 LIMIT 1",
86 if(strlen($r[0]['dfrn-id'])) {
89 * We don't need to be here. It has already happened.
92 notice( t("This introduction has already been accepted.") . EOL );
96 $contact_record = $r[0];
99 if(is_array($contact_record)) {
100 $r = q("UPDATE `contact` SET `ret-aes` = %d WHERE `id` = %d LIMIT 1",
102 intval($contact_record['id'])
108 * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
111 require_once('Scrape.php');
113 $parms = scrape_dfrn($dfrn_url);
115 if(! count($parms)) {
116 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
121 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
122 if(! x($parms,'photo'))
123 notice( t('Warning: profile location has no profile photo.') . EOL );
124 $invalid = validate_dfrn($parms);
126 notice( sprintf( tt("%d required parameter was not found at the given location",
127 "%d required parameters were not found at the given location",
128 $invalid), $invalid) . EOL );
133 $dfrn_request = $parms['dfrn-request'];
135 /********* Escape the entire array ********/
139 /******************************************/
142 * Create a contact record on our site for the other person
145 $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `name`, `nick`, `photo`, `site-pubkey`,
146 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`)
147 VALUES ( %d, '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
148 intval(local_user()),
151 dbesc(normalise_link($dfrn_url)),
156 $parms['dfrn-request'],
157 $parms['dfrn-confirm'],
158 $parms['dfrn-notify'],
167 info( t("Introduction complete.") . EOL);
171 * Allow the blocked remote notification to complete
174 if(is_array($contact_record))
175 $dfrn_request = $contact_record['request'];
177 if(strlen($dfrn_request) && strlen($confirm_key))
178 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
180 // (ignore reply, nothing we can do it failed)
183 return; // NOTREACHED
189 // invalid/bogus request
191 notice( t('Unrecoverable protocol error.') . EOL );
193 return; // NOTREACHED
200 * We are the requestee. A person from a remote cell has made an introduction
201 * on our profile web page and clicked submit. We will use their DFRN-URL to
202 * figure out how to contact their cell.
204 * Scrape the originating DFRN-URL for everything we need. Create a contact record
205 * and an introduction to show our user next time he/she logs in.
206 * Finally redirect back to the requestor so that their site can record the request.
207 * If our user (the requestee) later confirms this request, a record of it will need
208 * to exist on the requestor's cell in order for the confirmation process to complete..
210 * It's possible that neither the requestor or the requestee are logged in at the moment,
211 * and the requestor does not yet have any credentials to the requestee profile.
213 * Who is the requestee? We've already loaded their profile which means their nickname should be
214 * in $a->argv[1] and we should have their complete info in $a->profile.
218 if(! (is_array($a->profile) && count($a->profile))) {
219 notice( t('Profile unavailable.') . EOL);
223 $nickname = $a->profile['nickname'];
224 $notify_flags = $a->profile['notify-flags'];
225 $uid = $a->profile['uid'];
226 $maxreq = intval($a->profile['maxreq']);
227 $contact_record = null;
232 if( x($_POST,'dfrn_url')) {
235 * Block friend request spam
239 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
240 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
243 if(count($r) > $maxreq) {
244 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
245 notice( t('Spam protection measures have been invoked.') . EOL);
246 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
253 * Cleanup old introductions that remain blocked.
254 * Also remove the contact record, but only if there is no existing relationship
255 * Do not remove email contacts as these may be awaiting email verification
258 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
259 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
260 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
261 AND `contact`.`network` != '%s'
262 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ",
268 q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
272 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
280 * Cleanup any old email intros - which will have a greater lifetime
283 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
284 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
285 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
286 AND `contact`.`network` = '%s'
287 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ",
293 q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
297 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
304 $url = trim($_POST['dfrn_url']);
306 notice( t("Invalid locator") . EOL );
310 // Canonicalise email-style profile locator
313 $url = webfinger_dfrn($url,$hcard);
315 if(substr($url,0,5) === 'stat:') {
316 $network = NETWORK_OSTATUS;
317 $url = substr($url,5);
320 $network = NETWORK_DFRN;
323 logger('dfrn_request: url: ' . $url);
326 notice( t("Unable to resolve your name at the provided location.") . EOL);
331 if($network === NETWORK_DFRN) {
332 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
338 if(strlen($ret[0]['issued-id'])) {
339 notice( t('You have already introduced yourself here.') . EOL );
342 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
343 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
347 $contact_record = $ret[0];
348 $parms = array('dfrn-request' => $ret[0]['request']);
352 $issued_id = random_string();
354 if(is_array($contact_record)) {
355 // There is a contact record but no issued-id, so this
356 // is a reciprocal introduction from a known contact
357 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1",
359 intval($contact_record['id'])
363 if(! validate_url($url)) {
364 notice( t('Invalid profile URL.') . EOL);
365 goaway($a->get_baseurl() . '/' . $a->cmd);
366 return; // NOTREACHED
369 if(! allowed_url($url)) {
370 notice( t('Disallowed profile URL.') . EOL);
371 goaway($a->get_baseurl() . '/' . $a->cmd);
372 return; // NOTREACHED
376 require_once('Scrape.php');
378 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
380 if(! count($parms)) {
381 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
382 goaway($a->get_baseurl() . '/' . $a->cmd);
386 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
387 if(! x($parms,'photo'))
388 notice( t('Warning: profile location has no profile photo.') . EOL );
389 $invalid = validate_dfrn($parms);
391 notice( sprintf( tt("%d required parameter was not found at the given location",
392 "%d required parameters were not found at the given location",
393 $invalid), $invalid) . EOL );
400 $parms['url'] = $url;
401 $parms['issued-id'] = $issued_id;
405 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`,`name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
406 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
407 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
409 dbesc(datetime_convert()),
411 dbesc(normalise_link($parms['url'])),
417 $parms['dfrn-request'],
418 $parms['dfrn-confirm'],
419 $parms['dfrn-notify'],
425 // find the contact record we just created
427 $r = q("SELECT `id` FROM `contact`
428 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
434 $contact_record = $r[0];
439 notice( t('Failed to update contact record.') . EOL );
443 $hash = random_string() . (string) time(); // Generate a confirm_key
445 if(is_array($contact_record)) {
446 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
447 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
449 intval($contact_record['id']),
450 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
451 dbesc(notags(trim($_POST['dfrn-request-message']))),
453 dbesc(datetime_convert())
457 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
460 info( t('Your introduction has been sent.') . EOL );
462 // "Homecoming" - send the requestor back to their site to record the introduction.
464 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
465 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
467 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
468 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
469 . '&confirm_key=' . $hash
470 . (($aes_allow) ? "&aes_allow=1" : "")
473 // END $network === NETWORK_DFRN
475 elseif($network === NETWORK_OSTATUS) {
480 * Check contact existence
481 * Try and scrape together enough information to create a contact record,
482 * with us as CONTACT_IS_FOLLOWER
483 * Substitute our user's feed URL into $url template
484 * Send the subscriber home to subscribe
488 $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url);
491 // END $network === NETWORK_OSTATUS
500 if(! function_exists('dfrn_request_content')) {
501 function dfrn_request_content(&$a) {
503 if(($a->argc != 2) || (! count($a->profile)))
507 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
508 // to send us to the post section to record the introduction.
510 if(x($_GET,'dfrn_url')) {
513 info( t("Please login to confirm introduction.") . EOL );
515 /* setup the return URL to come back to this page if they use openid */
517 $stripped = str_replace('q=','',$a->query_string);
518 $_SESSION['return_url'] = trim($stripped,'/');
523 // Edge case, but can easily happen in the wild. This person is authenticated,
524 // but not as the person who needs to deal with this request.
526 if ($a->user['nickname'] != $a->argv[1]) {
527 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
531 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
532 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
533 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
534 $tpl = get_markup_template("dfrn_req_confirm.tpl");
535 $o = replace_macros($tpl,array(
536 '$dfrn_url' => $dfrn_url,
537 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
538 '$confirm_key' => $confirm_key,
539 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
540 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
541 '$submit' => t('Confirm'),
542 '$uid' => $_SESSION['uid'],
543 '$nickname' => $a->user['nickname'],
544 'dfrn_rawurl' => $_GET['dfrn_url']
549 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
551 // we are the requestee and it is now safe to send our user their introduction,
552 // We could just unblock it, but first we have to jump through a few hoops to
553 // send an email, or even to find out if we need to send an email.
555 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
556 dbesc($_GET['confirm_key'])
561 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
562 WHERE `contact`.`id` = %d LIMIT 1",
563 intval($intro[0]['contact-id'])
566 $auto_confirm = false;
569 if($r[0]['page-flags'] != PAGE_NORMAL)
570 $auto_confirm = true;
572 if(! $auto_confirm) {
573 require_once('include/enotify.php');
575 'type' => NOTIFY_INTRO,
576 'notify_flags' => $r[0]['notify-flags'],
577 'language' => $r[0]['language'],
578 'to_name' => $r[0]['username'],
579 'to_email' => $r[0]['email'],
580 'uid' => $r[0]['uid'],
581 'link' => $a->get_baseurl() . '/notifications/intros',
582 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
583 'source_link' => $r[0]['url'],
584 'source_photo' => $r[0]['photo'],
585 'verb' => ACTIVITY_REQ_FRIEND,
591 require_once('mod/dfrn_confirm.php');
593 'uid' => $r[0]['uid'],
594 'node' => $r[0]['nickname'],
595 'dfrn_id' => $r[0]['issued-id'],
596 'intro_id' => $intro[0]['id'],
597 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0)
599 dfrn_confirm_post($a,$handsfree);
604 if(! $auto_confirm) {
606 // If we are auto_confirming, this record will have already been nuked
607 // in dfrn_confirm_post()
609 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s' LIMIT 1",
610 dbesc($_GET['confirm_key'])
616 return; // NOTREACHED
621 * Normal web request. Display our user's introduction form.
624 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
625 notice( t('Public access denied.') . EOL);
631 * Try to auto-fill the profile address
635 if(strlen($a->path)) {
636 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
639 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
642 elseif(x($_GET,'addr')) {
643 $myaddr = hex2bin($_GET['addr']);
646 /* $_GET variables are already urldecoded */
647 $myaddr = ((x($_GET,'address')) ? $_GET['address'] : '');
650 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
655 * The auto_request form only has the profile address
656 * because nobody is going to read the comments and
657 * it doesn't matter if they know you or not.
661 if($a->profile['page-flags'] == PAGE_NORMAL)
662 $tpl = get_markup_template('dfrn_request.tpl');
664 $tpl = get_markup_template('auto_request.tpl');
666 $page_desc = sprintf( t('Diaspora members: Please do not use this form. Instead, enter "%s" into your Diaspora search bar.'),
667 $target_addr) . EOL . EOL;
669 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported social networks:");
671 $o .= replace_macros($tpl,array(
672 '$header' => t('Friend/Connection Request'),
673 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
674 '$pls_answer' => t('Please answer the following:'),
675 '$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
678 '$add_note' => t('Add a personal note:'),
679 '$page_desc' => $page_desc,
680 '$friendica' => t('Friendica'),
681 '$statusnet' => t('StatusNet/Federated Social Web'),
682 '$diaspora' => t('Diaspora'),
683 '$diasnote' => t('- please share from your own site as noted above'),
684 '$your_address' => t('Your Identity Address:'),
685 '$submit' => t('Submit Request'),
686 '$cancel' => t('Cancel'),
687 '$nickname' => $a->argv[1],
688 '$name' => $a->profile['name'],
694 return; // Somebody is fishing.