Append author's contact id to allowed contacts to prevent empty ACL for private events
[friendica.git/.git] / mod / dfrn_request.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  *Handles communication associated with the issuance of friend requests.
21  *
22  * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/stable/spec/dfrn2.pdf
23  *    You also find a graphic which describes the confirmation process at
24  *    https://github.com/friendica/friendica/blob/stable/spec/dfrn2_contact_request.png
25  */
26
27 use Friendica\App;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Search;
32 use Friendica\Core\Session;
33 use Friendica\Core\System;
34 use Friendica\Database\DBA;
35 use Friendica\DI;
36 use Friendica\Model\Contact;
37 use Friendica\Model\Group;
38 use Friendica\Model\Notify;
39 use Friendica\Model\Notify\Type;
40 use Friendica\Model\Profile;
41 use Friendica\Model\User;
42 use Friendica\Module\Security\Login;
43 use Friendica\Network\Probe;
44 use Friendica\Protocol\Activity;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Network;
47 use Friendica\Util\Strings;
48
49 function dfrn_request_init(App $a)
50 {
51         if ($a->argc > 1) {
52                 $which = $a->argv[1];
53                 Profile::load($a, $which);
54         }
55
56         return;
57 }
58
59 /**
60  * Function: dfrn_request_post
61  *
62  * Purpose:
63  * Handles multiple scenarios.
64  *
65  * Scenario 1:
66  * Clicking 'submit' on a friend request page.
67  *
68  * Scenario 2:
69  * Following Scenario 1, we are brought back to our home site
70  * in order to link our friend request with our own server cell.
71  * After logging in, we click 'submit' to approve the linkage.
72  *
73  * @param App $a
74  * @throws ImagickException
75  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
76  */
77 function dfrn_request_post(App $a)
78 {
79         if ($a->argc != 2 || empty($a->profile)) {
80                 Logger::log('Wrong count of argc or profiles: argc=' . $a->argc . ', profile()=' . count($a->profile ?? []));
81                 return;
82         }
83
84         if (!empty($_POST['cancel'])) {
85                 DI::baseUrl()->redirect();
86         }
87
88         /*
89          * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
90          * to confirm the request, and then we've clicked submit (perhaps after logging in).
91          * That brings us here:
92          */
93         if (!empty($_POST['localconfirm']) && ($_POST['localconfirm'] == 1)) {
94                 // Ensure this is a valid request
95                 if (local_user() && ($a->user['nickname'] == $a->argv[1]) && !empty($_POST['dfrn_url'])) {
96                         $dfrn_url    = Strings::escapeTags(trim($_POST['dfrn_url']));
97                         $aes_allow   = !empty($_POST['aes_allow']);
98                         $confirm_key = $_POST['confirm_key'] ?? '';
99                         $hidden      = (!empty($_POST['hidden-contact']) ? intval($_POST['hidden-contact']) : 0);
100                         $contact_record = null;
101                         $blocked     = 1;
102                         $pending     = 1;
103
104                         if (!empty($dfrn_url)) {
105                                 // Lookup the contact based on their URL (which is the only unique thing we have at the moment)
106                                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND NOT `self` LIMIT 1",
107                                         intval(local_user()),
108                                         DBA::escape(Strings::normaliseLink($dfrn_url))
109                                 );
110
111                                 if (DBA::isResult($r)) {
112                                         if (strlen($r[0]['dfrn-id'])) {
113                                                 // We don't need to be here. It has already happened.
114                                                 notice(DI::l10n()->t("This introduction has already been accepted."));
115                                                 return;
116                                         } else {
117                                                 $contact_record = $r[0];
118                                         }
119                                 }
120
121                                 if (is_array($contact_record)) {
122                                         $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
123                                                 intval($aes_allow),
124                                                 intval($hidden),
125                                                 intval($contact_record['id'])
126                                         );
127                                 } else {
128                                         // Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
129                                         $parms = Probe::profile($dfrn_url);
130
131                                         if (!count($parms)) {
132                                                 notice(DI::l10n()->t('Profile location is not valid or does not contain profile information.'));
133                                                 return;
134                                         } else {
135                                                 if (empty($parms['fn'])) {
136                                                         notice(DI::l10n()->t('Warning: profile location has no identifiable owner name.'));
137                                                 }
138                                                 if (empty($parms['photo'])) {
139                                                         notice(DI::l10n()->t('Warning: profile location has no profile photo.'));
140                                                 }
141                                                 $invalid = Probe::validDfrn($parms);
142                                                 if ($invalid) {
143                                                         notice(DI::l10n()->tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid));
144                                                         return;
145                                                 }
146                                         }
147
148                                         $dfrn_request = $parms['dfrn-request'];
149
150                                         $photo = $parms["photo"];
151
152                                         // Escape the entire array
153                                         DBA::escapeArray($parms);
154
155                                         // Create a contact record on our site for the other person
156                                         $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
157                                                 `request`, `confirm`, `notify`, `poll`, `network`, `aes_allow`, `hidden`, `blocked`, `pending`)
158                                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d)",
159                                                 intval(local_user()),
160                                                 DateTimeFormat::utcNow(),
161                                                 DBA::escape($dfrn_url),
162                                                 DBA::escape(Strings::normaliseLink($dfrn_url)),
163                                                 $parms['addr'],
164                                                 $parms['fn'],
165                                                 $parms['nick'],
166                                                 $parms['photo'],
167                                                 $parms['key'],
168                                                 $parms['dfrn-request'],
169                                                 $parms['dfrn-confirm'],
170                                                 $parms['dfrn-notify'],
171                                                 $parms['dfrn-poll'],
172                                                 DBA::escape(Protocol::DFRN),
173                                                 intval($aes_allow),
174                                                 intval($hidden),
175                                                 intval($blocked),
176                                                 intval($pending)
177                                         );
178                                 }
179
180                                 if ($r) {
181                                         info(DI::l10n()->t("Introduction complete."));
182                                 }
183
184                                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
185                                         intval(local_user()),
186                                         DBA::escape($dfrn_url),
187                                         $parms['key'] ?? '' // Potentially missing
188                                 );
189                                 if (DBA::isResult($r)) {
190                                         Group::addMember(User::getDefaultGroup(local_user(), $r[0]["network"]), $r[0]['id']);
191
192                                         if (isset($photo)) {
193                                                 Contact::updateAvatar($r[0]["id"], $photo, true);
194                                         }
195
196                                         $forward_path = "contact/" . $r[0]['id'];
197                                 } else {
198                                         $forward_path = "contact";
199                                 }
200
201                                 // Allow the blocked remote notification to complete
202                                 if (is_array($contact_record)) {
203                                         $dfrn_request = $contact_record['request'];
204                                 }
205
206                                 if (!empty($dfrn_request) && strlen($confirm_key)) {
207                                         DI::httpRequest()->fetch($dfrn_request . '?confirm_key=' . $confirm_key);
208                                 }
209
210                                 // (ignore reply, nothing we can do it failed)
211                                 DI::baseUrl()->redirect($forward_path);
212                                 return; // NOTREACHED
213                         }
214                 }
215
216                 // invalid/bogus request
217                 notice(DI::l10n()->t('Unrecoverable protocol error.'));
218                 DI::baseUrl()->redirect();
219                 return; // NOTREACHED
220         }
221
222         /*
223          * Otherwise:
224          *
225          * Scenario 1:
226          * We are the requestee. A person from a remote cell has made an introduction
227          * on our profile web page and clicked submit. We will use their DFRN-URL to
228          * figure out how to contact their cell.
229          *
230          * Scrape the originating DFRN-URL for everything we need. Create a contact record
231          * and an introduction to show our user next time he/she logs in.
232          * Finally redirect back to the requestor so that their site can record the request.
233          * If our user (the requestee) later confirms this request, a record of it will need
234          * to exist on the requestor's cell in order for the confirmation process to complete..
235          *
236          * It's possible that neither the requestor or the requestee are logged in at the moment,
237          * and the requestor does not yet have any credentials to the requestee profile.
238          *
239          * Who is the requestee? We've already loaded their profile which means their nickname should be
240          * in $a->argv[1] and we should have their complete info in $a->profile.
241          *
242          */
243         if (empty($a->profile['uid'])) {
244                 notice(DI::l10n()->t('Profile unavailable.'));
245                 return;
246         }
247
248         $nickname       = $a->profile['nickname'];
249         $uid            = $a->profile['uid'];
250         $maxreq         = intval($a->profile['maxreq']);
251         $contact_record = null;
252         $failed         = false;
253         $parms          = null;
254         $blocked = 1;
255         $pending = 1;
256
257         if (!empty($_POST['dfrn_url'])) {
258                 // Block friend request spam
259                 if ($maxreq) {
260                         $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
261                                 DBA::escape(DateTimeFormat::utc('now - 24 hours')),
262                                 intval($uid)
263                         );
264                         if (DBA::isResult($r) && count($r) > $maxreq) {
265                                 notice(DI::l10n()->t('%s has received too many connection requests today.', $a->profile['name']));
266                                 notice(DI::l10n()->t('Spam protection measures have been invoked.'));
267                                 notice(DI::l10n()->t('Friends are advised to please try again in 24 hours.'));
268                                 return;
269                         }
270                 }
271
272                 /* Cleanup old introductions that remain blocked.
273                  * Also remove the contact record, but only if there is no existing relationship
274                  */
275                 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel`
276                         FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
277                         WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0
278                         AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE "
279                 );
280                 if (DBA::isResult($r)) {
281                         foreach ($r as $rr) {
282                                 if (!$rr['rel']) {
283                                         DBA::delete('contact', ['id' => $rr['cid'], 'self' => false]);
284                                 }
285                                 DBA::delete('intro', ['id' => $rr['iid']]);
286                         }
287                 }
288
289                 $url = trim($_POST['dfrn_url']);
290                 if (!strlen($url)) {
291                         notice(DI::l10n()->t("Invalid locator"));
292                         return;
293                 }
294
295                 $hcard = '';
296
297                 // Detect the network
298                 $data = Contact::getByURL($url);
299                 $network = $data["network"];
300
301                 // Canonicalize email-style profile locator
302                 $url = Probe::webfingerDfrn($data['url'] ?? $url, $hcard);
303
304                 if (substr($url, 0, 5) === 'stat:') {
305                         // Every time we detect the remote subscription we define this as OStatus.
306                         // We do this even if it is not OStatus.
307                         // we only need to pass this through another section of the code.
308                         if ($network != Protocol::DIASPORA) {
309                                 $network = Protocol::OSTATUS;
310                         }
311
312                         $url = substr($url, 5);
313                 } else {
314                         $network = Protocol::DFRN;
315                 }
316
317                 Logger::log('dfrn_request: url: ' . $url . ',network=' . $network, Logger::DEBUG);
318
319                 if ($network === Protocol::DFRN) {
320                         $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
321                                 intval($uid),
322                                 DBA::escape($url)
323                         );
324
325                         if (DBA::isResult($ret)) {
326                                 if (strlen($ret[0]['issued-id'])) {
327                                         notice(DI::l10n()->t('You have already introduced yourself here.'));
328                                         return;
329                                 } elseif ($ret[0]['rel'] == Contact::FRIEND) {
330                                         notice(DI::l10n()->t('Apparently you are already friends with %s.', $a->profile['name']));
331                                         return;
332                                 } else {
333                                         $contact_record = $ret[0];
334                                         $parms = ['dfrn-request' => $ret[0]['request']];
335                                 }
336                         }
337
338                         $issued_id = Strings::getRandomHex();
339
340                         if (is_array($contact_record)) {
341                                 // There is a contact record but no issued-id, so this
342                                 // is a reciprocal introduction from a known contact
343                                 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
344                                         DBA::escape($issued_id),
345                                         intval($contact_record['id'])
346                                 );
347                         } else {
348                                 $url = Network::isUrlValid($url);
349                                 if (!$url) {
350                                         notice(DI::l10n()->t('Invalid profile URL.'));
351                                         DI::baseUrl()->redirect(DI::args()->getCommand());
352                                         return; // NOTREACHED
353                                 }
354
355                                 if (!Network::isUrlAllowed($url)) {
356                                         notice(DI::l10n()->t('Disallowed profile URL.'));
357                                         DI::baseUrl()->redirect(DI::args()->getCommand());
358                                         return; // NOTREACHED
359                                 }
360
361                                 if (Network::isUrlBlocked($url)) {
362                                         notice(DI::l10n()->t('Blocked domain'));
363                                         DI::baseUrl()->redirect(DI::args()->getCommand());
364                                         return; // NOTREACHED
365                                 }
366
367                                 $parms = Probe::profile(($hcard) ? $hcard : $url);
368
369                                 if (!count($parms)) {
370                                         notice(DI::l10n()->t('Profile location is not valid or does not contain profile information.'));
371                                         DI::baseUrl()->redirect(DI::args()->getCommand());
372                                 } else {
373                                         if (empty($parms['fn'])) {
374                                                 notice(DI::l10n()->t('Warning: profile location has no identifiable owner name.'));
375                                         }
376                                         if (empty($parms['photo'])) {
377                                                 notice(DI::l10n()->t('Warning: profile location has no profile photo.'));
378                                         }
379                                         $invalid = Probe::validDfrn($parms);
380                                         if ($invalid) {
381                                                 notice(DI::l10n()->tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid));
382
383                                                 return;
384                                         }
385                                 }
386
387                                 $parms['url'] = $url;
388                                 $parms['issued-id'] = $issued_id;
389                                 $photo = $parms["photo"];
390
391                                 DBA::escapeArray($parms);
392                                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
393                                         `request`, `confirm`, `notify`, `poll`, `network`, `blocked`, `pending` )
394                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
395                                         intval($uid),
396                                         DBA::escape(DateTimeFormat::utcNow()),
397                                         $parms['url'],
398                                         DBA::escape(Strings::normaliseLink($url)),
399                                         $parms['addr'],
400                                         $parms['fn'],
401                                         $parms['nick'],
402                                         $parms['issued-id'],
403                                         $parms['photo'],
404                                         $parms['key'],
405                                         $parms['dfrn-request'],
406                                         $parms['dfrn-confirm'],
407                                         $parms['dfrn-notify'],
408                                         $parms['dfrn-poll'],
409                                         DBA::escape(Protocol::DFRN),
410                                         intval($blocked),
411                                         intval($pending)
412                                 );
413
414                                 // find the contact record we just created
415                                 if ($r) {
416                                         $r = q("SELECT `id` FROM `contact`
417                                                 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
418                                                 intval($uid),
419                                                 $parms['url'],
420                                                 $parms['issued-id']
421                                         );
422                                         if (DBA::isResult($r)) {
423                                                 $contact_record = $r[0];
424                                                 Contact::updateAvatar($contact_record["id"], $photo, true);
425                                         }
426                                 }
427                         }
428                         if ($r === false) {
429                                 notice(DI::l10n()->t('Failed to update contact record.'));
430                                 return;
431                         }
432
433                         $hash = Strings::getRandomHex() . (string) time();   // Generate a confirm_key
434
435                         if (is_array($contact_record)) {
436                                 q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
437                                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
438                                         intval($uid),
439                                         intval($contact_record['id']),
440                                         intval(!empty($_POST['knowyou'])),
441                                         DBA::escape(Strings::escapeTags(trim($_POST['dfrn-request-message'] ?? ''))),
442                                         DBA::escape($hash),
443                                         DBA::escape(DateTimeFormat::utcNow())
444                                 );
445                         }
446
447                         // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
448                         if (!$failed) {
449                                 info(DI::l10n()->t('Your introduction has been sent.'));
450                         }
451
452                         // "Homecoming" - send the requestor back to their site to record the introduction.
453                         $dfrn_url = bin2hex(DI::baseUrl()->get() . '/profile/' . $nickname);
454                         $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
455
456                         System::externalRedirect($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
457                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
458                                 . '&confirm_key=' . $hash
459                                 . (($aes_allow) ? "&aes_allow=1" : "")
460                         );
461                         // NOTREACHED
462                         // END $network === Protocol::DFRN
463                 } elseif (($network != Protocol::PHANTOM) && ($url != "")) {
464
465                         /* Substitute our user's feed URL into $url template
466                          * Send the subscriber home to subscribe
467                          */
468                         // Diaspora needs the uri in the format user@domain.tld
469                         // Diaspora will support the remote subscription in a future version
470                         if ($network == Protocol::DIASPORA) {
471                                 $uri = urlencode($a->profile['addr']);
472                         } else {
473                                 $uri = urlencode($a->profile['url']);
474                         }
475
476                         $url = str_replace('{uri}', $uri, $url);
477                         System::externalRedirect($url);
478                         // NOTREACHED
479                         // END $network != Protocol::PHANTOM
480                 } else {
481                         notice(DI::l10n()->t("Remote subscription can't be done for your network. Please subscribe directly on your system."));
482                         return;
483                 }
484         } return;
485 }
486
487 function dfrn_request_content(App $a)
488 {
489         if ($a->argc != 2 || empty($a->profile)) {
490                 return "";
491         }
492
493         // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
494         // to send us to the post section to record the introduction.
495         if (!empty($_GET['dfrn_url'])) {
496                 if (!local_user()) {
497                         info(DI::l10n()->t("Please login to confirm introduction."));
498                         /* setup the return URL to come back to this page if they use openid */
499                         return Login::form();
500                 }
501
502                 // Edge case, but can easily happen in the wild. This person is authenticated,
503                 // but not as the person who needs to deal with this request.
504                 if ($a->user['nickname'] != $a->argv[1]) {
505                         notice(DI::l10n()->t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile."));
506                         return Login::form();
507                 }
508
509                 $dfrn_url = Strings::escapeTags(trim(hex2bin($_GET['dfrn_url'])));
510                 $aes_allow = !empty($_GET['aes_allow']);
511                 $confirm_key = $_GET['confirm_key'] ?? '';
512
513                 // Checking fastlane for validity
514                 if (!empty($_SESSION['fastlane']) && (Strings::normaliseLink($_SESSION["fastlane"]) == Strings::normaliseLink($dfrn_url))) {
515                         $_POST["dfrn_url"] = $dfrn_url;
516                         $_POST["confirm_key"] = $confirm_key;
517                         $_POST["localconfirm"] = 1;
518                         $_POST["hidden-contact"] = 0;
519                         $_POST["submit"] = DI::l10n()->t('Confirm');
520
521                         dfrn_request_post($a);
522
523                         exit();
524                 }
525
526                 $tpl = Renderer::getMarkupTemplate("dfrn_req_confirm.tpl");
527                 $o = Renderer::replaceMacros($tpl, [
528                         '$dfrn_url' => $dfrn_url,
529                         '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
530                         '$hidethem' => DI::l10n()->t('Hide this contact'),
531                         '$confirm_key' => $confirm_key,
532                         '$welcome' => DI::l10n()->t('Welcome home %s.', $a->user['username']),
533                         '$please' => DI::l10n()->t('Please confirm your introduction/connection request to %s.', $dfrn_url),
534                         '$submit' => DI::l10n()->t('Confirm'),
535                         '$uid' => $_SESSION['uid'],
536                         '$nickname' => $a->user['nickname'],
537                         'dfrn_rawurl' => $_GET['dfrn_url']
538                 ]);
539                 return $o;
540         } elseif (!empty($_GET['confirm_key'])) {
541                 // we are the requestee and it is now safe to send our user their introduction,
542                 // We could just unblock it, but first we have to jump through a few hoops to
543                 // send an email, or even to find out if we need to send an email.
544                 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
545                         DBA::escape($_GET['confirm_key'])
546                 );
547
548                 if (DBA::isResult($intro)) {
549                         $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
550                                 WHERE `contact`.`id` = %d LIMIT 1",
551                                 intval($intro[0]['contact-id'])
552                         );
553
554                         $auto_confirm = false;
555
556                         if (DBA::isResult($r)) {
557                                 if ($r[0]['page-flags'] != User::PAGE_FLAGS_NORMAL && $r[0]['page-flags'] != User::PAGE_FLAGS_PRVGROUP) {
558                                         $auto_confirm = true;
559                                 }
560
561                                 if (!$auto_confirm) {
562                                         notification([
563                                                 'type'  => Type::INTRO,
564                                                 'otype' => Notify\ObjectType::INTRO,
565                                                 'verb'  => Activity::REQ_FRIEND,
566                                                 'uid'   => $r[0]['uid'],
567                                                 'cid'   => $r[0]['id'],
568                                                 'link'  => DI::baseUrl() . '/notifications/intros',
569                                         ]);
570                                 }
571
572                                 if ($auto_confirm) {
573                                         require_once 'mod/dfrn_confirm.php';
574                                         $handsfree = [
575                                                 'uid'      => $r[0]['uid'],
576                                                 'node'     => $r[0]['nickname'],
577                                                 'dfrn_id'  => $r[0]['issued-id'],
578                                                 'intro_id' => $intro[0]['id'],
579                                                 'duplex'   => (($r[0]['page-flags'] == User::PAGE_FLAGS_FREELOVE) ? 1 : 0),
580                                         ];
581                                         dfrn_confirm_post($a, $handsfree);
582                                 }
583                         }
584
585                         if (!$auto_confirm) {
586
587                                 // If we are auto_confirming, this record will have already been nuked
588                                 // in dfrn_confirm_post()
589
590                                 q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
591                                         DBA::escape($_GET['confirm_key'])
592                                 );
593                         }
594                 }
595
596                 exit();
597         } else {
598                 // Normal web request. Display our user's introduction form.
599                 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
600                         if (!DI::config()->get('system', 'local_block')) {
601                                 notice(DI::l10n()->t('Public access denied.'));
602                                 return;
603                         }
604                 }
605
606                 // Try to auto-fill the profile address
607                 // At first look if an address was provided
608                 // Otherwise take the local address
609                 if (!empty($_GET['addr'])) {
610                         $myaddr = hex2bin($_GET['addr']);
611                 } elseif (!empty($_GET['address'])) {
612                         $myaddr = $_GET['address'];
613                 } elseif (local_user()) {
614                         if (strlen(DI::baseUrl()->getUrlPath())) {
615                                 $myaddr = DI::baseUrl() . '/profile/' . $a->user['nickname'];
616                         } else {
617                                 $myaddr = $a->user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
618                         }
619                 } else {
620                         // last, try a zrl
621                         $myaddr = Profile::getMyURL();
622                 }
623
624                 $target_addr = $a->profile['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
625
626                 /* The auto_request form only has the profile address
627                  * because nobody is going to read the comments and
628                  * it doesn't matter if they know you or not.
629                  */
630                 if ($a->profile['page-flags'] == User::PAGE_FLAGS_NORMAL) {
631                         $tpl = Renderer::getMarkupTemplate('dfrn_request.tpl');
632                 } else {
633                         $tpl = Renderer::getMarkupTemplate('auto_request.tpl');
634                 }
635
636                 $o = Renderer::replaceMacros($tpl, [
637                         '$header'        => DI::l10n()->t('Friend/Connection Request'),
638                         '$page_desc'     => DI::l10n()->t('Enter your Webfinger address (user@domain.tld) or profile URL here. If this isn\'t supported by your system (for example it doesn\'t work with Diaspora), you have to subscribe to <strong>%s</strong> directly on your system', $target_addr),
639                         '$invite_desc'   => DI::l10n()->t('If you are not yet a member of the free social web, <a href="%s">follow this link to find a public Friendica node and join us today</a>.', Search::getGlobalDirectory() . '/servers'),
640                         '$your_address'  => DI::l10n()->t('Your Webfinger address or profile URL:'),
641                         '$pls_answer'    => DI::l10n()->t('Please answer the following:'),
642                         '$submit'        => DI::l10n()->t('Submit Request'),
643                         '$cancel'        => DI::l10n()->t('Cancel'),
644
645                         '$request'       => 'dfrn_request/' . $a->argv[1],
646                         '$name'          => $a->profile['name'],
647                         '$myaddr'        => $myaddr,
648
649                         '$does_know_you' => ['knowyou', DI::l10n()->t('%s knows you', $a->profile['name'])],
650                         '$addnote_field' => ['dfrn-request-message', DI::l10n()->t('Add a personal note:')],
651                 ]);
652                 return $o;
653         }
654 }