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