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