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