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