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