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