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