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