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
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 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ");
264 q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
268 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
274 $url = trim($_POST['dfrn_url']);
276 notice( t("Invalid locator") . EOL );
280 // Canonicalise email-style profile locator
283 $url = webfinger_dfrn($url,$hcard);
285 if(substr($url,0,5) === 'stat:') {
286 $network = NETWORK_OSTATUS;
287 $url = substr($url,5);
290 $network = NETWORK_DFRN;
293 logger('dfrn_request: url: ' . $url);
296 notice( t("Unable to resolve your name at the provided location.") . EOL);
301 if($network === NETWORK_DFRN) {
302 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
308 if(strlen($ret[0]['issued-id'])) {
309 notice( t('You have already introduced yourself here.') . EOL );
312 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
313 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
317 $contact_record = $ret[0];
318 $parms = array('dfrn-request' => $ret[0]['request']);
322 $issued_id = random_string();
324 if(is_array($contact_record)) {
325 // There is a contact record but no issued-id, so this
326 // is a reciprocal introduction from a known contact
327 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1",
329 intval($contact_record['id'])
333 if(! validate_url($url)) {
334 notice( t('Invalid profile URL.') . EOL);
335 goaway($a->get_baseurl() . '/' . $a->cmd);
336 return; // NOTREACHED
339 if(! allowed_url($url)) {
340 notice( t('Disallowed profile URL.') . EOL);
341 goaway($a->get_baseurl() . '/' . $a->cmd);
342 return; // NOTREACHED
346 require_once('Scrape.php');
348 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
350 if(! count($parms)) {
351 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
352 goaway($a->get_baseurl() . '/' . $a->cmd);
356 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
357 if(! x($parms,'photo'))
358 notice( t('Warning: profile location has no profile photo.') . EOL );
359 $invalid = validate_dfrn($parms);
361 notice( sprintf( tt("%d required parameter was not found at the given location",
362 "%d required parameters were not found at the given location",
363 $invalid), $invalid) . EOL );
370 $parms['url'] = $url;
371 $parms['issued-id'] = $issued_id;
375 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`,`name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
376 `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
377 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
379 dbesc(datetime_convert()),
381 dbesc(normalise_link($parms['url'])),
387 $parms['dfrn-request'],
388 $parms['dfrn-confirm'],
389 $parms['dfrn-notify'],
395 // find the contact record we just created
397 $r = q("SELECT `id` FROM `contact`
398 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
404 $contact_record = $r[0];
409 notice( t('Failed to update contact record.') . EOL );
413 $hash = random_string() . (string) time(); // Generate a confirm_key
415 if(is_array($contact_record)) {
416 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
417 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
419 intval($contact_record['id']),
420 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
421 dbesc(notags(trim($_POST['dfrn-request-message']))),
423 dbesc(datetime_convert())
427 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
430 info( t('Your introduction has been sent.') . EOL );
432 // "Homecoming" - send the requestor back to their site to record the introduction.
434 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
435 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
437 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
438 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
439 . '&confirm_key=' . $hash
440 . (($aes_allow) ? "&aes_allow=1" : "")
443 // END $network === NETWORK_DFRN
445 elseif($network === NETWORK_OSTATUS) {
450 * Check contact existence
451 * Try and scrape together enough information to create a contact record,
452 * with us as CONTACT_IS_FOLLOWER
453 * Substitute our user's feed URL into $url template
454 * Send the subscriber home to subscribe
458 $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url);
461 // END $network === NETWORK_OSTATUS
470 if(! function_exists('dfrn_request_content')) {
471 function dfrn_request_content(&$a) {
473 if(($a->argc != 2) || (! count($a->profile)))
477 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
478 // to send us to the post section to record the introduction.
480 if(x($_GET,'dfrn_url')) {
483 info( t("Please login to confirm introduction.") . EOL );
485 /* setup the return URL to come back to this page if they use openid */
487 $stripped = str_replace('q=','',$a->query_string);
488 $_SESSION['return_url'] = trim($stripped,'/');
493 // Edge case, but can easily happen in the wild. This person is authenticated,
494 // but not as the person who needs to deal with this request.
496 if ($a->user['nickname'] != $a->argv[1]) {
497 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
501 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
502 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
503 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
504 $tpl = get_markup_template("dfrn_req_confirm.tpl");
505 $o = replace_macros($tpl,array(
506 '$dfrn_url' => $dfrn_url,
507 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
508 '$confirm_key' => $confirm_key,
509 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
510 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
511 '$submit' => t('Confirm'),
512 '$uid' => $_SESSION['uid'],
513 '$nickname' => $a->user['nickname'],
514 'dfrn_rawurl' => $_GET['dfrn_url']
519 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
521 // we are the requestee and it is now safe to send our user their introduction,
522 // We could just unblock it, but first we have to jump through a few hoops to
523 // send an email, or even to find out if we need to send an email.
525 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
526 dbesc($_GET['confirm_key'])
531 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
532 WHERE `contact`.`id` = %d LIMIT 1",
533 intval($intro[0]['contact-id'])
536 $auto_confirm = false;
539 if($r[0]['page-flags'] != PAGE_NORMAL)
540 $auto_confirm = true;
541 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && (! $auto_confirm)) {
542 $email_tpl = get_intltext_template('request_notify_eml.tpl');
543 $email = replace_macros($email_tpl, array(
544 '$requestor' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
545 '$url' => stripslashes($r[0]['url']),
546 '$myname' => $r[0]['username'],
547 '$siteurl' => $a->get_baseurl(),
548 '$sitename' => $a->config['sitename']
550 $res = mail($r[0]['email'],
551 t("Introduction received at ") . $a->config['sitename'],
553 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
554 . 'Content-type: text/plain; charset=UTF-8' . "\n"
555 . 'Content-transfer-encoding: 8bit' );
557 // This is a redundant notification - no point throwing errors if it fails.
560 require_once('mod/dfrn_confirm.php');
562 'uid' => $r[0]['uid'],
563 'node' => $r[0]['nickname'],
564 'dfrn_id' => $r[0]['issued-id'],
565 'intro_id' => $intro[0]['id'],
566 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0)
568 dfrn_confirm_post($a,$handsfree);
573 if(! $auto_confirm) {
575 // If we are auto_confirming, this record will have already been nuked
576 // in dfrn_confirm_post()
578 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s' LIMIT 1",
579 dbesc($_GET['confirm_key'])
585 return; // NOTREACHED
590 * Normal web request. Display our user's introduction form.
593 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
594 notice( t('Public access denied.') . EOL);
600 * Try to auto-fill the profile address
604 if(strlen($a->path)) {
605 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
608 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
611 elseif(x($_GET,'addr')) {
612 $myaddr = hex2bin($_GET['addr']);
615 /* $_GET variables are already urldecoded */
616 $myaddr = ((x($_GET,'address')) ? $_GET['address'] : '');
619 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
624 * The auto_request form only has the profile address
625 * because nobody is going to read the comments and
626 * it doesn't matter if they know you or not.
630 if($a->profile['page-flags'] == PAGE_NORMAL)
631 $tpl = get_markup_template('dfrn_request.tpl');
633 $tpl = get_markup_template('auto_request.tpl');
635 $page_desc = sprintf( t('Diaspora members: Please do not use this form. Instead, enter "%s" into your Diaspora search bar.'),
636 $target_addr) . EOL . EOL;
638 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported social networks:");
640 $o .= replace_macros($tpl,array(
641 '$header' => t('Friend/Connection Request'),
642 '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
643 '$pls_answer' => t('Please answer the following:'),
644 '$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
647 '$add_note' => t('Add a personal note:'),
648 '$page_desc' => $page_desc,
649 '$friendika' => t('Friendica'),
650 '$statusnet' => t('StatusNet/Federated Social Web'),
651 '$diaspora' => t('Diaspora'),
652 '$diasnote' => t('- please share from your own site as noted above'),
653 '$your_address' => t('Your Identity Address:'),
654 '$submit' => t('Submit Request'),
655 '$cancel' => t('Cancel'),
656 '$nickname' => $a->argv[1],
657 '$name' => $a->profile['name'],
663 return; // Somebody is fishing.