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