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