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