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