]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_confirm.php
Merge pull request #3149 from annando/1601-new-diaspora-mention
[friendica.git] / mod / dfrn_confirm.php
1 <?php
2
3 /**
4  * @file mod/dfrn_confirm.php
5  * @brief Module: dfrn_confirm
6  * Purpose: Friendship acceptance for DFRN contacts
7  *.
8  * There are two possible entry points and three scenarios.
9  *.
10  *   1. A form was submitted by our user approving a friendship that originated elsewhere.
11  *      This may also be called from dfrn_request to automatically approve a friendship.
12  *
13  *   2. We may be the target or other side of the conversation to scenario 1, and will
14  *      interact with that process on our own user's behalf.
15  *.
16  *  @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
17  *    You also find a graphic which describes the confirmation process at
18  *    https://github.com/friendica/friendica/blob/master/spec/dfrn2_contact_confirmation.png
19  */
20
21 require_once('include/enotify.php');
22 require_once('include/group.php');
23 require_once('include/Probe.php');
24
25 function dfrn_confirm_post(App $a, $handsfree = null) {
26
27         if(is_array($handsfree)) {
28
29                 /*
30                  * We were called directly from dfrn_request due to automatic friend acceptance.
31                  * Any $_POST parameters we may require are supplied in the $handsfree array.
32                  *
33                  */
34
35                 $node = $handsfree['node'];
36                 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
37
38         }
39         else {
40                 if($a->argc > 1)
41                         $node = $a->argv[1];
42         }
43
44                 /*
45                  *
46                  * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
47                  * from another site) and clicked 'Approve'.
48                  * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
49                  *
50                  * We may also have been called directly from dfrn_request ($handsfree != null) due to
51                  * this being a page type which supports automatic friend acceptance. That is also Scenario 1
52                  * since we are operating on behalf of our registered user to approve a friendship.
53                  *
54                  */
55
56         if(! x($_POST,'source_url')) {
57
58                 $uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user());
59
60                 if(! $uid) {
61                         notice( t('Permission denied.') . EOL );
62                         return;
63                 }
64
65                 $user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
66                         intval($uid)
67                 );
68
69                 if(! $user) {
70                         notice( t('Profile not found.') . EOL );
71                         return;
72                 }
73
74
75                 // These data elements may come from either the friend request notification form or $handsfree array.
76
77                 if(is_array($handsfree)) {
78                         logger('Confirm in handsfree mode');
79                         $dfrn_id   = $handsfree['dfrn_id'];
80                         $intro_id  = $handsfree['intro_id'];
81                         $duplex    = $handsfree['duplex'];
82                         $hidden    = ((array_key_exists('hidden',$handsfree)) ? intval($handsfree['hidden']) : 0 );
83                         $activity  = ((array_key_exists('activity',$handsfree)) ? intval($handsfree['activity']) : 0 );
84                 }
85                 else {
86                         $dfrn_id  = ((x($_POST,'dfrn_id'))    ? notags(trim($_POST['dfrn_id'])) : "");
87                         $intro_id = ((x($_POST,'intro_id'))   ? intval($_POST['intro_id'])      : 0 );
88                         $duplex   = ((x($_POST,'duplex'))     ? intval($_POST['duplex'])        : 0 );
89                         $cid      = ((x($_POST,'contact_id')) ? intval($_POST['contact_id'])    : 0 );
90                         $hidden   = ((x($_POST,'hidden'))     ? intval($_POST['hidden'])        : 0 );
91                         $activity = ((x($_POST,'activity'))   ? intval($_POST['activity'])      : 0 );
92                 }
93
94                 /*
95                  *
96                  * Ensure that dfrn_id has precedence when we go to find the contact record.
97                  * We only want to search based on contact id if there is no dfrn_id,
98                  * e.g. for OStatus network followers.
99                  *
100                  */
101
102                 if(strlen($dfrn_id))
103                         $cid = 0;
104
105                 logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
106                 if($cid)
107                         logger('Confirming follower with contact_id: ' . $cid);
108
109
110                 /*
111                  *
112                  * The other person will have been issued an ID when they first requested friendship.
113                  * Locate their record. At this time, their record will have both pending and blocked set to 1.
114                  * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
115                  *
116                  */
117
118                 $r = q("SELECT * FROM `contact` WHERE ( ( `issued-id` != '' AND `issued-id` = '%s' ) OR ( `id` = %d AND `id` != 0 ) ) AND `uid` = %d AND `duplex` = 0 LIMIT 1",
119                         dbesc($dfrn_id),
120                         intval($cid),
121                         intval($uid)
122                 );
123
124                 if (! dbm::is_result($r)) {
125                         logger('Contact not found in DB.');
126                         notice( t('Contact not found.') . EOL );
127                         notice( t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL );
128                         return;
129                 }
130
131                 $contact = $r[0];
132
133                 $contact_id   = $contact['id'];
134                 $relation     = $contact['rel'];
135                 $site_pubkey  = $contact['site-pubkey'];
136                 $dfrn_confirm = $contact['confirm'];
137                 $aes_allow    = $contact['aes_allow'];
138
139                 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
140
141                 if($contact['network'])
142                         $network = $contact['network'];
143
144                 if($network === NETWORK_DFRN) {
145
146                         /*
147                          *
148                          * Generate a key pair for all further communications with this person.
149                          * We have a keypair for every contact, and a site key for unknown people.
150                          * This provides a means to carry on relationships with other people if
151                          * any single key is compromised. It is a robust key. We're much more
152                          * worried about key leakage than anybody cracking it.
153                          *
154                          */
155                         require_once('include/crypto.php');
156
157                         $res = new_keypair(4096);
158
159
160                         $private_key = $res['prvkey'];
161                         $public_key  = $res['pubkey'];
162
163                         // Save the private key. Send them the public key.
164
165                         $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
166                                 dbesc($private_key),
167                                 intval($contact_id),
168                                 intval($uid)
169                         );
170
171                         $params = array();
172
173                         /*
174                          *
175                          * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
176                          * site private key (person on the other end can decrypt it with our site public key).
177                          * Then encrypt our profile URL with the other person's site public key. They can decrypt
178                          * it with their site private key. If the decryption on the other end fails for either
179                          * item, it indicates tampering or key failure on at least one site and we will not be
180                          * able to provide a secure communication pathway.
181                          *
182                          * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
183                          * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
184                          * random key which is encrypted with their site public key.
185                          *
186                          */
187
188                         $src_aes_key = random_string();
189
190                         $result = '';
191                         openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
192
193                         $params['dfrn_id'] = bin2hex($result);
194                         $params['public_key'] = $public_key;
195
196
197                         $my_url = App::get_baseurl() . '/profile/' . $user[0]['nickname'];
198
199                         openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
200                         $params['source_url'] = bin2hex($params['source_url']);
201
202                         if($aes_allow && function_exists('openssl_encrypt')) {
203                                 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
204                                 $params['aes_key'] = bin2hex($params['aes_key']);
205                                 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
206                         }
207
208                         $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
209                         if($duplex == 1)
210                                 $params['duplex'] = 1;
211
212                         if($user[0]['page-flags'] == PAGE_COMMUNITY)
213                                 $params['page'] = 1;
214                         if($user[0]['page-flags'] == PAGE_PRVGROUP)
215                                 $params['page'] = 2;
216
217                         logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params,true), LOGGER_DATA);
218
219                         /*
220                          *
221                          * POST all this stuff to the other site.
222                          * Temporarily raise the network timeout to 120 seconds because the default 60
223                          * doesn't always give the other side quite enough time to decrypt everything.
224                          *
225                          */
226
227                         $res = post_url($dfrn_confirm, $params, null, $redirects, 120);
228
229                         logger(' Confirm: received data: ' . $res, LOGGER_DATA);
230
231                         // Now figure out what they responded. Try to be robust if the remote site is
232                         // having difficulty and throwing up errors of some kind.
233
234                         $leading_junk = substr($res,0,strpos($res,'<?xml'));
235
236                         $res = substr($res,strpos($res,'<?xml'));
237                         if(! strlen($res)) {
238
239                                         // No XML at all, this exchange is messed up really bad.
240                                         // We shouldn't proceed, because the xml parser might choke,
241                                         // and $status is going to be zero, which indicates success.
242                                         // We can hardly call this a success.
243
244                                 notice( t('Response from remote site was not understood.') . EOL);
245                                 return;
246                         }
247
248                         if(strlen($leading_junk) && get_config('system','debugging')) {
249
250                                         // This might be more common. Mixed error text and some XML.
251                                         // If we're configured for debugging, show the text. Proceed in either case.
252
253                                 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
254                         }
255
256                         if(stristr($res, "<status")===false) {
257                                 // wrong xml! stop here!
258                                 notice( t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL );
259                                 return;
260                         }
261
262                         $xml = parse_xml_string($res);
263                         $status = (int) $xml->status;
264                         $message = unxmlify($xml->message);   // human readable text of what may have gone wrong.
265                         switch($status) {
266                                 case 0:
267                                         info( t("Confirmation completed successfully.") . EOL);
268                                         if(strlen($message))
269                                                 notice( t('Remote site reported: ') . $message . EOL);
270                                         break;
271                                 case 1:
272                                         // birthday paradox - generate new dfrn-id and fall through.
273                                         $new_dfrn_id = random_string();
274                                         $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
275                                                 dbesc($new_dfrn_id),
276                                                 intval($contact_id),
277                                                 intval($uid)
278                                         );
279
280                                 case 2:
281                                         notice( t("Temporary failure. Please wait and try again.") . EOL);
282                                         if(strlen($message))
283                                                 notice( t('Remote site reported: ') . $message . EOL);
284                                         break;
285
286
287                                 case 3:
288                                         notice( t("Introduction failed or was revoked.") . EOL);
289                                         if(strlen($message))
290                                                 notice( t('Remote site reported: ') . $message . EOL);
291                                         break;
292                                 }
293
294                         if(($status == 0) && ($intro_id)) {
295
296                                 // Success. Delete the notification.
297
298                                 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
299                                         intval($intro_id),
300                                         intval($uid)
301                                 );
302
303                         }
304
305                         if($status != 0)
306                                 return;
307                 }
308
309
310                 /*
311                  *
312                  * We have now established a relationship with the other site.
313                  * Let's make our own personal copy of their profile photo so we don't have
314                  * to always load it from their site.
315                  *
316                  * We will also update the contact record with the nature and scope of the relationship.
317                  *
318                  */
319
320                 require_once('include/Photo.php');
321
322                 update_contact_avatar($contact['photo'],$uid,$contact_id);
323
324                 logger('dfrn_confirm: confirm - imported photos');
325
326                 if($network === NETWORK_DFRN) {
327
328                         $new_relation = CONTACT_IS_FOLLOWER;
329                         if(($relation == CONTACT_IS_SHARING) || ($duplex))
330                                 $new_relation = CONTACT_IS_FRIEND;
331
332                         if(($relation == CONTACT_IS_SHARING) && ($duplex))
333                                 $duplex = 0;
334
335                         $r = q("UPDATE `contact` SET `rel` = %d,
336                                 `name-date` = '%s',
337                                 `uri-date` = '%s',
338                                 `blocked` = 0,
339                                 `pending` = 0,
340                                 `duplex` = %d,
341                                 `hidden` = %d,
342                                 `network` = '%s' WHERE `id` = %d
343                         ",
344                                 intval($new_relation),
345                                 dbesc(datetime_convert()),
346                                 dbesc(datetime_convert()),
347                                 intval($duplex),
348                                 intval($hidden),
349                                 dbesc(NETWORK_DFRN),
350                                 intval($contact_id)
351                         );
352                 }
353                 else {
354
355                         // $network !== NETWORK_DFRN
356
357                         $network = (($contact['network']) ? $contact['network'] : NETWORK_OSTATUS);
358                         $notify = (($contact['notify']) ? $contact['notify'] : '');
359                         $poll   = (($contact['poll']) ? $contact['poll'] : '');
360
361                         if((! $contact['notify']) || (! $contact['poll'])) {
362                                 $arr = Probe::lrdd($contact['url']);
363                                 if(count($arr)) {
364                                         foreach($arr as $link) {
365                                                 if($link['@attributes']['rel'] === 'salmon')
366                                                         $notify = $link['@attributes']['href'];
367                                                 if($link['@attributes']['rel'] === NAMESPACE_FEED)
368                                                         $poll = $link['@attributes']['href'];
369                                         }
370                                 }
371                         }
372
373                         $new_relation = $contact['rel'];
374                         $writable = $contact['writable'];
375
376                         if($network === NETWORK_DIASPORA) {
377                                 if($duplex)
378                                         $new_relation = CONTACT_IS_FRIEND;
379                                 else
380                                         $new_relation = CONTACT_IS_FOLLOWER;
381
382                                 if($new_relation != CONTACT_IS_FOLLOWER)
383                                         $writable = 1;
384                         }
385
386                         $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
387                                 intval($intro_id),
388                                 intval($uid)
389                         );
390
391
392                         $r = q("UPDATE `contact` SET `name-date` = '%s',
393                                 `uri-date` = '%s',
394                                 `notify` = '%s',
395                                 `poll` = '%s',
396                                 `blocked` = 0,
397                                 `pending` = 0,
398                                 `network` = '%s',
399                                 `writable` = %d,
400                                 `hidden` = %d,
401                                 `rel` = %d
402                                 WHERE `id` = %d
403                         ",
404                                 dbesc(datetime_convert()),
405                                 dbesc(datetime_convert()),
406                                 dbesc($notify),
407                                 dbesc($poll),
408                                 dbesc($network),
409                                 intval($writable),
410                                 intval($hidden),
411                                 intval($new_relation),
412                                 intval($contact_id)
413                         );
414                 }
415
416                 /// @TODO is dbm::is_result() working here?
417                 if ($r === false) {
418                         notice( t('Unable to set contact photo.') . EOL);
419                 }
420
421                 // reload contact info
422
423                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
424                         intval($contact_id)
425                 );
426                 if (dbm::is_result($r)) {
427                         $contact = $r[0];
428                 } else {
429                         $contact = null;
430                 }
431
432
433                 if ((isset($new_relation) && $new_relation == CONTACT_IS_FRIEND)) {
434
435                         if (($contact) && ($contact['network'] === NETWORK_DIASPORA)) {
436                                 require_once('include/diaspora.php');
437                                 $ret = Diaspora::send_share($user[0],$r[0]);
438                                 logger('share returns: ' . $ret);
439                         }
440
441                         // Send a new friend post if we are allowed to...
442
443                         $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
444                                 intval($uid)
445                         );
446
447                         if((dbm::is_result($r)) && ($r[0]['hide-friends'] == 0) && ($activity) && (! $hidden)) {
448
449                                 require_once('include/items.php');
450
451                                 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
452                                         intval($uid)
453                                 );
454
455                                 if(count($self)) {
456
457                                         $arr = array();
458                                         $arr['guid'] = get_guid(32);
459                                         $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $uid);
460                                         $arr['uid'] = $uid;
461                                         $arr['contact-id'] = $self[0]['id'];
462                                         $arr['wall'] = 1;
463                                         $arr['type'] = 'wall';
464                                         $arr['gravity'] = 0;
465                                         $arr['origin'] = 1;
466                                         $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
467                                         $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
468                                         $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
469
470                                         $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
471                                         $APhoto = '[url=' . $self[0]['url'] . ']' . '[img]' . $self[0]['thumb'] . '[/img][/url]';
472
473                                         $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
474                                         $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
475
476                                         $arr['verb'] = ACTIVITY_FRIEND;
477                                         $arr['object-type'] = ACTIVITY_OBJ_PERSON;
478                                         $arr['body'] =  sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$BPhoto;
479
480                                         $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
481                                                 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
482                                         $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
483                                         $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
484                                         $arr['object'] .= '</link></object>' . "\n";
485
486                                         $arr['last-child'] = 1;
487
488                                         $arr['allow_cid'] = $user[0]['allow_cid'];
489                                         $arr['allow_gid'] = $user[0]['allow_gid'];
490                                         $arr['deny_cid']  = $user[0]['deny_cid'];
491                                         $arr['deny_gid']  = $user[0]['deny_gid'];
492
493                                         $i = item_store($arr);
494                                         if($i)
495                                                 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
496                                 }
497                         }
498                 }
499
500                 $def_gid = get_default_group($uid, $contact["network"]);
501                 if($contact && intval($def_gid))
502                         group_add_member($uid, '', $contact['id'], $def_gid);
503
504                 // Let's send our user to the contact editor in case they want to
505                 // do anything special with this new friend.
506
507                 if ($handsfree === null) {
508                         goaway(App::get_baseurl() . '/contacts/' . intval($contact_id));
509                 } else {
510                         return;
511                 }
512                 //NOTREACHED
513         }
514
515         /*
516          *
517          *
518          * End of Scenario 1. [Local confirmation of remote friend request].
519          *
520          * Begin Scenario 2. This is the remote response to the above scenario.
521          * This will take place on the site that originally initiated the friend request.
522          * In the section above where the confirming party makes a POST and
523          * retrieves xml status information, they are communicating with the following code.
524          *
525          */
526
527         if (x($_POST,'source_url')) {
528
529                 // We are processing an external confirmation to an introduction created by our user.
530
531                 $public_key = ((x($_POST,'public_key'))   ? $_POST['public_key']           : '');
532                 $dfrn_id    = ((x($_POST,'dfrn_id'))      ? hex2bin($_POST['dfrn_id'])     : '');
533                 $source_url = ((x($_POST,'source_url'))   ? hex2bin($_POST['source_url'])  : '');
534                 $aes_key    = ((x($_POST,'aes_key'))      ? $_POST['aes_key']              : '');
535                 $duplex     = ((x($_POST,'duplex'))       ? intval($_POST['duplex'])       : 0 );
536                 $page       = ((x($_POST,'page'))         ? intval($_POST['page'])         : 0 );
537                 $version_id = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
538
539                 $forum = (($page == 1) ? 1 : 0);
540                 $prv   = (($page == 2) ? 1 : 0);
541
542                 logger('dfrn_confirm: requestee contacted: ' . $node);
543
544                 logger('dfrn_confirm: request: POST=' . print_r($_POST,true), LOGGER_DATA);
545
546                 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
547
548                 if (x($aes_key)) {
549                         $aes_key = hex2bin($aes_key);
550                         $public_key = hex2bin($public_key);
551                 }
552
553                 // Find our user's account
554
555                 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
556                         dbesc($node));
557
558                 if (! dbm::is_result($r)) {
559                         $message = sprintf(t('No user record found for \'%s\' '), $node);
560                         xml_status(3,$message); // failure
561                         // NOTREACHED
562                 }
563
564                 $my_prvkey = $r[0]['prvkey'];
565                 $local_uid = $r[0]['uid'];
566
567
568                 if(! strstr($my_prvkey,'PRIVATE KEY')) {
569                         $message = t('Our site encryption key is apparently messed up.');
570                         xml_status(3,$message);
571                 }
572
573                 // verify everything
574
575                 $decrypted_source_url = "";
576                 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
577
578
579                 if(! strlen($decrypted_source_url)) {
580                         $message = t('Empty site URL was provided or URL could not be decrypted by us.');
581                         xml_status(3,$message);
582                         // NOTREACHED
583                 }
584
585                 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
586                         dbesc($decrypted_source_url),
587                         intval($local_uid)
588                 );
589                 if(! count($ret)) {
590                         if(strstr($decrypted_source_url,'http:'))
591                                 $newurl = str_replace('http:','https:',$decrypted_source_url);
592                         else
593                                 $newurl = str_replace('https:','http:',$decrypted_source_url);
594
595                         $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
596                                 dbesc($newurl),
597                                 intval($local_uid)
598                         );
599                         if(! count($ret)) {
600                                 // this is either a bogus confirmation (?) or we deleted the original introduction.
601                                 $message = t('Contact record was not found for you on our site.');
602                                 xml_status(3,$message);
603                                 return; // NOTREACHED
604                         }
605                 }
606
607                 $relation = $ret[0]['rel'];
608
609                 // Decrypt all this stuff we just received
610
611                 $foreign_pubkey = $ret[0]['site-pubkey'];
612                 $dfrn_record    = $ret[0]['id'];
613
614                 if(! $foreign_pubkey) {
615                         $message = sprintf( t('Site public key not available in contact record for URL %s.'), $newurl);
616                         xml_status(3,$message);
617                 }
618
619                 $decrypted_dfrn_id = "";
620                 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
621
622                 if(strlen($aes_key)) {
623                         $decrypted_aes_key = "";
624                         openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
625                         $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
626                 }
627                 else {
628                         $dfrn_pubkey = $public_key;
629                 }
630
631                 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
632                         dbesc($decrypted_dfrn_id)
633                 );
634                 if (dbm::is_result($r)) {
635                         $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
636                         xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
637                         // NOTREACHED
638                 }
639
640                 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
641                         dbesc($decrypted_dfrn_id),
642                         dbesc($dfrn_pubkey),
643                         intval($dfrn_record)
644                 );
645                 if (! dbm::is_result($r)) {
646                         $message = t('Unable to set your contact credentials on our system.');
647                         xml_status(3,$message);
648                 }
649
650                 // It's possible that the other person also requested friendship.
651                 // If it is a duplex relationship, ditch the issued-id if one exists.
652
653                 if($duplex) {
654                         $r = q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
655                                 intval($dfrn_record)
656                         );
657                 }
658
659                 // We're good but now we have to scrape the profile photo and send notifications.
660
661
662
663                 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
664                         intval($dfrn_record));
665
666                 if (dbm::is_result($r)) {
667                         $photo = $r[0]['photo'];
668                 } else {
669                         $photo = App::get_baseurl() . '/images/person-175.jpg';
670                 }
671
672                 require_once("include/Photo.php");
673
674                 update_contact_avatar($photo,$local_uid,$dfrn_record);
675
676                 logger('dfrn_confirm: request - photos imported');
677
678                 $new_relation = CONTACT_IS_SHARING;
679                 if (($relation == CONTACT_IS_FOLLOWER) || ($duplex)) {
680                         $new_relation = CONTACT_IS_FRIEND;
681                 }
682
683                 if (($relation == CONTACT_IS_FOLLOWER) && ($duplex)) {
684                         $duplex = 0;
685                 }
686
687                 $r = q("UPDATE `contact` SET
688                         `rel` = %d,
689                         `name-date` = '%s',
690                         `uri-date` = '%s',
691                         `blocked` = 0,
692                         `pending` = 0,
693                         `duplex` = %d,
694                         `forum` = %d,
695                         `prv` = %d,
696                         `network` = '%s' WHERE `id` = %d
697                 ",
698                         intval($new_relation),
699                         dbesc(datetime_convert()),
700                         dbesc(datetime_convert()),
701                         intval($duplex),
702                         intval($forum),
703                         intval($prv),
704                         dbesc(NETWORK_DFRN),
705                         intval($dfrn_record)
706                 );
707                 if ($r === false) {    // indicates schema is messed up or total db failure
708                         $message = t('Unable to update your contact profile details on our system');
709                         xml_status(3,$message);
710                 }
711
712                 // Otherwise everything seems to have worked and we are almost done. Yay!
713                 // Send an email notification
714
715                 logger('dfrn_confirm: request: info updated');
716
717                 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
718                         WHERE `contact`.`id` = %d LIMIT 1",
719                         intval($dfrn_record)
720                 );
721
722                 if (dbm::is_result($r))
723                         $combined = $r[0];
724
725                 if((dbm::is_result($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
726                         $mutual = ($new_relation == CONTACT_IS_FRIEND);
727                         notification(array(
728                                 'type'         => NOTIFY_CONFIRM,
729                                 'notify_flags' => $r[0]['notify-flags'],
730                                 'language'     => $r[0]['language'],
731                                 'to_name'      => $r[0]['username'],
732                                 'to_email'     => $r[0]['email'],
733                                 'uid'          => $r[0]['uid'],
734                                 'link'             => App::get_baseurl() . '/contacts/' . $dfrn_record,
735                                 'source_name'  => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
736                                 'source_link'  => $r[0]['url'],
737                                 'source_photo' => $r[0]['photo'],
738                                 'verb'         => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
739                                 'otype'        => 'intro'
740                         ));
741                 }
742
743                 // Send a new friend post if we are allowed to...
744
745                 if($page && intval(get_pconfig($local_uid,'system','post_joingroup'))) {
746                         $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
747                                 intval($local_uid)
748                         );
749
750                         if((dbm::is_result($r)) && ($r[0]['hide-friends'] == 0)) {
751
752                                 require_once('include/items.php');
753
754                                 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
755                                         intval($local_uid)
756                                 );
757
758                                 if(count($self)) {
759
760                                         $arr = array();
761                                         $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid);
762                                         $arr['uid'] = $local_uid;
763                                         $arr['contact-id'] = $self[0]['id'];
764                                         $arr['wall'] = 1;
765                                         $arr['type'] = 'wall';
766                                         $arr['gravity'] = 0;
767                                         $arr['origin'] = 1;
768                                         $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
769                                         $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
770                                         $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
771
772                                         $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
773                                         $APhoto = '[url=' . $self[0]['url'] . ']' . '[img]' . $self[0]['thumb'] . '[/img][/url]';
774
775                                         $B = '[url=' . $combined['url'] . ']' . $combined['name'] . '[/url]';
776                                         $BPhoto = '[url=' . $combined['url'] . ']' . '[img]' . $combined['thumb'] . '[/img][/url]';
777
778                                         $arr['verb'] = ACTIVITY_JOIN;
779                                         $arr['object-type'] = ACTIVITY_OBJ_GROUP;
780                                         $arr['body'] =  sprintf( t('%1$s has joined %2$s'), $A, $B)."\n\n\n" .$BPhoto;
781                                         $arr['object'] = '<object><type>' . ACTIVITY_OBJ_GROUP . '</type><title>' . $combined['name'] . '</title>'
782                                                 . '<id>' . $combined['url'] . '/' . $combined['name'] . '</id>';
783                                         $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $combined['url'] . '" />' . "\n");
784                                         $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $combined['thumb'] . '" />' . "\n");
785                                         $arr['object'] .= '</link></object>' . "\n";
786
787                                         $arr['last-child'] = 1;
788
789                                         $arr['allow_cid'] = $user[0]['allow_cid'];
790                                         $arr['allow_gid'] = $user[0]['allow_gid'];
791                                         $arr['deny_cid']  = $user[0]['deny_cid'];
792                                         $arr['deny_gid']  = $user[0]['deny_gid'];
793
794                                         $i = item_store($arr);
795                                         if($i)
796                                                 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
797
798                                 }
799                         }
800                 }
801                 xml_status(0); // Success
802                 return; // NOTREACHED
803
804                         ////////////////////// End of this scenario ///////////////////////////////////////////////
805         }
806
807         // somebody arrived here by mistake or they are fishing. Send them to the homepage.
808
809         goaway(z_root());
810         // NOTREACHED
811
812 }