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`, `name`, `nick`, `photo`, `site-pubkey`,
146 `request`, `confirm`, `notify`, `poll`, `network`, `aes_allow`)
147 VALUES ( %d, '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
148 intval(local_user()),
155 $parms['dfrn-request'],
156 $parms['dfrn-confirm'],
157 $parms['dfrn-notify'],
165 info( t("Introduction complete.") . EOL);
169 * Allow the blocked remote notification to complete
172 if(is_array($contact_record))
173 $dfrn_request = $contact_record['request'];
175 if(strlen($dfrn_request) && strlen($confirm_key))
176 $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
178 // (ignore reply, nothing we can do it failed)
181 return; // NOTREACHED
187 // invalid/bogus request
189 notice( t('Unrecoverable protocol error.') . EOL );
191 return; // NOTREACHED
198 * We are the requestee. A person from a remote cell has made an introduction
199 * on our profile web page and clicked submit. We will use their DFRN-URL to
200 * figure out how to contact their cell.
202 * Scrape the originating DFRN-URL for everything we need. Create a contact record
203 * and an introduction to show our user next time he/she logs in.
204 * Finally redirect back to the requestor so that their site can record the request.
205 * If our user (the requestee) later confirms this request, a record of it will need
206 * to exist on the requestor's cell in order for the confirmation process to complete..
208 * It's possible that neither the requestor or the requestee are logged in at the moment,
209 * and the requestor does not yet have any credentials to the requestee profile.
211 * Who is the requestee? We've already loaded their profile which means their nickname should be
212 * in $a->argv[1] and we should have their complete info in $a->profile.
216 if(! (is_array($a->profile) && count($a->profile))) {
217 notice( t('Profile unavailable.') . EOL);
221 $nickname = $a->profile['nickname'];
222 $notify_flags = $a->profile['notify-flags'];
223 $uid = $a->profile['uid'];
224 $maxreq = intval($a->profile['maxreq']);
225 $contact_record = null;
230 if( x($_POST,'dfrn_url')) {
233 * Block friend request spam
237 $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
238 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
241 if(count($r) > $maxreq) {
242 notice( sprintf( t('%s has received too many connection requests today.'), $a->profile['name']) . EOL);
243 notice( t('Spam protection measures have been invoked.') . EOL);
244 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
251 * Cleanup old introductions that remain blocked.
252 * Also remove the contact record, but only if there is no existing relationship
256 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
257 FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
258 WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ");
262 q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
266 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
272 $url = trim($_POST['dfrn_url']);
274 notice( t("Invalid locator") . EOL );
278 // Canonicalise email-style profile locator
280 $url = webfinger_dfrn($url);
282 if(substr($url,0,5) === 'stat:') {
284 $url = substr($url,5);
290 logger('dfrn_request: url: ' . $url);
293 notice( t("Unable to resolve your name at the provided location.") . EOL);
298 if($network === NETWORK_DFRN) {
299 $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
305 if(strlen($ret[0]['issued-id'])) {
306 notice( t('You have already introduced yourself here.') . EOL );
309 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
310 notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
314 $contact_record = $ret[0];
315 $parms = array('dfrn-request' => $ret[0]['request']);
319 $issued_id = random_string();
321 if(is_array($contact_record)) {
322 // There is a contact record but no issued-id, so this
323 // is a reciprocal introduction from a known contact
324 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1",
326 intval($contact_record['id'])
330 if(! validate_url($url)) {
331 notice( t('Invalid profile URL.') . EOL);
332 goaway($a->get_baseurl() . '/' . $a->cmd);
333 return; // NOTREACHED
336 if(! allowed_url($url)) {
337 notice( t('Disallowed profile URL.') . EOL);
338 goaway($a->get_baseurl() . '/' . $a->cmd);
339 return; // NOTREACHED
343 require_once('Scrape.php');
345 $parms = scrape_dfrn($url);
347 if(! count($parms)) {
348 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
349 goaway($a->get_baseurl() . '/' . $a->cmd);
353 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
354 if(! x($parms,'photo'))
355 notice( t('Warning: profile location has no profile photo.') . EOL );
356 $invalid = validate_dfrn($parms);
358 notice( sprintf( tt("%d required parameter was not found at the given location",
359 "%d required parameters were not found at the given location",
360 $invalid), $invalid) . EOL );
367 $parms['url'] = $url;
368 $parms['issued-id'] = $issued_id;
372 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
373 `request`, `confirm`, `notify`, `poll`, `network` )
374 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
383 $parms['dfrn-request'],
384 $parms['dfrn-confirm'],
385 $parms['dfrn-notify'],
390 // find the contact record we just created
392 $r = q("SELECT `id` FROM `contact`
393 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
399 $contact_record = $r[0];
404 notice( t('Failed to update contact record.') . EOL );
408 $hash = random_string() . (string) time(); // Generate a confirm_key
410 if(is_array($contact_record)) {
411 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
412 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
414 intval($contact_record['id']),
415 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
416 dbesc(notags(trim($_POST['dfrn-request-message']))),
418 dbesc(datetime_convert())
422 // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
425 info( t('Your introduction has been sent.') . EOL );
427 // "Homecoming" - send the requestor back to their site to record the introduction.
429 $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
430 $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
432 goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
433 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
434 . '&confirm_key=' . $hash
435 . (($aes_allow) ? "&aes_allow=1" : "")
438 // END $network === NETWORK_DFRN
440 elseif($network === NETWORK_OSTATUS) {
445 * Check contact existence
446 * Try and scrape together enough information to create a contact record,
447 * with us as CONTACT_IS_FOLLOWER
448 * Substitute our user's feed URL into $url template
449 * Send the subscriber home to subscribe
453 $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url);
456 // END $network === NETWORK_OSTATUS
465 if(! function_exists('dfrn_request_content')) {
466 function dfrn_request_content(&$a) {
468 if(($a->argc != 2) || (! count($a->profile)))
472 // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
473 // to send us to the post section to record the introduction.
475 if(x($_GET,'dfrn_url')) {
478 info( t("Please login to confirm introduction.") . EOL );
480 /* setup the return URL to come back to this page if they use openid */
482 $stripped = str_replace('q=','',$a->query_string);
483 $_SESSION['return_url'] = trim($stripped,'/');
488 // Edge case, but can easily happen in the wild. This person is authenticated,
489 // but not as the person who needs to deal with this request.
491 if ($a->user['nickname'] != $a->argv[1]) {
492 notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
496 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
497 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
498 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
499 $tpl = get_markup_template("dfrn_req_confirm.tpl");
500 $o = replace_macros($tpl,array(
501 '$dfrn_url' => $dfrn_url,
502 '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
503 '$confirm_key' => $confirm_key,
504 '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
505 '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
506 '$submit' => t('Confirm'),
507 '$uid' => $_SESSION['uid'],
508 '$nickname' => $a->user['nickname'],
509 'dfrn_rawurl' => $_GET['dfrn_url']
514 elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
516 // we are the requestee and it is now safe to send our user their introduction,
517 // We could just unblock it, but first we have to jump through a few hoops to
518 // send an email, or even to find out if we need to send an email.
520 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
521 dbesc($_GET['confirm_key'])
526 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
527 WHERE `contact`.`id` = %d LIMIT 1",
528 intval($intro[0]['contact-id'])
531 $auto_confirm = false;
534 if($r[0]['page-flags'] != PAGE_NORMAL)
535 $auto_confirm = true;
536 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && (! $auto_confirm)) {
537 $email_tpl = get_intltext_template('request_notify_eml.tpl');
538 $email = replace_macros($email_tpl, array(
539 '$requestor' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
540 '$url' => stripslashes($r[0]['url']),
541 '$myname' => $r[0]['username'],
542 '$siteurl' => $a->get_baseurl(),
543 '$sitename' => $a->config['sitename']
545 $res = mail($r[0]['email'],
546 t("Introduction received at ") . $a->config['sitename'],
548 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
549 . 'Content-type: text/plain; charset=UTF-8' . "\n"
550 . 'Content-transfer-encoding: 8bit' );
552 // This is a redundant notification - no point throwing errors if it fails.
555 require_once('mod/dfrn_confirm.php');
557 'uid' => $r[0]['uid'],
558 'node' => $r[0]['nickname'],
559 'dfrn_id' => $r[0]['issued-id'],
560 'intro_id' => $intro[0]['id'],
561 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0)
563 dfrn_confirm_post($a,$handsfree);
568 if(! $auto_confirm) {
570 // If we are auto_confirming, this record will have already been nuked
571 // in dfrn_confirm_post()
573 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s' LIMIT 1",
574 dbesc($_GET['confirm_key'])
580 return; // NOTREACHED
585 * Normal web request. Display our user's introduction form.
588 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
589 notice( t('Public access denied.') . EOL);
595 * Try to auto-fill the profile address
599 if(strlen($a->path)) {
600 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
603 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
606 elseif(x($_GET,'addr')) {
607 $myaddr = hex2bin($_GET['addr']);
610 /* $_GET variables are already urldecoded */
611 $myaddr = ((x($_GET,'address')) ? $_GET['address'] : '');
616 * The auto_request form only has the profile address
617 * because nobody is going to read the comments and
618 * it doesn't matter if they know you or not.
622 if($a->profile['page-flags'] == PAGE_NORMAL)
623 $tpl = get_markup_template('dfrn_request.tpl');
625 $tpl = get_markup_template('auto_request.tpl');
627 $o .= replace_macros($tpl,array(
628 '$header' => t('Friend/Connection Request'),
629 '$desc' => t('Examples: jojo@demo.friendika.com, http://demo.friendika.com/profile/jojo, testuser@identi.ca'),
630 '$pls_answer' => t('Please answer the following:'),
631 '$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
634 '$add_note' => t('Add a personal note:'),
635 '$page_desc' => t("Please enter your 'Identity Address' from one of the following supported social networks:"),
636 '$friendika' => t('Friendika'),
637 '$statusnet' => t('StatusNet/Federated Social Web'),
638 '$private_net' => t("Private \x28secure\x29 network"),
639 '$public_net' => t("Public \x28insecure\x29 network"),
640 '$your_address' => t('Your Identity Address:'),
641 '$submit' => t('Submit Request'),
642 '$cancel' => t('Cancel'),
643 '$nickname' => $a->argv[1],
644 '$name' => $a->profile['name'],
650 return; // Somebody is fishing.