]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_request.php
Merge pull request #2564 from annando/1606-contact-handling
[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 require_once('include/group.php');
15
16 if(! function_exists('dfrn_request_init')) {
17 function dfrn_request_init(&$a) {
18
19         if($a->argc > 1)
20                 $which = $a->argv[1];
21
22         profile_load($a,$which);
23         return;
24 }}
25
26
27 /**
28  * Function: dfrn_request_post
29  *
30  * Purpose:
31  * Handles multiple scenarios.
32  *
33  * Scenario 1:
34  * Clicking 'submit' on a friend request page.
35  *
36  * Scenario 2:
37  * Following Scenario 1, we are brought back to our home site
38  * in order to link our friend request with our own server cell.
39  * After logging in, we click 'submit' to approve the linkage.
40  *
41  */
42
43 if(! function_exists('dfrn_request_post')) {
44 function dfrn_request_post(&$a) {
45
46         if(($a->argc != 2) || (! count($a->profile))) {
47                 logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
48                 return;
49         }
50
51
52         if(x($_POST, 'cancel')) {
53                 goaway(z_root());
54         }
55
56
57         /**
58          *
59          * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
60          * to confirm the request, and then we've clicked submit (perhaps after logging in).
61          * That brings us here:
62          *
63          */
64
65         if((x($_POST,'localconfirm')) && ($_POST['localconfirm'] == 1)) {
66
67                 /**
68                  * Ensure this is a valid request
69                  */
70
71                 if(local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST,'dfrn_url'))) {
72
73
74                         $dfrn_url    = notags(trim($_POST['dfrn_url']));
75                         $aes_allow   = (((x($_POST,'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
76                         $confirm_key = ((x($_POST,'confirm_key')) ? $_POST['confirm_key'] : "");
77                         $hidden = ((x($_POST,'hidden-contact')) ? intval($_POST['hidden-contact']) : 0);
78                         $contact_record = null;
79
80                         if(x($dfrn_url)) {
81
82                                 /**
83                                  * Lookup the contact based on their URL (which is the only unique thing we have at the moment)
84                                  */
85
86                                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND (`url` = '%s' OR `nurl` = '%s') AND `self` = 0 LIMIT 1",
87                                         intval(local_user()),
88                                         dbesc($dfrn_url),
89                                         dbesc(normalise_link($dfrn_url))
90                                 );
91
92                                 if(count($r)) {
93                                         if(strlen($r[0]['dfrn-id'])) {
94
95                                                 /**
96                                                  * We don't need to be here. It has already happened.
97                                                  */
98
99                                                 notice( t("This introduction has already been accepted.") . EOL );
100                                                 return;
101                                         }
102                                         else
103                                                 $contact_record = $r[0];
104                                 }
105
106                                 if(is_array($contact_record)) {
107                                         $r = q("UPDATE `contact` SET `ret-aes` = %d, hidden = %d WHERE `id` = %d",
108                                                 intval($aes_allow),
109                                                 intval($hidden),
110                                                 intval($contact_record['id'])
111                                         );
112                                 }
113                                 else {
114
115                                         /**
116                                          * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
117                                          */
118
119                                         $parms = scrape_dfrn($dfrn_url);
120
121                                         if(! count($parms)) {
122                                                 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
123                                                 return;
124                                         }
125                                         else {
126                                                 if(! x($parms,'fn'))
127                                                         notice( t('Warning: profile location has no identifiable owner name.') . EOL );
128                                                 if(! x($parms,'photo'))
129                                                         notice( t('Warning: profile location has no profile photo.') . EOL );
130                                                 $invalid = validate_dfrn($parms);
131                                                 if($invalid) {
132                                                         notice( sprintf( tt("%d required parameter was not found at the given location",
133                                                                                                 "%d required parameters were not found at the given location",
134                                                                                                 $invalid), $invalid) . EOL );
135                                                         return;
136                                                 }
137                                         }
138
139                                         $dfrn_request = $parms['dfrn-request'];
140
141                                         /********* Escape the entire array ********/
142
143                                         dbesc_array($parms);
144
145                                         /******************************************/
146
147                                         /**
148                                          * Create a contact record on our site for the other person
149                                          */
150
151                                         $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `addr`, `name`, `nick`, `photo`, `site-pubkey`,
152                                                 `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`, `hidden`)
153                                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
154                                                 intval(local_user()),
155                                                 datetime_convert(),
156                                                 dbesc($dfrn_url),
157                                                 dbesc(normalise_link($dfrn_url)),
158                                                 $parms['addr'],
159                                                 $parms['fn'],
160                                                 $parms['nick'],
161                                                 $parms['photo'],
162                                                 $parms['key'],
163                                                 $parms['dfrn-request'],
164                                                 $parms['dfrn-confirm'],
165                                                 $parms['dfrn-notify'],
166                                                 $parms['dfrn-poll'],
167                                                 $parms['dfrn-poco'],
168                                                 dbesc(NETWORK_DFRN),
169                                                 intval($aes_allow),
170                                                 intval($hidden)
171                                         );
172                                 }
173
174                                 if($r) {
175                                         info( t("Introduction complete.") . EOL);
176                                 }
177
178                                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `site-pubkey` = '%s' LIMIT 1",
179                                         intval(local_user()),
180                                         dbesc($dfrn_url),
181                                         $parms['key'] // this was already escaped
182                                 );
183                                 if(count($r)) {
184                                         $def_gid = get_default_group(local_user(), $r[0]["network"]);
185                                         if(intval($def_gid))
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                                         group_add_member($uid, '', $contact_id, $def_gid);
399
400                                 $photo = avatar_img($addr);
401
402                                 $r = q("UPDATE `contact` SET
403                                         `photo` = '%s',
404                                         `thumb` = '%s',
405                                         `micro` = '%s',
406                                         `name-date` = '%s',
407                                         `uri-date` = '%s',
408                                         `avatar-date` = '%s',
409                                         `hidden` = 0,
410                                         WHERE `id` = %d
411                                 ",
412                                         dbesc($photos[0]),
413                                         dbesc($photos[1]),
414                                         dbesc($photos[2]),
415                                         dbesc(datetime_convert()),
416                                         dbesc(datetime_convert()),
417                                         dbesc(datetime_convert()),
418                                         intval($contact_id)
419                                 );
420                         }
421
422                         // contact is created. Now create an introduction
423
424                         $hash = random_string();
425
426                         $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
427                                 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
428                                 intval($uid),
429                                 intval($contact_id),
430                                 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
431                                 dbesc(notags(trim($_POST['dfrn-request-message']))),
432                                 dbesc($hash),
433                                 dbesc(datetime_convert()),
434                                 1
435                         );
436
437                         // Next send an email verify form to the requestor.
438
439                 } else {
440                         // Detect the network
441                         $data = probe_url($url);
442                         $network = $data["network"];
443
444                         // Canonicalise email-style profile locator
445                         $url = webfinger_dfrn($url,$hcard);
446
447                         if (substr($url,0,5) === 'stat:') {
448
449                                 // Every time we detect the remote subscription we define this as OStatus.
450                                 // We do this even if it is not OStatus.
451                                 // we only need to pass this through another section of the code.
452                                 if ($network != NETWORK_DIASPORA)
453                                         $network = NETWORK_OSTATUS;
454
455                                 $url = substr($url,5);
456                         } else
457                                 $network = NETWORK_DFRN;
458                 }
459
460                 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
461
462                 if($network === NETWORK_DFRN) {
463                         $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
464                                 intval($uid),
465                                 dbesc($url)
466                         );
467
468                         if(count($ret)) {
469                                 if(strlen($ret[0]['issued-id'])) {
470                                         notice( t('You have already introduced yourself here.') . EOL );
471                                         return;
472                                 }
473                                 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
474                                         notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
475                                         return;
476                                 }
477                                 else {
478                                         $contact_record = $ret[0];
479                                         $parms = array('dfrn-request' => $ret[0]['request']);
480                                 }
481                         }
482
483                         $issued_id = random_string();
484
485                         if(is_array($contact_record)) {
486                                 // There is a contact record but no issued-id, so this
487                                 // is a reciprocal introduction from a known contact
488                                 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
489                                         dbesc($issued_id),
490                                         intval($contact_record['id'])
491                                 );
492                         }
493                         else {
494                                 if(! validate_url($url)) {
495                                         notice( t('Invalid profile URL.') . EOL);
496                                         goaway($a->get_baseurl() . '/' . $a->cmd);
497                                         return; // NOTREACHED
498                                 }
499
500                                 if(! allowed_url($url)) {
501                                         notice( t('Disallowed profile URL.') . EOL);
502                                         goaway($a->get_baseurl() . '/' . $a->cmd);
503                                         return; // NOTREACHED
504                                 }
505
506
507                                 require_once('include/Scrape.php');
508
509                                 $parms = scrape_dfrn(($hcard) ? $hcard : $url);
510
511                                 if(! count($parms)) {
512                                         notice( t('Profile location is not valid or does not contain profile information.') . EOL );
513                                         goaway($a->get_baseurl() . '/' . $a->cmd);
514                                 }
515                                 else {
516                                         if(! x($parms,'fn'))
517                                                 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
518                                         if(! x($parms,'photo'))
519                                                 notice( t('Warning: profile location has no profile photo.') . EOL );
520                                         $invalid = validate_dfrn($parms);
521                                         if($invalid) {
522                                                 notice( sprintf( tt("%d required parameter was not found at the given location",
523                                                                                         "%d required parameters were not found at the given location",
524                                                                                         $invalid), $invalid) . EOL );
525
526                                                 return;
527                                         }
528                                 }
529
530
531                                 $parms['url'] = $url;
532                                 $parms['issued-id'] = $issued_id;
533
534
535                                 dbesc_array($parms);
536                                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
537                                         `request`, `confirm`, `notify`, `poll`, `poco`, `network` )
538                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
539                                         intval($uid),
540                                         dbesc(datetime_convert()),
541                                         $parms['url'],
542                                         dbesc(normalise_link($parms['url'])),
543                                         $parms['addr'],
544                                         $parms['fn'],
545                                         $parms['nick'],
546                                         $parms['issued-id'],
547                                         $parms['photo'],
548                                         $parms['key'],
549                                         $parms['dfrn-request'],
550                                         $parms['dfrn-confirm'],
551                                         $parms['dfrn-notify'],
552                                         $parms['dfrn-poll'],
553                                         $parms['dfrn-poco'],
554                                         dbesc(NETWORK_DFRN)
555                                 );
556
557                                 // find the contact record we just created
558                                 if($r) {
559                                         $r = q("SELECT `id` FROM `contact`
560                                                 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
561                                                 intval($uid),
562                                                 $parms['url'],
563                                                 $parms['issued-id']
564                                         );
565                                         if(count($r))
566                                                 $contact_record = $r[0];
567                                 }
568
569                         }
570                         if($r === false) {
571                                 notice( t('Failed to update contact record.') . EOL );
572                                 return;
573                         }
574
575                         $hash = random_string() . (string) time();   // Generate a confirm_key
576
577                         if(is_array($contact_record)) {
578                                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
579                                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
580                                         intval($uid),
581                                         intval($contact_record['id']),
582                                         ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
583                                         dbesc(notags(trim($_POST['dfrn-request-message']))),
584                                         dbesc($hash),
585                                         dbesc(datetime_convert())
586                                 );
587                         }
588
589                         // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
590
591                         if(! $failed)
592                                 info( t('Your introduction has been sent.') . EOL );
593
594                         // "Homecoming" - send the requestor back to their site to record the introduction.
595
596                         $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
597                         $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
598
599                         goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
600                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
601                                 . '&confirm_key='  . $hash
602                                 . (($aes_allow) ? "&aes_allow=1" : "")
603                         );
604                         // NOTREACHED
605                         // END $network === NETWORK_DFRN
606                 } elseif (($network != NETWORK_PHANTOM) AND ($url != "")) {
607
608                         /**
609                          *
610                          * Substitute our user's feed URL into $url template
611                          * Send the subscriber home to subscribe
612                          *
613                          */
614
615                         // Diaspora needs the uri in the format user@domain.tld
616                         // Diaspora will support the remote subscription in a future version
617                         if ($network == NETWORK_DIASPORA) {
618                                 $uri = $nickname.'@'.$a->get_hostname();
619
620                                 if ($a->get_path())
621                                         $uri .= '/'.$a->get_path();
622
623                                 $uri = urlencode($uri);
624                         } else
625                                 $uri = $a->get_baseurl().'/profile/'.$nickname;
626
627                         $url = str_replace('{uri}', $uri, $url);
628                         goaway($url);
629                         // NOTREACHED
630                         // END $network != NETWORK_PHANTOM
631                 } else {
632                         notice(t("Remote subscription can't be done for your network. Please subscribe directly on your system.").EOL);
633                         return;
634                 }
635
636         }       return;
637 }}
638
639
640
641
642 if(! function_exists('dfrn_request_content')) {
643 function dfrn_request_content(&$a) {
644
645         if(($a->argc != 2) || (! count($a->profile)))
646                 return "";
647
648
649         // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
650         // to send us to the post section to record the introduction.
651
652         if(x($_GET,'dfrn_url')) {
653
654                 if(! local_user()) {
655                         info( t("Please login to confirm introduction.") . EOL );
656                         /* setup the return URL to come back to this page if they use openid */
657                         $_SESSION['return_url'] = $a->query_string;
658                         return login();
659                 }
660
661                 // Edge case, but can easily happen in the wild. This person is authenticated,
662                 // but not as the person who needs to deal with this request.
663
664                 if ($a->user['nickname'] != $a->argv[1]) {
665                         notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
666                         return login();
667                 }
668
669                 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
670                 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
671                 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
672
673                 // Checking fastlane for validity
674                 if (x($_SESSION, "fastlane") AND (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
675                         $_POST["dfrn_url"] = $dfrn_url;
676                         $_POST["confirm_key"] = $confirm_key;
677                         $_POST["localconfirm"] = 1;
678                         $_POST["hidden-contact"] = 0;
679                         $_POST["submit"] = t('Confirm');
680
681                         dfrn_request_post($a);
682
683                         killme();
684                         return; // NOTREACHED
685                 }
686
687                 $tpl = get_markup_template("dfrn_req_confirm.tpl");
688                 $o  = replace_macros($tpl,array(
689                         '$dfrn_url' => $dfrn_url,
690                         '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
691                         '$hidethem' => t('Hide this contact'),
692                         '$hidechecked' => '',
693                         '$confirm_key' => $confirm_key,
694                         '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
695                         '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
696                         '$submit' => t('Confirm'),
697                         '$uid' => $_SESSION['uid'],
698                         '$nickname' => $a->user['nickname'],
699                         'dfrn_rawurl' => $_GET['dfrn_url']
700                         ));
701                 return $o;
702
703         }
704         elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
705
706                 // we are the requestee and it is now safe to send our user their introduction,
707                 // We could just unblock it, but first we have to jump through a few hoops to
708                 // send an email, or even to find out if we need to send an email.
709
710                 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
711                         dbesc($_GET['confirm_key'])
712                 );
713
714                 if(count($intro)) {
715
716                         $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
717                                 WHERE `contact`.`id` = %d LIMIT 1",
718                                 intval($intro[0]['contact-id'])
719                         );
720
721                         $auto_confirm = false;
722
723                         if(count($r)) {
724                                 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
725                                         $auto_confirm = true;
726
727                                 if(! $auto_confirm) {
728
729                                         notification(array(
730                                                 'type'         => NOTIFY_INTRO,
731                                                 'notify_flags' => $r[0]['notify-flags'],
732                                                 'language'     => $r[0]['language'],
733                                                 'to_name'      => $r[0]['username'],
734                                                 'to_email'     => $r[0]['email'],
735                                                 'uid'          => $r[0]['uid'],
736                                                 'link'             => $a->get_baseurl() . '/notifications/intros',
737                                                 'source_name'  => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
738                                                 'source_link'  => $r[0]['url'],
739                                                 'source_photo' => $r[0]['photo'],
740                                                 'verb'         => ACTIVITY_REQ_FRIEND,
741                                                 'otype'        => 'intro'
742                                         ));
743                                 }
744
745                                 if($auto_confirm) {
746                                         require_once('mod/dfrn_confirm.php');
747                                         $handsfree = array(
748                                                 'uid' => $r[0]['uid'],
749                                                 'node' => $r[0]['nickname'],
750                                                 'dfrn_id' => $r[0]['issued-id'],
751                                                 'intro_id' => $intro[0]['id'],
752                                                 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
753                                                 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
754                                         );
755                                         dfrn_confirm_post($a,$handsfree);
756                                 }
757
758                         }
759
760                         if(! $auto_confirm) {
761
762                                 // If we are auto_confirming, this record will have already been nuked
763                                 // in dfrn_confirm_post()
764
765                                 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
766                                         dbesc($_GET['confirm_key'])
767                                 );
768                         }
769                 }
770
771                 killme();
772                 return; // NOTREACHED
773         }
774         else {
775
776                 /**
777                  * Normal web request. Display our user's introduction form.
778                  */
779
780                 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
781                         if(! get_config('system','local_block')) {
782                                 notice( t('Public access denied.') . EOL);
783                                 return;
784                         }
785                 }
786
787
788                 /**
789                  * Try to auto-fill the profile address
790                  */
791
792                 // At first look if an address was provided
793                 // Otherwise take the local address
794                 if (x($_GET,'addr') AND ($_GET['addr'] != ""))
795                         $myaddr = hex2bin($_GET['addr']);
796                 elseif (x($_GET,'address') AND ($_GET['address'] != ""))
797                         $myaddr = $_GET['address'];
798                 elseif(local_user()) {
799                         if(strlen($a->path)) {
800                                 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
801                         }
802                         else {
803                                 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
804                         }
805                 } else  // last, try a zrl
806                         $myaddr = get_my_url();
807
808                 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
809
810
811                 /**
812                  *
813                  * The auto_request form only has the profile address
814                  * because nobody is going to read the comments and
815                  * it doesn't matter if they know you or not.
816                  *
817                  */
818
819                 if($a->profile['page-flags'] == PAGE_NORMAL)
820                         $tpl = get_markup_template('dfrn_request.tpl');
821                 else
822                         $tpl = get_markup_template('auto_request.tpl');
823
824                 $page_desc = t("Please enter your 'Identity Address' from one of the following supported communications networks:");
825
826                 // see if we are allowed to have NETWORK_MAIL2 contacts
827
828                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
829                 if(get_config('system','dfrn_only'))
830                         $mail_disabled = 1;
831
832                 if(! $mail_disabled) {
833                         $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
834                                 intval($a->profile['uid'])
835                         );
836                         if(! count($r))
837                                 $mail_disabled = 1;
838                 }
839
840                 // "coming soon" is disabled for now
841                 //$emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
842                 $emailnet = "";
843
844                 $invite_desc = sprintf(
845                         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>.'),
846                         get_server()
847                 );
848
849                 $o = replace_macros($tpl,array(
850                         '$header' => t('Friend/Connection Request'),
851                         '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
852                         '$pls_answer' => t('Please answer the following:'),
853                         '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'),$a->profile['name']), false, '', array(t('No'),t('Yes'))),
854                         /*'$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
855                         '$yes' => t('Yes'),
856                         '$no' => t('No'), */
857                         '$add_note' => t('Add a personal note:'),
858                         '$page_desc' => $page_desc,
859                         '$friendica' => t('Friendica'),
860                         '$statusnet' => t('StatusNet/Federated Social Web'),
861                         '$diaspora' => t('Diaspora'),
862                         '$diasnote' => sprintf (t(' - please do not use this form.  Instead, enter %s into your Diaspora search bar.'),$target_addr),
863                         '$your_address' => t('Your Identity Address:'),
864                         '$invite_desc' => $invite_desc,
865                         '$emailnet' => $emailnet,
866                         '$submit' => t('Submit Request'),
867                         '$cancel' => t('Cancel'),
868                         '$nickname' => $a->argv[1],
869                         '$name' => $a->profile['name'],
870                         '$myaddr' => $myaddr
871                 ));
872                 return $o;
873         }
874
875         return; // Somebody is fishing.
876 }}