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