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