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