]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_confirm.php
Merge pull request #4152 from MrPetovan/task/4137-add-posts-only-feed
[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 use Friendica\Util\Crypto;
33
34 require_once 'include/enotify.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                         $res = Crypto::newKeypair(4096);
167
168
169                         $private_key = $res['prvkey'];
170                         $public_key  = $res['pubkey'];
171
172                         // Save the private key. Send them the public key.
173
174                         $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
175                                 dbesc($private_key),
176                                 intval($contact_id),
177                                 intval($uid)
178                         );
179
180                         $params = array();
181
182                         /*
183                          *
184                          * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
185                          * site private key (person on the other end can decrypt it with our site public key).
186                          * Then encrypt our profile URL with the other person's site public key. They can decrypt
187                          * it with their site private key. If the decryption on the other end fails for either
188                          * item, it indicates tampering or key failure on at least one site and we will not be
189                          * able to provide a secure communication pathway.
190                          *
191                          * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
192                          * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
193                          * random key which is encrypted with their site public key.
194                          *
195                          */
196
197                         $src_aes_key = openssl_random_pseudo_bytes(64);
198
199                         $result = '';
200                         openssl_private_encrypt($dfrn_id, $result, $user[0]['prvkey']);
201
202                         $params['dfrn_id'] = bin2hex($result);
203                         $params['public_key'] = $public_key;
204
205
206                         $my_url = System::baseUrl() . '/profile/' . $user[0]['nickname'];
207
208                         openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
209                         $params['source_url'] = bin2hex($params['source_url']);
210
211                         if($aes_allow && function_exists('openssl_encrypt')) {
212                                 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
213                                 $params['aes_key'] = bin2hex($params['aes_key']);
214                                 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
215                         }
216
217                         $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
218                         if($duplex == 1)
219                                 $params['duplex'] = 1;
220
221                         if($user[0]['page-flags'] == PAGE_COMMUNITY)
222                                 $params['page'] = 1;
223                         if($user[0]['page-flags'] == PAGE_PRVGROUP)
224                                 $params['page'] = 2;
225
226                         logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params,true), LOGGER_DATA);
227
228                         /*
229                          *
230                          * POST all this stuff to the other site.
231                          * Temporarily raise the network timeout to 120 seconds because the default 60
232                          * doesn't always give the other side quite enough time to decrypt everything.
233                          *
234                          */
235
236                         $res = post_url($dfrn_confirm, $params, null, $redirects, 120);
237
238                         logger(' Confirm: received data: ' . $res, LOGGER_DATA);
239
240                         // Now figure out what they responded. Try to be robust if the remote site is
241                         // having difficulty and throwing up errors of some kind.
242
243                         $leading_junk = substr($res,0,strpos($res,'<?xml'));
244
245                         $res = substr($res,strpos($res,'<?xml'));
246                         if(! strlen($res)) {
247
248                                         // No XML at all, this exchange is messed up really bad.
249                                         // We shouldn't proceed, because the xml parser might choke,
250                                         // and $status is going to be zero, which indicates success.
251                                         // We can hardly call this a success.
252
253                                 notice( t('Response from remote site was not understood.') . EOL);
254                                 return;
255                         }
256
257                         if(strlen($leading_junk) && Config::get('system','debugging')) {
258
259                                         // This might be more common. Mixed error text and some XML.
260                                         // If we're configured for debugging, show the text. Proceed in either case.
261
262                                 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
263                         }
264
265                         if(stristr($res, "<status")===false) {
266                                 // wrong xml! stop here!
267                                 notice( t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL );
268                                 return;
269                         }
270
271                         $xml = parse_xml_string($res);
272                         $status = (int) $xml->status;
273                         $message = unxmlify($xml->message);   // human readable text of what may have gone wrong.
274                         switch($status) {
275                                 case 0:
276                                         info( t("Confirmation completed successfully.") . EOL);
277                                         if(strlen($message))
278                                                 notice( t('Remote site reported: ') . $message . EOL);
279                                         break;
280                                 case 1:
281                                         // birthday paradox - generate new dfrn-id and fall through.
282                                         $new_dfrn_id = random_string();
283                                         $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
284                                                 dbesc($new_dfrn_id),
285                                                 intval($contact_id),
286                                                 intval($uid)
287                                         );
288
289                                 case 2:
290                                         notice( t("Temporary failure. Please wait and try again.") . EOL);
291                                         if(strlen($message))
292                                                 notice( t('Remote site reported: ') . $message . EOL);
293                                         break;
294
295
296                                 case 3:
297                                         notice( t("Introduction failed or was revoked.") . EOL);
298                                         if(strlen($message))
299                                                 notice( t('Remote site reported: ') . $message . EOL);
300                                         break;
301                                 }
302
303                         if(($status == 0) && ($intro_id)) {
304
305                                 // Success. Delete the notification.
306
307                                 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d",
308                                         intval($intro_id),
309                                         intval($uid)
310                                 );
311
312                         }
313
314                         if($status != 0)
315                                 return;
316                 }
317
318
319                 /*
320                  *
321                  * We have now established a relationship with the other site.
322                  * Let's make our own personal copy of their profile photo so we don't have
323                  * to always load it from their site.
324                  *
325                  * We will also update the contact record with the nature and scope of the relationship.
326                  *
327                  */
328
329                 Contact::updateAvatar($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::sendShare($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                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
506
507                 // Let's send our user to the contact editor in case they want to
508                 // do anything special with this new friend.
509                 if ($handsfree === null) {
510                         goaway(System::baseUrl() . '/contacts/' . intval($contact_id));
511                 } else {
512                         return;
513                 }
514                 //NOTREACHED
515         }
516
517         /*
518          *
519          *
520          * End of Scenario 1. [Local confirmation of remote friend request].
521          *
522          * Begin Scenario 2. This is the remote response to the above scenario.
523          * This will take place on the site that originally initiated the friend request.
524          * In the section above where the confirming party makes a POST and
525          * retrieves xml status information, they are communicating with the following code.
526          *
527          */
528
529         if (x($_POST,'source_url')) {
530
531                 // We are processing an external confirmation to an introduction created by our user.
532
533                 $public_key = ((x($_POST,'public_key'))   ? $_POST['public_key']           : '');
534                 $dfrn_id    = ((x($_POST,'dfrn_id'))      ? hex2bin($_POST['dfrn_id'])     : '');
535                 $source_url = ((x($_POST,'source_url'))   ? hex2bin($_POST['source_url'])  : '');
536                 $aes_key    = ((x($_POST,'aes_key'))      ? $_POST['aes_key']              : '');
537                 $duplex     = ((x($_POST,'duplex'))       ? intval($_POST['duplex'])       : 0 );
538                 $page       = ((x($_POST,'page'))         ? intval($_POST['page'])         : 0 );
539                 $version_id = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
540
541                 $forum = (($page == 1) ? 1 : 0);
542                 $prv   = (($page == 2) ? 1 : 0);
543
544                 logger('dfrn_confirm: requestee contacted: ' . $node);
545
546                 logger('dfrn_confirm: request: POST=' . print_r($_POST,true), LOGGER_DATA);
547
548                 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
549
550                 if (x($aes_key)) {
551                         $aes_key = hex2bin($aes_key);
552                         $public_key = hex2bin($public_key);
553                 }
554
555                 // Find our user's account
556
557                 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
558                         dbesc($node));
559
560                 if (! DBM::is_result($r)) {
561                         $message = sprintf(t('No user record found for \'%s\' '), $node);
562                         xml_status(3,$message); // failure
563                         // NOTREACHED
564                 }
565
566                 $my_prvkey = $r[0]['prvkey'];
567                 $local_uid = $r[0]['uid'];
568
569
570                 if(! strstr($my_prvkey,'PRIVATE KEY')) {
571                         $message = t('Our site encryption key is apparently messed up.');
572                         xml_status(3,$message);
573                 }
574
575                 // verify everything
576
577                 $decrypted_source_url = "";
578                 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
579
580
581                 if(! strlen($decrypted_source_url)) {
582                         $message = t('Empty site URL was provided or URL could not be decrypted by us.');
583                         xml_status(3,$message);
584                         // NOTREACHED
585                 }
586
587                 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
588                         dbesc($decrypted_source_url),
589                         intval($local_uid)
590                 );
591                 if (!DBM::is_result($ret)) {
592                         if (strstr($decrypted_source_url,'http:')) {
593                                 $newurl = str_replace('http:','https:',$decrypted_source_url);
594                         } else {
595                                 $newurl = str_replace('https:','http:',$decrypted_source_url);
596                         }
597
598                         $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
599                                 dbesc($newurl),
600                                 intval($local_uid)
601                         );
602                         if (!DBM::is_result($ret)) {
603                                 // this is either a bogus confirmation (?) or we deleted the original introduction.
604                                 $message = t('Contact record was not found for you on our site.');
605                                 xml_status(3,$message);
606                                 return; // NOTREACHED
607                         }
608                 }
609
610                 $relation = $ret[0]['rel'];
611
612                 // Decrypt all this stuff we just received
613
614                 $foreign_pubkey = $ret[0]['site-pubkey'];
615                 $dfrn_record    = $ret[0]['id'];
616
617                 if (! $foreign_pubkey) {
618                         $message = sprintf( t('Site public key not available in contact record for URL %s.'), $newurl);
619                         xml_status(3,$message);
620                 }
621
622                 $decrypted_dfrn_id = "";
623                 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
624
625                 if (strlen($aes_key)) {
626                         $decrypted_aes_key = "";
627                         openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
628                         $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
629                 }
630                 else {
631                         $dfrn_pubkey = $public_key;
632                 }
633
634                 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
635                         dbesc($decrypted_dfrn_id)
636                 );
637                 if (DBM::is_result($r)) {
638                         $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
639                         xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
640                         // NOTREACHED
641                 }
642
643                 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
644                         dbesc($decrypted_dfrn_id),
645                         dbesc($dfrn_pubkey),
646                         intval($dfrn_record)
647                 );
648                 if (! DBM::is_result($r)) {
649                         $message = t('Unable to set your contact credentials on our system.');
650                         xml_status(3,$message);
651                 }
652
653                 // It's possible that the other person also requested friendship.
654                 // If it is a duplex relationship, ditch the issued-id if one exists.
655
656                 if($duplex) {
657                         $r = q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
658                                 intval($dfrn_record)
659                         );
660                 }
661
662                 // We're good but now we have to scrape the profile photo and send notifications.
663
664
665
666                 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
667                         intval($dfrn_record));
668
669                 if (DBM::is_result($r)) {
670                         $photo = $r[0]['photo'];
671                 } else {
672                         $photo = System::baseUrl() . '/images/person-175.jpg';
673                 }
674
675                 Contact::updateAvatar($photo,$local_uid,$dfrn_record);
676
677                 logger('dfrn_confirm: request - photos imported');
678
679                 $new_relation = CONTACT_IS_SHARING;
680                 if (($relation == CONTACT_IS_FOLLOWER) || ($duplex)) {
681                         $new_relation = CONTACT_IS_FRIEND;
682                 }
683
684                 if (($relation == CONTACT_IS_FOLLOWER) && ($duplex)) {
685                         $duplex = 0;
686                 }
687
688                 $r = q("UPDATE `contact` SET
689                         `rel` = %d,
690                         `name-date` = '%s',
691                         `uri-date` = '%s',
692                         `blocked` = 0,
693                         `pending` = 0,
694                         `duplex` = %d,
695                         `forum` = %d,
696                         `prv` = %d,
697                         `network` = '%s' WHERE `id` = %d
698                 ",
699                         intval($new_relation),
700                         dbesc(datetime_convert()),
701                         dbesc(datetime_convert()),
702                         intval($duplex),
703                         intval($forum),
704                         intval($prv),
705                         dbesc(NETWORK_DFRN),
706                         intval($dfrn_record)
707                 );
708                 if ($r === false) {    // indicates schema is messed up or total db failure
709                         $message = t('Unable to update your contact profile details on our system');
710                         xml_status(3,$message);
711                 }
712
713                 // Otherwise everything seems to have worked and we are almost done. Yay!
714                 // Send an email notification
715
716                 logger('dfrn_confirm: request: info updated');
717
718                 $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
719                         WHERE `contact`.`id` = %d LIMIT 1",
720                         intval($dfrn_record)
721                 );
722
723                 if (DBM::is_result($r))
724                         $combined = $r[0];
725
726                 if((DBM::is_result($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
727                         $mutual = ($new_relation == CONTACT_IS_FRIEND);
728                         notification(array(
729                                 'type'         => NOTIFY_CONFIRM,
730                                 'notify_flags' => $r[0]['notify-flags'],
731                                 'language'     => $r[0]['language'],
732                                 'to_name'      => $r[0]['username'],
733                                 'to_email'     => $r[0]['email'],
734                                 'uid'          => $r[0]['uid'],
735                                 'link'             => System::baseUrl() . '/contacts/' . $dfrn_record,
736                                 'source_name'  => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
737                                 'source_link'  => $r[0]['url'],
738                                 'source_photo' => $r[0]['photo'],
739                                 'verb'         => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
740                                 'otype'        => 'intro'
741                         ));
742                 }
743
744                 // Send a new friend post if we are allowed to...
745
746                 if($page && intval(PConfig::get($local_uid,'system','post_joingroup'))) {
747                         $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
748                                 intval($local_uid)
749                         );
750
751                         if((DBM::is_result($r)) && ($r[0]['hide-friends'] == 0)) {
752
753                                 require_once 'include/items.php';
754
755                                 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
756                                         intval($local_uid)
757                                 );
758
759                                 if(count($self)) {
760
761                                         $arr = array();
762                                         $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $local_uid);
763                                         $arr['uid'] = $local_uid;
764                                         $arr['contact-id'] = $self[0]['id'];
765                                         $arr['wall'] = 1;
766                                         $arr['type'] = 'wall';
767                                         $arr['gravity'] = 0;
768                                         $arr['origin'] = 1;
769                                         $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
770                                         $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
771                                         $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
772
773                                         $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
774                                         $APhoto = '[url=' . $self[0]['url'] . ']' . '[img]' . $self[0]['thumb'] . '[/img][/url]';
775
776                                         $B = '[url=' . $combined['url'] . ']' . $combined['name'] . '[/url]';
777                                         $BPhoto = '[url=' . $combined['url'] . ']' . '[img]' . $combined['thumb'] . '[/img][/url]';
778
779                                         $arr['verb'] = ACTIVITY_JOIN;
780                                         $arr['object-type'] = ACTIVITY_OBJ_GROUP;
781                                         $arr['body'] =  sprintf( t('%1$s has joined %2$s'), $A, $B)."\n\n\n" .$BPhoto;
782                                         $arr['object'] = '<object><type>' . ACTIVITY_OBJ_GROUP . '</type><title>' . $combined['name'] . '</title>'
783                                                 . '<id>' . $combined['url'] . '/' . $combined['name'] . '</id>';
784                                         $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $combined['url'] . '" />' . "\n");
785                                         $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $combined['thumb'] . '" />' . "\n");
786                                         $arr['object'] .= '</link></object>' . "\n";
787
788                                         $arr['last-child'] = 1;
789
790                                         $arr['allow_cid'] = $user[0]['allow_cid'];
791                                         $arr['allow_gid'] = $user[0]['allow_gid'];
792                                         $arr['deny_cid']  = $user[0]['deny_cid'];
793                                         $arr['deny_gid']  = $user[0]['deny_gid'];
794
795                                         $i = item_store($arr);
796                                         if($i)
797                                                 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
798
799                                 }
800                         }
801                 }
802                 xml_status(0); // Success
803                 return; // NOTREACHED
804
805                         ////////////////////// End of this scenario ///////////////////////////////////////////////
806         }
807
808         // somebody arrived here by mistake or they are fishing. Send them to the homepage.
809
810         goaway(System::baseUrl());
811         // NOTREACHED
812
813 }