]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_request.php
Merge branch 'rewrites/dbm_is_result' of github.com:Quix0r/friendica into rewrites...
[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 = $a->get_baseurl()."/contacts/".$r[0]['id'];
197                                 } else
198                                         $forwardurl = $a->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                         logger('dfrn_request: url=' . $url . ',network=' . $network . ',hcard=' . $hcard . ' - BEFORE!', LOGGER_DEBUG);
453
454                         // Canonicalise email-style profile locator
455                         $url = Probe::webfinger_dfrn($url,$hcard);
456
457                         logger('dfrn_request: url=' . $url . ',network=' . $network . ',hcard=' . $hcard . ' - AFTER!', LOGGER_DEBUG);
458
459                         if (substr($url,0,5) === 'stat:') {
460
461                                 // Every time we detect the remote subscription we define this as OStatus.
462                                 // We do this even if it is not OStatus.
463                                 // we only need to pass this through another section of the code.
464                                 if ($network != NETWORK_DIASPORA)
465                                         $network = NETWORK_OSTATUS;
466
467                                 $url = substr($url,5);
468                         } else
469                                 $network = NETWORK_DFRN;
470                 }
471
472                 logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG);
473
474                 if($network === NETWORK_DFRN) {
475                         $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
476                                 intval($uid),
477                                 dbesc($url)
478                         );
479
480                         if(dbm::is_result($ret)) {
481                                 if(strlen($ret[0]['issued-id'])) {
482                                         notice( t('You have already introduced yourself here.') . EOL );
483                                         return;
484                                 }
485                                 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
486                                         notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
487                                         return;
488                                 }
489                                 else {
490                                         $contact_record = $ret[0];
491                                         $parms = array('dfrn-request' => $ret[0]['request']);
492                                 }
493                         }
494
495                         $issued_id = random_string();
496
497                         if(is_array($contact_record)) {
498                                 // There is a contact record but no issued-id, so this
499                                 // is a reciprocal introduction from a known contact
500                                 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d",
501                                         dbesc($issued_id),
502                                         intval($contact_record['id'])
503                                 );
504                         }
505                         else {
506                                 if(! validate_url($url)) {
507                                         notice( t('Invalid profile URL.') . EOL);
508                                         goaway($a->get_baseurl() . '/' . $a->cmd);
509                                         return; // NOTREACHED
510                                 }
511
512                                 if(! allowed_url($url)) {
513                                         notice( t('Disallowed profile URL.') . EOL);
514                                         goaway($a->get_baseurl() . '/' . $a->cmd);
515                                         return; // NOTREACHED
516                                 }
517
518
519                                 require_once('include/Scrape.php');
520
521                                 $parms = Probe::profile(($hcard) ? $hcard : $url);
522
523                                 if(! count($parms)) {
524                                         notice( t('Profile location is not valid or does not contain profile information.') . EOL );
525                                         goaway($a->get_baseurl() . '/' . $a->cmd);
526                                 }
527                                 else {
528                                         if(! x($parms,'fn'))
529                                                 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
530                                         if(! x($parms,'photo'))
531                                                 notice( t('Warning: profile location has no profile photo.') . EOL );
532                                         $invalid = Probe::valid_dfrn($parms);
533                                         if($invalid) {
534                                                 notice( sprintf( tt("%d required parameter was not found at the given location",
535                                                                                         "%d required parameters were not found at the given location",
536                                                                                         $invalid), $invalid) . EOL );
537
538                                                 return;
539                                         }
540                                 }
541
542
543                                 $parms['url'] = $url;
544                                 $parms['issued-id'] = $issued_id;
545                                 $photo = $parms["photo"];
546
547                                 dbesc_array($parms);
548                                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
549                                         `request`, `confirm`, `notify`, `poll`, `poco`, `network`, `blocked`, `pending` )
550                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
551                                         intval($uid),
552                                         dbesc(datetime_convert()),
553                                         $parms['url'],
554                                         dbesc(normalise_link($url)),
555                                         $parms['addr'],
556                                         $parms['fn'],
557                                         $parms['nick'],
558                                         $parms['issued-id'],
559                                         $parms['photo'],
560                                         $parms['key'],
561                                         $parms['dfrn-request'],
562                                         $parms['dfrn-confirm'],
563                                         $parms['dfrn-notify'],
564                                         $parms['dfrn-poll'],
565                                         $parms['dfrn-poco'],
566                                         dbesc(NETWORK_DFRN),
567                                         intval($blocked),
568                                         intval($pending)
569                                 );
570
571                                 // find the contact record we just created
572                                 if($r) {
573                                         $r = q("SELECT `id` FROM `contact`
574                                                 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
575                                                 intval($uid),
576                                                 $parms['url'],
577                                                 $parms['issued-id']
578                                         );
579                                         if(dbm::is_result($r)) {
580                                                 $contact_record = $r[0];
581                                                 update_contact_avatar($photo, $uid, $contact_record["id"], true);
582                                         }
583                                 }
584
585                         }
586                         if($r === false) {
587                                 notice( t('Failed to update contact record.') . EOL );
588                                 return;
589                         }
590
591                         $hash = random_string() . (string) time();   // Generate a confirm_key
592
593                         if(is_array($contact_record)) {
594                                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
595                                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
596                                         intval($uid),
597                                         intval($contact_record['id']),
598                                         ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
599                                         dbesc(notags(trim($_POST['dfrn-request-message']))),
600                                         dbesc($hash),
601                                         dbesc(datetime_convert())
602                                 );
603                         }
604
605                         // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
606
607                         if(! $failed)
608                                 info( t('Your introduction has been sent.') . EOL );
609
610                         // "Homecoming" - send the requestor back to their site to record the introduction.
611
612                         $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
613                         $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
614
615                         goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url"
616                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
617                                 . '&confirm_key='  . $hash
618                                 . (($aes_allow) ? "&aes_allow=1" : "")
619                         );
620                         // NOTREACHED
621                         // END $network === NETWORK_DFRN
622                 } elseif (($network != NETWORK_PHANTOM) AND ($url != "")) {
623
624                         /*
625                          *
626                          * Substitute our user's feed URL into $url template
627                          * Send the subscriber home to subscribe
628                          *
629                          */
630
631                         // Diaspora needs the uri in the format user@domain.tld
632                         // Diaspora will support the remote subscription in a future version
633                         if ($network == NETWORK_DIASPORA) {
634                                 $uri = $nickname.'@'.$a->get_hostname();
635
636                                 if ($a->get_path())
637                                         $uri .= '/'.$a->get_path();
638
639                                 $uri = urlencode($uri);
640                         } else
641                                 $uri = $a->get_baseurl().'/profile/'.$nickname;
642
643                         $url = str_replace('{uri}', $uri, $url);
644                         goaway($url);
645                         // NOTREACHED
646                         // END $network != NETWORK_PHANTOM
647                 } else {
648                         notice(t("Remote subscription can't be done for your network. Please subscribe directly on your system.").EOL);
649                         return;
650                 }
651
652         }       return;
653 }
654
655
656 function dfrn_request_content(&$a) {
657
658         if(($a->argc != 2) || (! count($a->profile)))
659                 return "";
660
661
662         // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
663         // to send us to the post section to record the introduction.
664
665         if(x($_GET,'dfrn_url')) {
666
667                 if(! local_user()) {
668                         info( t("Please login to confirm introduction.") . EOL );
669                         /* setup the return URL to come back to this page if they use openid */
670                         $_SESSION['return_url'] = $a->query_string;
671                         return login();
672                 }
673
674                 // Edge case, but can easily happen in the wild. This person is authenticated,
675                 // but not as the person who needs to deal with this request.
676
677                 if ($a->user['nickname'] != $a->argv[1]) {
678                         notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
679                         return login();
680                 }
681
682                 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
683                 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
684                 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
685
686                 // Checking fastlane for validity
687                 if (x($_SESSION, "fastlane") AND (normalise_link($_SESSION["fastlane"]) == normalise_link($dfrn_url))) {
688                         $_POST["dfrn_url"] = $dfrn_url;
689                         $_POST["confirm_key"] = $confirm_key;
690                         $_POST["localconfirm"] = 1;
691                         $_POST["hidden-contact"] = 0;
692                         $_POST["submit"] = t('Confirm');
693
694                         dfrn_request_post($a);
695
696                         killme();
697                         return; // NOTREACHED
698                 }
699
700                 $tpl = get_markup_template("dfrn_req_confirm.tpl");
701                 $o  = replace_macros($tpl,array(
702                         '$dfrn_url' => $dfrn_url,
703                         '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
704                         '$hidethem' => t('Hide this contact'),
705                         '$hidechecked' => '',
706                         '$confirm_key' => $confirm_key,
707                         '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
708                         '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
709                         '$submit' => t('Confirm'),
710                         '$uid' => $_SESSION['uid'],
711                         '$nickname' => $a->user['nickname'],
712                         'dfrn_rawurl' => $_GET['dfrn_url']
713                         ));
714                 return $o;
715
716         }
717         elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) {
718
719                 // we are the requestee and it is now safe to send our user their introduction,
720                 // We could just unblock it, but first we have to jump through a few hoops to
721                 // send an email, or even to find out if we need to send an email.
722
723                 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
724                         dbesc($_GET['confirm_key'])
725                 );
726
727                 if(dbm::is_result($intro)) {
728
729                         $auto_confirm = false;
730
731                         $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
732                                 WHERE `contact`.`id` = %d LIMIT 1",
733                                 intval($intro[0]['contact-id'])
734                         );
735
736                         $auto_confirm = false;
737
738                         if(dbm::is_result($r)) {
739                                 if(($r[0]['page-flags'] != PAGE_NORMAL) && ($r[0]['page-flags'] != PAGE_PRVGROUP))
740                                         $auto_confirm = true;
741
742                                 if(! $auto_confirm) {
743
744                                         notification(array(
745                                                 'type'         => NOTIFY_INTRO,
746                                                 'notify_flags' => $r[0]['notify-flags'],
747                                                 'language'     => $r[0]['language'],
748                                                 'to_name'      => $r[0]['username'],
749                                                 'to_email'     => $r[0]['email'],
750                                                 'uid'          => $r[0]['uid'],
751                                                 'link'             => $a->get_baseurl() . '/notifications/intros',
752                                                 'source_name'  => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
753                                                 'source_link'  => $r[0]['url'],
754                                                 'source_photo' => $r[0]['photo'],
755                                                 'verb'         => ACTIVITY_REQ_FRIEND,
756                                                 'otype'        => 'intro'
757                                         ));
758                                 }
759
760                                 if($auto_confirm) {
761                                         require_once('mod/dfrn_confirm.php');
762                                         $handsfree = array(
763                                                 'uid' => $r[0]['uid'],
764                                                 'node' => $r[0]['nickname'],
765                                                 'dfrn_id' => $r[0]['issued-id'],
766                                                 'intro_id' => $intro[0]['id'],
767                                                 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0),
768                                                 'activity' => intval(get_pconfig($r[0]['uid'],'system','post_newfriend'))
769                                         );
770                                         dfrn_confirm_post($a,$handsfree);
771                                 }
772
773                         }
774
775                         if(! $auto_confirm) {
776
777                                 // If we are auto_confirming, this record will have already been nuked
778                                 // in dfrn_confirm_post()
779
780                                 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s'",
781                                         dbesc($_GET['confirm_key'])
782                                 );
783                         }
784                 }
785
786                 killme();
787                 return; // NOTREACHED
788         }
789         else {
790
791                 /*
792                  * Normal web request. Display our user's introduction form.
793                  */
794
795                 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
796                         if(! get_config('system','local_block')) {
797                                 notice( t('Public access denied.') . EOL);
798                                 return;
799                         }
800                 }
801
802
803                 /*
804                  * Try to auto-fill the profile address
805                  */
806
807                 // At first look if an address was provided
808                 // Otherwise take the local address
809                 if (x($_GET,'addr') AND ($_GET['addr'] != ""))
810                         $myaddr = hex2bin($_GET['addr']);
811                 elseif (x($_GET,'address') AND ($_GET['address'] != ""))
812                         $myaddr = $_GET['address'];
813                 elseif(local_user()) {
814                         if(strlen($a->path)) {
815                                 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
816                         }
817                         else {
818                                 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
819                         }
820                 } else  // last, try a zrl
821                         $myaddr = get_my_url();
822
823                 $target_addr = $a->profile['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
824
825
826                 /*
827                  *
828                  * The auto_request form only has the profile address
829                  * because nobody is going to read the comments and
830                  * it doesn't matter if they know you or not.
831                  *
832                  */
833
834                 if($a->profile['page-flags'] == PAGE_NORMAL)
835                         $tpl = get_markup_template('dfrn_request.tpl');
836                 else
837                         $tpl = get_markup_template('auto_request.tpl');
838
839                 $page_desc = t("Please enter your 'Identity Address' from one of the following supported communications networks:");
840
841                 // see if we are allowed to have NETWORK_MAIL2 contacts
842
843                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
844                 if(get_config('system','dfrn_only'))
845                         $mail_disabled = 1;
846
847                 if(! $mail_disabled) {
848                         $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
849                                 intval($a->profile['uid'])
850                         );
851                         if(! dbm::is_result($r))
852                                 $mail_disabled = 1;
853                 }
854
855                 // "coming soon" is disabled for now
856                 //$emailnet = (($mail_disabled) ? '' : t("<strike>Connect as an email follower</strike> \x28Coming soon\x29"));
857                 $emailnet = "";
858
859                 $invite_desc = sprintf(
860                         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>.'),
861                         get_server()
862                 );
863
864                 $o = replace_macros($tpl,array(
865                         '$header' => t('Friend/Connection Request'),
866                         '$desc' => t('Examples: jojo@demo.friendica.com, http://demo.friendica.com/profile/jojo, testuser@identi.ca'),
867                         '$pls_answer' => t('Please answer the following:'),
868                         '$does_know_you' => array('knowyou', sprintf(t('Does %s know you?'),$a->profile['name']), false, '', array(t('No'),t('Yes'))),
869                         /*'$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
870                         '$yes' => t('Yes'),
871                         '$no' => t('No'), */
872                         '$add_note' => t('Add a personal note:'),
873                         '$page_desc' => $page_desc,
874                         '$friendica' => t('Friendica'),
875                         '$statusnet' => t('StatusNet/Federated Social Web'),
876                         '$diaspora' => t('Diaspora'),
877                         '$diasnote' => sprintf (t(' - please do not use this form.  Instead, enter %s into your Diaspora search bar.'),$target_addr),
878                         '$your_address' => t('Your Identity Address:'),
879                         '$invite_desc' => $invite_desc,
880                         '$emailnet' => $emailnet,
881                         '$submit' => t('Submit Request'),
882                         '$cancel' => t('Cancel'),
883                         '$nickname' => $a->argv[1],
884                         '$name' => $a->profile['name'],
885                         '$myaddr' => $myaddr
886                 ));
887                 return $o;
888         }
889
890         return; // Somebody is fishing.
891 }