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