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