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