]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_request.php
More logging in case of errors + logged network type + added TODO (for ugly E_NOTICE).
[friendica.git] / mod / dfrn_request.php
1 <?php
2
3 /**
4  *
5  * Module: dfrn_request
6  *
7  * Purpose: Handles communication associated with the issuance of
8  * friend requests.
9  *
10  */
11
12 require_once('include/enotify.php');
13 require_once('include/Scrape.php');
14
15 if(! function_exists('dfrn_request_init')) {
16 function dfrn_request_init(&$a) {
17
18         if($a->argc > 1)
19                 $which = $a->argv[1];
20
21         profile_load($a,$which);
22         return;
23 }}
24
25
26 /**
27  * Function: dfrn_request_post
28  *
29  * Purpose:
30  * Handles multiple scenarios.
31  *
32  * Scenario 1:
33  * Clicking 'submit' on a friend request page.
34  *
35  * Scenario 2:
36  * Following Scenario 1, we are brought back to our home site
37  * in order to link our friend request with our own server cell.
38  * After logging in, we click 'submit' to approve the linkage.
39  *
40  */
41
42 if(! function_exists('dfrn_request_post')) {
43 function dfrn_request_post(&$a) {
44
45         if(($a->argc != 2) || (! count($a->profile))) {
46                 logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
47                 return;
48         }
49
50
51         if(x($_POST, 'cancel')) {
52                 goaway(z_root());
53         }
54
55
56         /**
57          *
58          * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
59          * to confirm the request, and then we've clicked submit (perhaps after logging in).
60          * That brings us here:
61          *
62          */
63
64         if((x($_POST,'localconfirm')) && ($_POST['localconfirm'] == 1)) {
65
66                 /**
67                  * Ensure this is a valid request
68                  */
69
70                 if(local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST,'dfrn_url'))) {
71
72
73                         $dfrn_url    = notags(trim($_POST['dfrn_url']));
74                         $aes_allow   = (((x($_POST,'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
75                         $confirm_key = ((x($_POST,'confirm_key')) ? $_POST['confirm_key'] : "");
76                         $hidden = ((x($_POST,'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
77                         $contact_record = null;
78
79                         if(x($dfrn_url)) {
80
81                                 /**
82                                  * Lookup the contact based on their URL (which is the only unique thing we have at the moment)
83                                  */
84
85                                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND (`url` = '%s' OR `nurl` = '%s') AND `self` = 0 LIMIT 1",
86                                         intval(local_user()),
87                                         dbesc($dfrn_url),
88                                         dbesc(normalise_link($dfrn_url))
89                                 );
90
91                                 if(count($r)) {
92                                         if(strlen($r[0]['dfrn-id'])) {
93
94                                                 /**
95                                                  * We don't need to be here. It has already happened.
96                                                  */
97
98                                                 notice( t("This introduction has already been accepted.") . EOL );
99                                                 return;
100                                         }
101                                         else
102                                                 $contact_record = $r[0];
103                                 }
104
105                                 if(is_array($contact_record)) {
106                                         $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
107                                                 intval($aes_allow),
108                                                 intval($hidden),
109                                                 intval($contact_record['id'])
110                                         );
111                                 }
112                                 else {
113
114                                         /**
115                                          * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
116                                          */
117
118                                         $parms = scrape_dfrn($dfrn_url);
119
120                                         if(! count($parms)) {
121                                                 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
122                                                 return;
123                                         }
124                                         else {
125                                                 if(! x($parms,'fn'))
126                                                         notice( t('Warning: profile location has no identifiable owner name.') . EOL );
127                                                 if(! x($parms,'photo'))
128                                                         notice( t('Warning: profile location has no profile photo.') . EOL );
129                                                 $invalid = validate_dfrn($parms);
130                                                 if($invalid) {
131                                                         notice( sprintf( tt("%d required parameter was not found at the given location",
132                                                                                                 "%d required parameters were not found at the given location",
133                                                                                                 $invalid), $invalid) . EOL );
134                                                         return;
135                                                 }
136                                         }
137
138                                         $dfrn_request = $parms['dfrn-request'];
139
140                                         /********* Escape the entire array ********/
141
142                                         dbesc_array($parms);
143
144                                         /******************************************/
145
146                                         /**
147                                          * Create a contact record on our site for the other person
148                                          */
149
150                                         $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
151                                                 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`)
152                                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
153                                                 intval(local_user()),
154                                                 datetime_convert(),
155                                                 dbesc($dfrn_url),
156                                                 dbesc(normalise_link($dfrn_url)),
157                                                 $parms['addr'],
158                                                 $parms['fn'],
159                                                 $parms['nick'],
160                                                 $parms['photo'],
161                                                 $parms['key'],
162                                                 $parms['dfrn-request'],
163                                                 $parms['dfrn-confirm'],
164                                                 $parms['dfrn-notify'],
165                                                 $parms['dfrn-poll'],
166                                                 $parms['dfrn-poco'],
167                                                 dbesc(NETWORK_DFRN),
168                                                 intval($aes_allow),
169                                                 intval($hidden)
170                                         );
171                                 }
172
173                                 if($r) {
174                                         info( t("Introduction complete.") . EOL);
175                                 }
176
177                                 $r = q("select id from contact where uid = %d and url = '%s' and `site-pubkey` = '%s' limit 1",
178                                         intval(local_user()),
179                                         dbesc($dfrn_url),
180                                         $parms['key'] // this was already escaped
181                                 );
182                                 if(count($r)) {
183                                         $g = q("select def_gid from user where uid = %d limit 1",
184                                                 intval(local_user())
185                                         );
186                                         if($g && intval($g[0]['def_gid'])) {
187                                                 require_once('include/group.php');
188                                                 group_add_member(local_user(),'',$r[0]['id'],$g[0]['def_gid']);
189                                         }
190                                         $forwardurl = $a->get_baseurl()."/contacts/".$r[0]['id'];
191                                 } else
192                                         $forwardurl = $a->get_baseurl()."/contacts";
193
194                                 /**
195                                  * Allow the blocked remote notification to complete
196                                  */
197
198                                 if(is_array($contact_record))
199                                         $dfrn_request = $contact_record['request'];
200
201                                 if(strlen($dfrn_request) && strlen($confirm_key))
202                                         $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
203
204                                 // (ignore reply, nothing we can do it failed)
205
206                                 // Old: goaway(zrl($dfrn_url));
207                                 goaway($forwardurl);
208                                 return; // NOTREACHED
209
210                         }
211
212                 }
213
214                 // invalid/bogus request
215
216                 notice( t('Unrecoverable protocol error.') . EOL );
217                 goaway(z_root());
218                 return; // NOTREACHED
219         }
220
221         /**
222          * Otherwise:
223          *
224          * Scenario 1:
225          * We are the requestee. A person from a remote cell has made an introduction
226          * on our profile web page and clicked submit. We will use their DFRN-URL to
227          * figure out how to contact their cell.
228          *
229          * Scrape the originating DFRN-URL for everything we need. Create a contact record
230          * and an introduction to show our user next time he/she logs in.
231          * Finally redirect back to the requestor so that their site can record the request.
232          * If our user (the requestee) later confirms this request, a record of it will need
233          * to exist on the requestor's cell in order for the confirmation process to complete..
234          *
235          * It's possible that neither the requestor or the requestee are logged in at the moment,
236          * and the requestor does not yet have any credentials to the requestee profile.
237          *
238          * Who is the requestee? We've already loaded their profile which means their nickname should be
239          * in $a->argv[1] and we should have their complete info in $a->profile.
240          *
241          */
242
243         if(! (is_array($a->profile) && count($a->profile))) {
244                 notice( t('Profile unavailable.') . EOL);
245                 return;
246         }
247
248         $nickname       = $a->profile['nickname'];
249         $notify_flags   = $a->profile['notify-flags'];
250         $uid            = $a->profile['uid'];
251         $maxreq         = intval($a->profile['maxreq']);
252         $contact_record = null;
253         $failed         = false;
254         $parms          = null;
255
256
257         if( x($_POST,'dfrn_url')) {
258
259                 /**
260                  * Block friend request spam
261                  */
262
263                 if($maxreq) {
264                         $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
265                                 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
266                                 intval($uid)
267                         );
268                         if(count($r) > $maxreq) {
269                                 notice( sprintf( t('%s has received too many connection requests today.'),  $a->profile['name']) . EOL);
270                                 notice( t('Spam protection measures have been invoked.') . EOL);
271                                 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
272                                 return;
273                         }
274                 }
275
276                 /**
277                  *
278                  * Cleanup old introductions that remain blocked.
279                  * Also remove the contact record, but only if there is no existing relationship
280                  * Do not remove email contacts as these may be awaiting email verification
281                  */
282
283                 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
284                         FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
285                         WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
286                         AND `contact`.`network` != '%s'
287                         AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ",
288                         dbesc(NETWORK_MAIL2)
289                 );
290                 if(count($r)) {
291                         foreach($r as $rr) {
292                                 if(! $rr['rel']) {
293                                         q("DELETE FROM `contact` WHERE `id` = %d",
294                                                 intval($rr['cid'])
295                                         );
296                                 }
297                                 q("DELETE FROM `intro` WHERE `id` = %d",
298                                         intval($rr['iid'])
299                                 );
300                         }
301                 }
302
303                 /**
304                  *
305                  * Cleanup any old email intros - which will have a greater lifetime
306                  */
307
308                 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
309                         FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
310                         WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
311                         AND `contact`.`network` = '%s'
312                         AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ",
313                         dbesc(NETWORK_MAIL2)
314                 );
315                 if(count($r)) {
316                         foreach($r as $rr) {
317                                 if(! $rr['rel']) {
318                                         q("DELETE FROM `contact` WHERE `id` = %d",
319                                                 intval($rr['cid'])
320                                         );
321                                 }
322                                 q("DELETE FROM `intro` WHERE `id` = %d",
323                                         intval($rr['iid'])
324                                 );
325                         }
326                 }
327
328                 $email_follow = (x($_POST,'email_follow') ? intval($_POST['email_follow']) : 0);
329                 $real_name = (x($_POST,'realname') ? notags(trim($_POST['realname'])) : '');
330
331                 $url = trim($_POST['dfrn_url']);
332                 if(! strlen($url)) {
333                         notice( t("Invalid locator") . EOL );
334                         return;
335                 }
336
337                 $hcard = '';
338
339                 if($email_follow) {
340
341                         if(! validate_email($url)) {
342                                 notice( t('Invalid email address.') . EOL);
343                                 return;
344                         }
345
346                         $addr    = $url;
347                         $name    = ($realname) ? $realname : $addr;
348                         $nick    = substr($addr,0,strpos($addr,'@'));
349                         $url     = 'http://' . substr($addr,strpos($addr,'@') + 1);
350                         $nurl    = normalise_url($host);
351                         $poll    = 'email ' . random_string();
352                         $notify  = 'smtp ' . random_string();
353                         $blocked = 1;
354                         $pending = 1;
355                         $network = NETWORK_MAIL2;
356                         $rel     = CONTACT_IS_FOLLOWER;
357
358                         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
359                         if(get_config('system','dfrn_only'))
360                                 $mail_disabled = 1;
361
362                         if(! $mail_disabled) {
363                                 $failed = false;
364                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
365                                         intval($uid)
366                                 );
367                                 if(! count($r)) {
368
369                                         notice( t('This account has not been configured for email. Request failed.') . EOL);
370                                         return;
371                                 }
372                         }
373
374                         $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
375                                 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
376                                 intval($uid),
377                                 dbesc(datetime_convert()),
378                                 dbesc($addr),
379                                 dbesc($name),
380                                 dbesc($nick),
381                                 dbesc($url),
382                                 dbesc($nurl),
383                                 dbesc($poll),
384                                 dbesc($notify),
385                                 intval($blocked),
386                                 intval($pending),
387                                 dbesc($network),
388                                 intval($rel)
389                         );
390
391                         $r = q("select id from contact where poll = '%s' and uid = %d limit 1",
392                                 dbesc($poll),
393                                 intval($uid)
394                         );
395                         if(count($r)) {
396                                 $contact_id = $r[0]['id'];
397
398                                 $g = q("select def_gid from user where uid = %d limit 1",
399                                         intval($uid)
400                                 );
401                                 if($g && intval($g[0]['def_gid'])) {
402                                         require_once('include/group.php');
403                                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
404                                 }
405
406                                 $photo = avatar_img($addr);
407
408                                 $r = q("UPDATE `contact` SET
409                                         `photo` = '%s',
410                                         `thumb` = '%s',
411                                         `micro` = '%s',
412                                         `name-date` = '%s',
413                                         `uri-date` = '%s',
414                                         `avatar-date` = '%s',
415                                         `hidden` = 0,
416                                         WHERE `id` = %d
417                                 ",
418                                         dbesc($photos[0]),
419                                         dbesc($photos[1]),
420                                         dbesc($photos[2]),
421                                         dbesc(datetime_convert()),
422                                         dbesc(datetime_convert()),
423                                         dbesc(datetime_convert()),
424                                         intval($contact_id)
425                                 );
426                         }
427
428                         // contact is created. Now create an introduction
429
430                         $hash = random_string();
431
432                         $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
433                                 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
434                                 intval($uid),
435                                 intval($contact_id),
436                                 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
437                                 dbesc(notags(trim($_POST['dfrn-request-message']))),
438                                 dbesc($hash),
439                                 dbesc(datetime_convert()),
440                                 1
441                         );
442
443                         // Next send an email verify form to the requestor.
444
445                 } else {
446                         // Detect the network
447                         $data = probe_url($url);
448                         $network = $data["network"];
449
450                         // Canonicalise email-style profile locator
451                         $url = webfinger_dfrn($url,$hcard);
452
453                         if (substr($url,0,5) === 'stat:') {
454
455                                 // Every time we detect the remote subscription we define this as OStatus.
456                                 // We do this even if it is not OStatus.
457                                 // we only need to pass this through another section of the code.
458                                 if ($network != NETWORK_DIASPORA)
459                                         $network = NETWORK_OSTATUS;
460
461                                 $url = substr($url,5);
462                         } else
463                                 $network = NETWORK_DFRN;
464                 }
465
466                 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
467
468                 if($network === NETWORK_DFRN) {
469                         $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
470                                 intval($uid),
471                                 dbesc($url)
472                         );
473
474                         if(count($ret)) {
475                                 if(strlen($ret[0]['issued-id'])) {
476                                         notice( t('You have already introduced yourself here.') . EOL );
477                                         return;
478                                 }
479                                 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
480                                         notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
481                                         return;
482                                 }
483                                 else {
484                                         $contact_record = $ret[0];
485                                         $parms = array('dfrn-request' => $ret[0]['request']);
486                                 }
487                         }
488
489                         $issued_id = random_string();
490
491                         if(is_array($contact_record)) {
492                                 // There is a contact record but no issued-id, so this
493                                 // is a reciprocal introduction from a known contact
494                                 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
495                                         dbesc($issued_id),
496                                         intval($contact_record['id'])
497                                 );
498                         }
499                         else {
500                                 if(! validate_url($url)) {
501                                         notice( t('Invalid profile URL.') . EOL);
502                                         goaway($a->get_baseurl() . '/' . $a->cmd);
503                                         return; // NOTREACHED
504                                 }
505
506                                 if(! allowed_url($url)) {
507                                         notice( t('Disallowed profile URL.') . EOL);
508                                         goaway($a->get_baseurl() . '/' . $a->cmd);
509                                         return; // NOTREACHED
510                                 }
511
512
513                                 require_once('include/Scrape.php');
514
515                                 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
516
517                                 if(! count($parms)) {
518                                         notice( t('Profile location is not valid or does not contain profile information.') . EOL );
519                                         goaway($a->get_baseurl() . '/' . $a->cmd);
520                                 }
521                                 else {
522                                         if(! x($parms,'fn'))
523                                                 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
524                                         if(! x($parms,'photo'))
525                                                 notice( t('Warning: profile location has no profile photo.') . EOL );
526                                         $invalid = validate_dfrn($parms);
527                                         if($invalid) {
528                                                 notice( sprintf( tt("%d required parameter was not found at the given location",
529                                                                                         "%d required parameters were not found at the given location",
530                                                                                         $invalid), $invalid) . EOL );
531
532                                                 return;
533                                         }
534                                 }
535
536
537                                 $parms['url'] = $url;
538                                 $parms['issued-id'] = $issued_id;
539
540
541                                 dbesc_array($parms);
542                                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
543                                         `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
544                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
545                                         intval($uid),
546                                         dbesc(datetime_convert()),
547                                         $parms['url'],
548                                         dbesc(normalise_link($parms['url'])),
549                                         $parms['addr'],
550                                         $parms['fn'],
551                                         $parms['nick'],
552                                         $parms['issued-id'],
553                                         $parms['photo'],
554                                         $parms['key'],
555                                         $parms['dfrn-request'],
556                                         $parms['dfrn-confirm'],
557                                         $parms['dfrn-notify'],
558                                         $parms['dfrn-poll'],
559                                         $parms['dfrn-poco'],
560                                         dbesc(NETWORK_DFRN)
561                                 );
562
563                                 // find the contact record we just created
564                                 if($r) {
565                                         $r = q("SELECT `id` FROM `contact`
566                                                 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
567                                                 intval($uid),
568                                                 $parms['url'],
569                                                 $parms['issued-id']
570                                         );
571                                         if(count($r))
572                                                 $contact_record = $r[0];
573                                 }
574
575                         }
576                         if($r === false) {
577                                 notice( t('Failed to update contact record.') . EOL );
578                                 return;
579                         }
580
581                         $hash = random_string() . (string) time();   // Generate a confirm_key
582
583                         if(is_array($contact_record)) {
584                                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
585                                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
586                                         intval($uid),
587                                         intval($contact_record['id']),
588                                         ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
589                                         dbesc(notags(trim($_POST['dfrn-request-message']))),
590                                         dbesc($hash),
591                                         dbesc(datetime_convert())
592                                 );
593                         }
594
595                         // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
596
597                         if(! $failed)
598                                 info( t('Your introduction has been sent.') . EOL );
599
600                         // "Homecoming" - send the requestor back to their site to record the introduction.
601
602                         $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
603                         $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
604
605                         goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
606                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
607                                 . '&confirm_key='  . $hash
608                                 . (($aes_allow) ? "&aes_allow=1" : "")
609                         );
610                         // NOTREACHED
611                         // END $network === NETWORK_DFRN
612                 } elseif (($network != NETWORK_PHANTOM) AND ($url != "")) {
613
614                         /**
615                          *
616                          * Substitute our user's feed URL into $url template
617                          * Send the subscriber home to subscribe
618                          *
619                          */
620
621                         // Diaspora needs the uri in the format user@domain.tld
622                         // Diaspora will support the remote subscription in a future version
623                         if ($network == NETWORK_DIASPORA) {
624                                 $uri = $nickname.'@'.$a->get_hostname();
625
626                                 if ($a->get_path())
627                                         $uri .= '/'.$a->get_path();
628
629                                 $uri = urlencode($uri);
630                         } else
631                                 $uri = $a->get_baseurl().'/profile/'.$nickname;
632
633                         $url = str_replace('{uri}', $uri, $url);
634                         goaway($url);
635                         // NOTREACHED
636                         // END $network != NETWORK_PHANTOM
637                 } else {
638                         notice(t("Remote subscription can't be done for your network. Please subscribe directly on your system.").EOL);
639                         return;
640                 }
641
642         }       return;
643 }}
644
645
646
647
648 if(! function_exists('dfrn_request_content')) {
649 function dfrn_request_content(&$a) {
650
651         if(($a->argc != 2) || (! count($a->profile)))
652                 return "";
653
654
655         // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
656         // to send us to the post section to record the introduction.
657
658         if(x($_GET,'dfrn_url')) {
659
660                 if(! local_user()) {
661                         info( t("Please login to confirm introduction.") . EOL );
662                         /* setup the return URL to come back to this page if they use openid */
663                         $_SESSION['return_url'] = $a->query_string;
664                         return login();
665                 }
666
667                 // Edge case, but can easily happen in the wild. This person is authenticated,
668                 // but not as the person who needs to deal with this request.
669
670                 if ($a->user['nickname'] != $a->argv[1]) {
671                         notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
672                         return login();
673                 }
674
675                 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
676                 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
677                 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
678
679                 // Checking fastlane for validity
680                 if (x($_SESSION, "fastlane") AND (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
681                         $_POST["dfrn_url"] = $dfrn_url;
682                         $_POST["confirm_key"] = $confirm_key;
683                         $_POST["localconfirm"] = 1;
684                         $_POST["hidden-contact"] = 0;
685                         $_POST["submit"] = t('Confirm');
686
687                         dfrn_request_post($a);
688
689                         killme();
690                         return; // NOTREACHED
691                 }
692
693                 $tpl = get_markup_template("dfrn_req_confirm.tpl");
694                 $o  = replace_macros($tpl,array(
695                         '$dfrn_url' => $dfrn_url,
696                         '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
697                         '$hidethem' => t('Hide this contact'),
698                         '$hidechecked' => '',
699                         '$confirm_key' => $confirm_key,
700                         '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
701                         '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
702                         '$submit' => t('Confirm'),
703                         '$uid' => $_SESSION['uid'],
704                         '$nickname' => $a->user['nickname'],
705                         'dfrn_rawurl' => $_GET['dfrn_url']
706                         ));
707                 return $o;
708
709         }
710         elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
711
712                 // we are the requestee and it is now safe to send our user their introduction,
713                 // We could just unblock it, but first we have to jump through a few hoops to
714                 // send an email, or even to find out if we need to send an email.
715
716                 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
717                         dbesc($_GET['confirm_key'])
718                 );
719
720                 if(count($intro)) {
721
722                         $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
723                                 WHERE `contact`.`id` = %d LIMIT 1",
724                                 intval($intro[0]['contact-id'])
725                         );
726
727                         $auto_confirm = false;
728
729                         if(count($r)) {
730                                 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
731                                         $auto_confirm = true;
732
733                                 if(! $auto_confirm) {
734
735                                         notification(array(
736                                                 'type'         => NOTIFY_INTRO,
737                                                 'notify_flags' => $r[0]['notify-flags'],
738                                                 'language'     => $r[0]['language'],
739                                                 'to_name'      => $r[0]['username'],
740                                                 'to_email'     => $r[0]['email'],
741                                                 'uid'          => $r[0]['uid'],
742                                                 'link'             => $a->get_baseurl() . '/notifications/intros',
743                                                 'source_name'  => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
744                                                 'source_link'  => $r[0]['url'],
745                                                 'source_photo' => $r[0]['photo'],
746                                                 'verb'         => ACTIVITY_REQ_FRIEND,
747                                                 'otype'        => 'intro'
748                                         ));
749                                 }
750
751                                 if($auto_confirm) {
752                                         require_once('mod/dfrn_confirm.php');
753                                         $handsfree = array(
754                                                 'uid' => $r[0]['uid'],
755                                                 'node' => $r[0]['nickname'],
756                                                 'dfrn_id' => $r[0]['issued-id'],
757                                                 'intro_id' => $intro[0]['id'],
758                                                 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
759                                                 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
760                                         );
761                                         dfrn_confirm_post($a,$handsfree);
762                                 }
763
764                         }
765
766                         if(! $auto_confirm) {
767
768                                 // If we are auto_confirming, this record will have already been nuked
769                                 // in dfrn_confirm_post()
770
771                                 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
772                                         dbesc($_GET['confirm_key'])
773                                 );
774                         }
775                 }
776
777                 killme();
778                 return; // NOTREACHED
779         }
780         else {
781
782                 /**
783                  * Normal web request. Display our user's introduction form.
784                  */
785
786                 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
787                         if(! get_config('system','local_block')) {
788                                 notice( t('Public access denied.') . EOL);
789                                 return;
790                         }
791                 }
792
793
794                 /**
795                  * Try to auto-fill the profile address
796                  */
797
798                 // At first look if an address was provided
799                 // Otherwise take the local address
800                 if (x($_GET,'addr') AND ($_GET['addr'] != ""))
801                         $myaddr = hex2bin($_GET['addr']);
802                 elseif (x($_GET,'address') AND ($_GET['address'] != ""))
803                         $myaddr = $_GET['address'];
804                 elseif(local_user()) {
805                         if(strlen($a->path)) {
806                                 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
807                         }
808                         else {
809                                 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
810                         }
811                 } else  // last, try a zrl
812                         $myaddr = get_my_url();
813
814                 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
815
816
817                 /**
818                  *
819                  * The auto_request form only has the profile address
820                  * because nobody is going to read the comments and
821                  * it doesn't matter if they know you or not.
822                  *
823                  */
824
825                 if($a->profile['page-flags'] == PAGE_NORMAL)
826                         $tpl = get_markup_template('dfrn_request.tpl');
827                 else
828                         $tpl = get_markup_template('auto_request.tpl');
829
830                 // TODO This .= triggers an E_NOTICE, really needed?
831                 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported communications networks:");
832
833                 // see if we are allowed to have NETWORK_MAIL2 contacts
834
835                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
836                 if(get_config('system','dfrn_only'))
837                         $mail_disabled = 1;
838
839                 if(! $mail_disabled) {
840                         $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
841                                 intval($a->profile['uid'])
842                         );
843                         if(! count($r))
844                                 $mail_disabled = 1;
845                 }
846
847                 // "coming soon" is disabled for now
848                 //$emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
849                 $emailnet = "";
850
851                 $invite_desc = sprintf(
852                         t('If you are not yet a member of the free social web, <a href="%s/siteinfo">follow this link to find a public Friendica site and join us today</a>.'),
853                         get_server()
854                 );
855
856                 // TODO This .= triggers an E_NOTICE, really needed?
857                 $o .= replace_macros($tpl,array(
858                         '$header' => t('Friend/Connection Request'),
859                         '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
860                         '$pls_answer' => t('Please answer the following:'),
861                         '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'),$a->profile['name']), false, '', array(t('No'),t('Yes'))),
862                         /*'$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
863                         '$yes' => t('Yes'),
864                         '$no' => t('No'), */
865                         '$add_note' => t('Add a personal note:'),
866                         '$page_desc' => $page_desc,
867                         '$friendica' => t('Friendica'),
868                         '$statusnet' => t('StatusNet/Federated Social Web'),
869                         '$diaspora' => t('Diaspora'),
870                         '$diasnote' => sprintf (t(' - please do not use this form.  Instead, enter %s into your Diaspora search bar.'),$target_addr),
871                         '$your_address' => t('Your Identity Address:'),
872                         '$invite_desc' => $invite_desc,
873                         '$emailnet' => $emailnet,
874                         '$submit' => t('Submit Request'),
875                         '$cancel' => t('Cancel'),
876                         '$nickname' => $a->argv[1],
877                         '$name' => $a->profile['name'],
878                         '$myaddr' => $myaddr
879                 ));
880                 return $o;
881         }
882
883         return; // Somebody is fishing.
884 }}