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