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