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