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