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