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