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