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