]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_request.php
rev update
[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 LIMIT 1",
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('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 LIMIT 1",
287                                                 intval($rr['cid'])
288                                         );
289                                 }
290                                 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
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 LIMIT 1",
312                                                 intval($rr['cid'])
313                                         );
314                                 }
315                                 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
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                                         notice( t('This account has not been configured for email. Request failed.') . EOL);
362                                         return;
363                                 }
364                         }
365
366                         $r = q("insert into contact ( uid, created, addr, name, nick, url, nurl, poll, notify, blocked, pending, network, rel )
367                                 values( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d ) ",
368                                 intval($uid),
369                                 dbesc(datetime_convert()),
370                                 dbesc($addr),
371                                 dbesc($name),
372                                 dbesc($nick),
373                                 dbesc($url),
374                                 dbesc($nurl),
375                                 dbesc($poll),
376                                 dbesc($notify),
377                                 intval($blocked),
378                                 intval($pending),
379                                 dbesc($network),
380                                 intval($rel)
381                         );
382
383                         $r = q("select id from contact where poll = '%s' and uid = %d limit 1",
384                                 dbesc($poll),
385                                 intval($uid)
386                         );
387                         if(count($r)) {
388                                 $contact_id = $r[0]['id'];
389
390                                 $g = q("select def_gid from user where uid = %d limit 1",
391                                         intval($uid)
392                                 );
393                                 if($g && intval($g[0]['def_gid'])) {
394                                         require_once('include/group.php');
395                                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
396                                 }
397
398                                 $photo = avatar_img($addr);
399
400                                 $r = q("UPDATE `contact` SET 
401                                         `photo` = '%s', 
402                                         `thumb` = '%s',
403                                         `micro` = '%s', 
404                                         `name-date` = '%s', 
405                                         `uri-date` = '%s', 
406                                         `avatar-date` = '%s', 
407                                         `hidden` = 0,
408                                         WHERE `id` = %d LIMIT 1
409                                 ",
410                                         dbesc($photos[0]),
411                                         dbesc($photos[1]),
412                                         dbesc($photos[2]),
413                                         dbesc(datetime_convert()),
414                                         dbesc(datetime_convert()),
415                                         dbesc(datetime_convert()),
416                                         intval($contact_id)
417                                 );
418                         }
419
420                         // contact is created. Now create an introduction
421
422                         $hash = random_string();
423
424                         $r = q("insert into intro ( uid, `contact-id`, knowyou, note, hash, datetime, blocked )
425                                 values( %d , %d, %d, '%s', '%s', '%s', %d ) ",
426                                 intval($uid),
427                                 intval($contact_id),
428                                 ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
429                                 dbesc(notags(trim($_POST['dfrn-request-message']))),
430                                 dbesc($hash),
431                                 dbesc(datetime_convert()),
432                                 1
433                         );
434                                 
435                         // Next send an email verify form to the requestor.
436
437                 }
438
439                 else {
440
441                         // Canonicalise email-style profile locator
442
443                         $url = webfinger_dfrn($url,$hcard);
444
445                         if(substr($url,0,5) === 'stat:') {
446                                 $network = NETWORK_OSTATUS;
447                                 $url = substr($url,5);
448                         }
449                         else {
450                                 $network = NETWORK_DFRN;
451                         }
452                 }
453
454                 logger('dfrn_request: url: ' . $url);
455
456                 if(! strlen($url)) {
457                         notice( t("Unable to resolve your name at the provided location.") . EOL);                      
458                         return;
459                 }
460
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 LIMIT 1",
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('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`,`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' )",
539                                         intval($uid),
540                                         dbesc(datetime_convert()),
541                                         $parms['url'],
542                                         dbesc(normalise_link($parms['url'])),
543                                         $parms['fn'],
544                                         $parms['nick'],
545                                         $parms['issued-id'],
546                                         $parms['photo'],
547                                         $parms['key'],
548                                         $parms['dfrn-request'],
549                                         $parms['dfrn-confirm'],
550                                         $parms['dfrn-notify'],
551                                         $parms['dfrn-poll'],
552                                         $parms['dfrn-poco'],
553                                         dbesc(NETWORK_DFRN)
554                                 );
555
556                                 // find the contact record we just created
557                                 if($r) {        
558                                         $r = q("SELECT `id` FROM `contact` 
559                                                 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
560                                                 intval($uid),
561                                                 $parms['url'],
562                                                 $parms['issued-id']
563                                         );
564                                         if(count($r)) 
565                                                 $contact_record = $r[0];
566                                 }
567         
568                         }
569                         if($r === false) {
570                                 notice( t('Failed to update contact record.') . EOL );
571                                 return;
572                         }
573
574                         $hash = random_string() . (string) time();   // Generate a confirm_key
575         
576                         if(is_array($contact_record)) {
577                                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
578                                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
579                                         intval($uid),
580                                         intval($contact_record['id']),
581                                         ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
582                                         dbesc(notags(trim($_POST['dfrn-request-message']))),
583                                         dbesc($hash),
584                                         dbesc(datetime_convert())
585                                 );
586                         }
587         
588                         // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
589
590                         if(! $failed) 
591                                 info( t('Your introduction has been sent.') . EOL );
592
593                         // "Homecoming" - send the requestor back to their site to record the introduction.
594
595                         $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
596                         $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
597
598                         goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url" 
599                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION 
600                                 . '&confirm_key='  . $hash 
601                                 . (($aes_allow) ? "&aes_allow=1" : "")
602                         );
603                         // NOTREACHED
604                         // END $network === NETWORK_DFRN
605                 }
606                 elseif($network === NETWORK_OSTATUS) {
607                         
608                         /**
609                          *
610                          * OStatus network
611                          * Check contact existence
612                          * Try and scrape together enough information to create a contact record, 
613                          * with us as CONTACT_IS_FOLLOWER
614                          * Substitute our user's feed URL into $url template
615                          * Send the subscriber home to subscribe
616                          *
617                          */
618
619                         $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url);
620                         goaway($url);
621                         // NOTREACHED
622                         // END $network === NETWORK_OSTATUS
623                 }
624
625         }       return;
626 }}
627
628
629
630
631 if(! function_exists('dfrn_request_content')) {
632 function dfrn_request_content(&$a) {
633
634         if(($a->argc != 2) || (! count($a->profile)))
635                 return "";
636
637
638         // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
639         // to send us to the post section to record the introduction.
640
641         if(x($_GET,'dfrn_url')) {
642
643                 if(! local_user()) {
644                         info( t("Please login to confirm introduction.") . EOL );
645
646                         /* setup the return URL to come back to this page if they use openid */
647
648                         $stripped = str_replace('q=','',$a->query_string);
649                         $_SESSION['return_url'] = trim($stripped,'/');
650
651                         return login();
652                 }
653
654                 // Edge case, but can easily happen in the wild. This person is authenticated, 
655                 // but not as the person who needs to deal with this request.
656
657                 if ($a->user['nickname'] != $a->argv[1]) {
658                         notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
659                         return login();
660                 }
661
662                 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
663                 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
664                 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
665                 $tpl = get_markup_template("dfrn_req_confirm.tpl");
666                 $o  = replace_macros($tpl,array(
667                         '$dfrn_url' => $dfrn_url,
668                         '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
669                         '$hidethem' => t('Hide this contact'),
670                         '$hidechecked' => '',
671                         '$confirm_key' => $confirm_key,
672                         '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
673                         '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
674                         '$submit' => t('Confirm'),
675                         '$uid' => $_SESSION['uid'],
676                         '$nickname' => $a->user['nickname'],
677                         'dfrn_rawurl' => $_GET['dfrn_url']
678                         ));
679                 return $o;
680
681         }
682         elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) { 
683
684                 // we are the requestee and it is now safe to send our user their introduction,
685                 // We could just unblock it, but first we have to jump through a few hoops to 
686                 // send an email, or even to find out if we need to send an email. 
687
688                 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
689                         dbesc($_GET['confirm_key'])
690                 );
691
692                 if(count($intro)) {
693
694                         $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
695                                 WHERE `contact`.`id` = %d LIMIT 1",
696                                 intval($intro[0]['contact-id'])
697                         );
698
699                         $auto_confirm = false;
700
701                         if(count($r)) {
702                                 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
703                                         $auto_confirm = true;                           
704
705                                 if(! $auto_confirm) {
706                                         require_once('include/enotify.php');
707                                         notification(array(
708                                                 'type'         => NOTIFY_INTRO,
709                                                 'notify_flags' => $r[0]['notify-flags'],
710                                                 'language'     => $r[0]['language'],
711                                                 'to_name'      => $r[0]['username'],
712                                                 'to_email'     => $r[0]['email'],
713                                                 'uid'          => $r[0]['uid'],
714                                                 'link'             => $a->get_baseurl() . '/notifications/intros',
715                                                 'source_name'  => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
716                                                 'source_link'  => $r[0]['url'],
717                                                 'source_photo' => $r[0]['photo'],
718                                                 'verb'         => ACTIVITY_REQ_FRIEND,
719                                                 'otype'        => 'intro'
720                                         ));
721                                 }
722
723                                 if($auto_confirm) {
724                                         require_once('mod/dfrn_confirm.php');
725                                         $handsfree = array(
726                                                 'uid' => $r[0]['uid'],
727                                                 'node' => $r[0]['nickname'],
728                                                 'dfrn_id' => $r[0]['issued-id'],
729                                                 'intro_id' => $intro[0]['id'],
730                                                 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
731                                                 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
732                                         );
733                                         dfrn_confirm_post($a,$handsfree);
734                                 }
735
736                         }
737
738                         if(! $auto_confirm) {
739
740                                 // If we are auto_confirming, this record will have already been nuked
741                                 // in dfrn_confirm_post()
742
743                                 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s' LIMIT 1",
744                                         dbesc($_GET['confirm_key'])
745                                 );
746                         }
747                 }
748
749                 killme();
750                 return; // NOTREACHED
751         }
752         else {
753
754                 /**
755                  * Normal web request. Display our user's introduction form.
756                  */
757  
758                 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
759                         if(! get_config('system','local_block')) {
760                                 notice( t('Public access denied.') . EOL);
761                                 return;
762                         }
763                 }
764
765
766                 /**
767                  * Try to auto-fill the profile address
768                  */
769
770                 if(local_user()) {
771                         if(strlen($a->path)) {
772                                 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
773                         }
774                         else {
775                                 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
776                         }
777                 }
778                 elseif(x($_GET,'addr')) {
779                         $myaddr = hex2bin($_GET['addr']);
780                 }
781                 else {
782                         /* $_GET variables are already urldecoded */ 
783                         $myaddr = ((x($_GET,'address')) ? $_GET['address'] : '');
784                 }
785
786                 // last, try a zrl
787                 if(! strlen($myaddr))
788                         $myaddr = get_my_url();
789
790
791                 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
792
793
794                 /**
795                  *
796                  * The auto_request form only has the profile address
797                  * because nobody is going to read the comments and 
798                  * it doesn't matter if they know you or not.
799                  *
800                  */
801
802                 if($a->profile['page-flags'] == PAGE_NORMAL)
803                         $tpl = get_markup_template('dfrn_request.tpl');
804                 else
805                         $tpl = get_markup_template('auto_request.tpl');
806
807         #       $page_desc = sprintf( t('Diaspora members: Please do not use this form. Instead, enter "%s" into your Diaspora search bar.'), 
808         #               $target_addr) . EOL . EOL;
809
810                 $page_desc .= t("Please enter your 'Identity Address' from one of the following supported communications networks:");
811
812                 // see if we are allowed to have NETWORK_MAIL2 contacts
813
814                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
815                 if(get_config('system','dfrn_only'))
816                         $mail_disabled = 1;
817
818                 if(! $mail_disabled) {
819                         $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
820                                 intval($a->profile['uid'])
821                         );
822                         if(! count($r))
823                                 $mail_disabled = 1;
824                 }
825
826                 $emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
827
828                 $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>.');
829
830                 $o .= replace_macros($tpl,array(
831                         '$header' => t('Friend/Connection Request'),
832                         '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
833                         '$pls_answer' => t('Please answer the following:'),
834                         '$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
835                         '$yes' => t('Yes'),
836                         '$no' => t('No'),
837                         '$add_note' => t('Add a personal note:'),
838                         '$page_desc' => $page_desc,
839                         '$friendica' => t('Friendica'),
840                         '$statusnet' => t('StatusNet/Federated Social Web'),
841                         '$diaspora' => t('Diaspora'),
842                         '$diasnote' => sprintf (t(' - please do not use this form.  Instead, enter %s into your Diaspora search bar.'),$target_addr),
843                         '$your_address' => t('Your Identity Address:'),
844                         '$invite_desc' => $invite_desc,
845                         '$emailnet' => $emailnet,
846                         '$submit' => t('Submit Request'),
847                         '$cancel' => t('Cancel'),
848                         '$nickname' => $a->argv[1],
849                         '$name' => $a->profile['name'],
850                         '$myaddr' => $myaddr
851                 ));
852                 return $o;
853         }
854
855         return; // Somebody is fishing.
856 }}