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