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