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