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