]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_confirm.php
f0d5d76305c975b31bbd537651d68fa6f3593c59
[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 use Friendica\Protocol\Diaspora;
28
29 require_once 'include/enotify.php';
30 require_once 'include/group.php';
31
32 function dfrn_confirm_post(App $a, $handsfree = null) {
33
34         if(is_array($handsfree)) {
35
36                 /*
37                  * We were called directly from dfrn_request due to automatic friend acceptance.
38                  * Any $_POST parameters we may require are supplied in the $handsfree array.
39                  *
40                  */
41
42                 $node = $handsfree['node'];
43                 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
44
45         }
46         else {
47                 if($a->argc > 1)
48                         $node = $a->argv[1];
49         }
50
51                 /*
52                  *
53                  * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
54                  * from another site) and clicked 'Approve'.
55                  * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
56                  *
57                  * We may also have been called directly from dfrn_request ($handsfree != null) due to
58                  * this being a page type which supports automatic friend acceptance. That is also Scenario 1
59                  * since we are operating on behalf of our registered user to approve a friendship.
60                  *
61                  */
62
63         if(! x($_POST,'source_url')) {
64
65                 $uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user());
66
67                 if(! $uid) {
68                         notice( t('Permission denied.') . EOL );
69                         return;
70                 }
71
72                 $user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
73                         intval($uid)
74                 );
75
76                 if(! $user) {
77                         notice( t('Profile not found.') . EOL );
78                         return;
79                 }
80
81
82                 // These data elements may come from either the friend request notification form or $handsfree array.
83
84                 if(is_array($handsfree)) {
85                         logger('Confirm in handsfree mode');
86                         $dfrn_id   = $handsfree['dfrn_id'];
87                         $intro_id  = $handsfree['intro_id'];
88                         $duplex    = $handsfree['duplex'];
89                         $hidden    = ((array_key_exists('hidden',$handsfree)) ? intval($handsfree['hidden']) : 0 );
90                         $activity  = ((array_key_exists('activity',$handsfree)) ? intval($handsfree['activity']) : 0 );
91                 }
92                 else {
93                         $dfrn_id  = ((x($_POST,'dfrn_id'))    ? notags(trim($_POST['dfrn_id'])) : "");
94                         $intro_id = ((x($_POST,'intro_id'))   ? intval($_POST['intro_id'])      : 0 );
95                         $duplex   = ((x($_POST,'duplex'))     ? intval($_POST['duplex'])        : 0 );
96                         $cid      = ((x($_POST,'contact_id')) ? intval($_POST['contact_id'])    : 0 );
97                         $hidden   = ((x($_POST,'hidden'))     ? intval($_POST['hidden'])        : 0 );
98                         $activity = ((x($_POST,'activity'))   ? intval($_POST['activity'])      : 0 );
99                 }
100
101                 /*
102                  *
103                  * Ensure that dfrn_id has precedence when we go to find the contact record.
104                  * We only want to search based on contact id if there is no dfrn_id,
105                  * e.g. for OStatus network followers.
106                  *
107                  */
108
109                 if(strlen($dfrn_id))
110                         $cid = 0;
111
112                 logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
113                 if($cid)
114                         logger('Confirming follower with contact_id: ' . $cid);
115
116
117                 /*
118                  *
119                  * The other person will have been issued an ID when they first requested friendship.
120                  * Locate their record. At this time, their record will have both pending and blocked set to 1.
121                  * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
122                  *
123                  */
124
125                 $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",
126                         dbesc($dfrn_id),
127                         intval($cid),
128                         intval($uid)
129                 );
130
131                 if (! dbm::is_result($r)) {
132                         logger('Contact not found in DB.');
133                         notice( t('Contact not found.') . EOL );
134                         notice( t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL );
135                         return;
136                 }
137
138                 $contact = $r[0];
139
140                 $contact_id   = $contact['id'];
141                 $relation     = $contact['rel'];
142                 $site_pubkey  = $contact['site-pubkey'];
143                 $dfrn_confirm = $contact['confirm'];
144                 $aes_allow    = $contact['aes_allow'];
145
146                 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
147
148                 if($contact['network'])
149                         $network = $contact['network'];
150
151                 if($network === NETWORK_DFRN) {
152
153                         /*
154                          *
155                          * Generate a key pair for all further communications with this person.
156                          * We have a keypair for every contact, and a site key for unknown people.
157                          * This provides a means to carry on relationships with other people if
158                          * any single key is compromised. It is a robust key. We're much more
159                          * worried about key leakage than anybody cracking it.
160                          *
161                          */
162                         require_once 'include/crypto.php';
163
164                         $res = new_keypair(4096);
165
166
167                         $private_key = $res['prvkey'];
168                         $public_key  = $res['pubkey'];
169
170                         // Save the private key. Send them the public key.
171
172                         $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
173                                 dbesc($private_key),
174                                 intval($contact_id),
175                                 intval($uid)
176                         );
177
178                         $params = array();
179
180                         /*
181                          *
182                          * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
183                          * site private key (person on the other end can decrypt it with our site public key).
184                          * Then encrypt our profile URL with the other person's site public key. They can decrypt
185                          * it with their site private key. If the decryption on the other end fails for either
186                          * item, it indicates tampering or key failure on at least one site and we will not be
187                          * able to provide a secure communication pathway.
188                          *
189                          * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
190                          * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
191                          * random key which is encrypted with their site public key.
192                          *
193                          */
194
195                         $src_aes_key = openssl_random_pseudo_bytes(64);
196
197                         $result = '';
198                         openssl_private_encrypt($dfrn_id, $result, $user[0]['prvkey']);
199
200                         $params['dfrn_id'] = bin2hex($result);
201                         $params['public_key'] = $public_key;
202
203
204                         $my_url = System::baseUrl() . '/profile/' . $user[0]['nickname'];
205
206                         openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
207                         $params['source_url'] = bin2hex($params['source_url']);
208
209                         if($aes_allow && function_exists('openssl_encrypt')) {
210                                 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
211                                 $params['aes_key'] = bin2hex($params['aes_key']);
212                                 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
213                         }
214
215                         $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
216                         if($duplex == 1)
217                                 $params['duplex'] = 1;
218
219                         if($user[0]['page-flags'] == PAGE_COMMUNITY)
220                                 $params['page'] = 1;
221                         if($user[0]['page-flags'] == PAGE_PRVGROUP)
222                                 $params['page'] = 2;
223
224                         logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params,true), LOGGER_DATA);
225
226                         /*
227                          *
228                          * POST all this stuff to the other site.
229                          * Temporarily raise the network timeout to 120 seconds because the default 60
230                          * doesn't always give the other side quite enough time to decrypt everything.
231                          *
232                          */
233
234                         $res = post_url($dfrn_confirm, $params, null, $redirects, 120);
235
236                         logger(' Confirm: received data: ' . $res, LOGGER_DATA);
237
238                         // Now figure out what they responded. Try to be robust if the remote site is
239                         // having difficulty and throwing up errors of some kind.
240
241                         $leading_junk = substr($res,0,strpos($res,'<?xml'));
242
243                         $res = substr($res,strpos($res,'<?xml'));
244                         if(! strlen($res)) {
245
246                                         // No XML at all, this exchange is messed up really bad.
247                                         // We shouldn't proceed, because the xml parser might choke,
248                                         // and $status is going to be zero, which indicates success.
249                                         // We can hardly call this a success.
250
251                                 notice( t('Response from remote site was not understood.') . EOL);
252                                 return;
253                         }
254
255                         if(strlen($leading_junk) && Config::get('system','debugging')) {
256
257                                         // This might be more common. Mixed error text and some XML.
258                                         // If we're configured for debugging, show the text. Proceed in either case.
259
260                                 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
261                         }
262
263                         if(stristr($res, "<status")===false) {
264                                 // wrong xml! stop here!
265                                 notice( t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL );
266                                 return;
267                         }
268
269                         $xml = parse_xml_string($res);
270                         $status = (int) $xml->status;
271                         $message = unxmlify($xml->message);   // human readable text of what may have gone wrong.
272                         switch($status) {
273                                 case 0:
274                                         info( t("Confirmation completed successfully.") . EOL);
275                                         if(strlen($message))
276                                                 notice( t('Remote site reported: ') . $message . EOL);
277                                         break;
278                                 case 1:
279                                         // birthday paradox - generate new dfrn-id and fall through.
280                                         $new_dfrn_id = random_string();
281                                         $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
282                                                 dbesc($new_dfrn_id),
283                                                 intval($contact_id),
284                                                 intval($uid)
285                                         );
286
287                                 case 2:
288                                         notice( t("Temporary failure. Please wait and try again.") . EOL);
289                                         if(strlen($message))
290                                                 notice( t('Remote site reported: ') . $message . EOL);
291                                         break;
292
293
294                                 case 3:
295                                         notice( t("Introduction failed or was revoked.") . EOL);
296                                         if(strlen($message))
297                                                 notice( t('Remote site reported: ') . $message . EOL);
298                                         break;
299                                 }
300
301                         if(($status == 0) && ($intro_id)) {
302
303                                 // Success. Delete the notification.
304
305                                 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
306                                         intval($intro_id),
307                                         intval($uid)
308                                 );
309
310                         }
311
312                         if($status != 0)
313                                 return;
314                 }
315
316
317                 /*
318                  *
319                  * We have now established a relationship with the other site.
320                  * Let's make our own personal copy of their profile photo so we don't have
321                  * to always load it from their site.
322                  *
323                  * We will also update the contact record with the nature and scope of the relationship.
324                  *
325                  */
326
327                 require_once 'include/Photo.php';
328
329                 update_contact_avatar($contact['photo'],$uid,$contact_id);
330
331                 logger('dfrn_confirm: confirm - imported photos');
332
333                 if($network === NETWORK_DFRN) {
334
335                         $new_relation = CONTACT_IS_FOLLOWER;
336                         if(($relation == CONTACT_IS_SHARING) || ($duplex))
337                                 $new_relation = CONTACT_IS_FRIEND;
338
339                         if(($relation == CONTACT_IS_SHARING) && ($duplex))
340                                 $duplex = 0;
341
342                         $r = q("UPDATE `contact` SET `rel` = %d,
343                                 `name-date` = '%s',
344                                 `uri-date` = '%s',
345                                 `blocked` = 0,
346                                 `pending` = 0,
347                                 `duplex` = %d,
348                                 `hidden` = %d,
349                                 `network` = '%s' WHERE `id` = %d
350                         ",
351                                 intval($new_relation),
352                                 dbesc(datetime_convert()),
353                                 dbesc(datetime_convert()),
354                                 intval($duplex),
355                                 intval($hidden),
356                                 dbesc(NETWORK_DFRN),
357                                 intval($contact_id)
358                         );
359                 } else {
360
361                         // $network !== NETWORK_DFRN
362
363                         $network = (($contact['network']) ? $contact['network'] : NETWORK_OSTATUS);
364                         $notify = (($contact['notify']) ? $contact['notify'] : '');
365                         $poll   = (($contact['poll']) ? $contact['poll'] : '');
366
367                         $arr = Probe::uri($contact['url']);
368                         if (empty($contact['notify'])) {
369                                 $notify = $arr['notify'];
370                         }
371                         if (empty($contact['poll'])) {
372                                 $poll = $arr['poll'];
373                         }
374
375                         $addr = $arr['addr'];
376
377                         $new_relation = $contact['rel'];
378                         $writable = $contact['writable'];
379
380                         if($network === NETWORK_DIASPORA) {
381                                 if($duplex)
382                                         $new_relation = CONTACT_IS_FRIEND;
383                                 else
384                                         $new_relation = CONTACT_IS_FOLLOWER;
385
386                                 if($new_relation != CONTACT_IS_FOLLOWER)
387                                         $writable = 1;
388                         }
389
390                         $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
391                                 intval($intro_id),
392                                 intval($uid)
393                         );
394
395
396                         $r = q("UPDATE `contact` SET `name-date` = '%s',
397                                 `uri-date` = '%s',
398                                 `addr` = '%s',
399                                 `notify` = '%s',
400                                 `poll` = '%s',
401                                 `blocked` = 0,
402                                 `pending` = 0,
403                                 `network` = '%s',
404                                 `writable` = %d,
405                                 `hidden` = %d,
406                                 `rel` = %d
407                                 WHERE `id` = %d
408                         ",
409                                 dbesc(datetime_convert()),
410                                 dbesc(datetime_convert()),
411                                 dbesc($addr),
412                                 dbesc($notify),
413                                 dbesc($poll),
414                                 dbesc($network),
415                                 intval($writable),
416                                 intval($hidden),
417                                 intval($new_relation),
418                                 intval($contact_id)
419                         );
420                 }
421
422                 /// @TODO is dbm::is_result() working here?
423                 if ($r === false) {
424                         notice( t('Unable to set contact photo.') . EOL);
425                 }
426
427                 // reload contact info
428
429                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
430                         intval($contact_id)
431                 );
432                 if (dbm::is_result($r)) {
433                         $contact = $r[0];
434                 } else {
435                         $contact = null;
436                 }
437
438
439                 if ((isset($new_relation) && $new_relation == CONTACT_IS_FRIEND)) {
440
441                         if (($contact) && ($contact['network'] === NETWORK_DIASPORA)) {
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 }