]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_request.php
98901e9f56c80c4e10745c0e9d4a0eb4128ab37d
[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 if(! function_exists('dfrn_request_init')) {
13 function dfrn_request_init(&$a) {
14
15         if($a->argc > 1)
16                 $which = $a->argv[1];
17
18         profile_load($a,$which);
19         return;
20 }}
21
22
23 /**
24  * Function: dfrn_request_post
25  *
26  * Purpose:
27  * Handles multiple scenarios.
28  *
29  * Scenario 1:
30  * Clicking 'submit' on a friend request page.
31  *
32  * Scenario 2:
33  * Following Scenario 1, we are brought back to our home site
34  * in order to link our friend request with our own server cell.
35  * After logging in, we click 'submit' to approve the linkage.
36  *
37  */
38
39 if(! function_exists('dfrn_request_post')) {
40 function dfrn_request_post(&$a) {
41
42         if(($a->argc != 2) || (! count($a->profile)))
43                 return;
44
45
46         if($_POST['cancel']) {
47                 goaway(z_root());
48         } 
49
50
51         /**
52          *
53          * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell
54          * to confirm the request, and then we've clicked submit (perhaps after logging in). 
55          * That brings us here:
56          *
57          */
58
59         if((x($_POST,'localconfirm')) && ($_POST['localconfirm'] == 1)) {
60
61                 /**
62                  * Ensure this is a valid request
63                  */
64
65                 if(local_user() && ($a->user['nickname'] == $a->argv[1]) && (x($_POST,'dfrn_url'))) {
66
67
68                         $dfrn_url    = notags(trim($_POST['dfrn_url']));
69                         $aes_allow   = (((x($_POST,'aes_allow')) && ($_POST['aes_allow'] == 1)) ? 1 : 0);
70                         $confirm_key = ((x($_POST,'confirm_key')) ? $_POST['confirm_key'] : "");
71
72                         $contact_record = null;
73         
74                         if(x($dfrn_url)) {
75
76                                 /**
77                                  * Lookup the contact based on their URL (which is the only unique thing we have at the moment)
78                                  */
79         
80                                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",
81                                         intval(local_user()),
82                                         dbesc($dfrn_url)
83                                 );
84         
85                                 if(count($r)) {
86                                         if(strlen($r[0]['dfrn-id'])) {
87
88                                                 /**
89                                                  * We don't need to be here. It has already happened.
90                                                  */
91
92                                                 notice( t("This introduction has already been accepted.") . EOL );
93                                                 return;
94                                         }
95                                         else
96                                                 $contact_record = $r[0];
97                                 }
98         
99                                 if(is_array($contact_record)) {
100                                         $r = q("UPDATE `contact` SET `ret-aes` = %d WHERE `id` = %d LIMIT 1",
101                                                 intval($aes_allow),
102                                                 intval($contact_record['id'])
103                                         );
104                                 }
105                                 else {
106         
107                                         /**
108                                          * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo
109                                          */
110
111                                         require_once('Scrape.php');
112         
113                                         $parms = scrape_dfrn($dfrn_url);
114         
115                                         if(! count($parms)) {
116                                                 notice( t('Profile location is not valid or does not contain profile information.') . EOL );
117                                                 return;
118                                         }
119                                         else {
120                                                 if(! x($parms,'fn'))
121                                                         notice( t('Warning: profile location has no identifiable owner name.') . EOL );
122                                                 if(! x($parms,'photo'))
123                                                         notice( t('Warning: profile location has no profile photo.') . EOL );
124                                                 $invalid = validate_dfrn($parms);               
125                                                 if($invalid) {
126                                                         notice( sprintf( tt("%d required parameter was not found at the given location",
127                                                                                                 "%d required parameters were not found at the given location",
128                                                                                                 $invalid), $invalid) . EOL );
129                                                         return;
130                                                 }
131                                         }
132
133                                         $dfrn_request = $parms['dfrn-request'];
134
135                     /********* Escape the entire array ********/
136
137                                         dbesc_array($parms);
138
139                                         /******************************************/
140
141                                         /**
142                                          * Create a contact record on our site for the other person
143                                          */
144
145                                         $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `name`, `nick`, `photo`, `site-pubkey`,
146                                                 `request`, `confirm`, `notify`, `poll`, `network`, `aes_allow`) 
147                                                 VALUES ( %d, '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
148                                                 intval(local_user()),
149                                                 datetime_convert(),
150                                                 dbesc($dfrn_url),
151                                                 $parms['fn'],
152                                                 $parms['nick'],
153                                                 $parms['photo'],
154                                                 $parms['key'],
155                                                 $parms['dfrn-request'],
156                                                 $parms['dfrn-confirm'],
157                                                 $parms['dfrn-notify'],
158                                                 $parms['dfrn-poll'],
159                                                 dbesc(NETWORK_DFRN),
160                                                 intval($aes_allow)
161                                         );
162                                 }
163
164                                 if($r) {
165                                         info( t("Introduction complete.") . EOL);
166                                 }
167
168                                 /**
169                                  * Allow the blocked remote notification to complete
170                                  */
171
172                                 if(is_array($contact_record))
173                                         $dfrn_request = $contact_record['request'];
174
175                                 if(strlen($dfrn_request) && strlen($confirm_key))
176                                         $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
177                                 
178                                 // (ignore reply, nothing we can do it failed)
179
180                                 goaway($dfrn_url);
181                                 return; // NOTREACHED
182
183                         }
184
185                 }
186
187                 // invalid/bogus request
188
189                 notice( t('Unrecoverable protocol error.') . EOL );
190                 goaway(z_root());
191                 return; // NOTREACHED
192         }
193
194         /**
195          * Otherwise:
196          * 
197          * Scenario 1:
198          * We are the requestee. A person from a remote cell has made an introduction 
199          * on our profile web page and clicked submit. We will use their DFRN-URL to 
200          * figure out how to contact their cell.  
201          *
202          * Scrape the originating DFRN-URL for everything we need. Create a contact record
203          * and an introduction to show our user next time he/she logs in.
204          * Finally redirect back to the requestor so that their site can record the request.
205          * If our user (the requestee) later confirms this request, a record of it will need 
206          * to exist on the requestor's cell in order for the confirmation process to complete.. 
207          *
208          * It's possible that neither the requestor or the requestee are logged in at the moment,
209          * and the requestor does not yet have any credentials to the requestee profile.
210          *
211          * Who is the requestee? We've already loaded their profile which means their nickname should be
212          * in $a->argv[1] and we should have their complete info in $a->profile.
213          *
214          */
215
216         if(! (is_array($a->profile) && count($a->profile))) {
217                 notice( t('Profile unavailable.') . EOL);
218                 return;
219         }
220
221         $nickname       = $a->profile['nickname'];
222         $notify_flags   = $a->profile['notify-flags'];
223         $uid            = $a->profile['uid'];
224         $maxreq         = intval($a->profile['maxreq']);
225         $contact_record = null;
226         $failed         = false;
227         $parms          = null;
228
229
230         if( x($_POST,'dfrn_url')) {
231
232                 /**
233                  * Block friend request spam
234                  */
235
236                 if($maxreq) {
237                         $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d",
238                                 dbesc(datetime_convert('UTC','UTC','now - 24 hours')),
239                                 intval($uid)
240                         );
241                         if(count($r) > $maxreq) {
242                                 notice( sprintf( t('%s has received too many connection requests today.'),  $a->profile['name']) . EOL);
243                                 notice( t('Spam protection measures have been invoked.') . EOL);
244                                 notice( t('Friends are advised to please try again in 24 hours.') . EOL);
245                                 return;
246                         } 
247                 }
248
249                 /**
250                  *
251                  * Cleanup old introductions that remain blocked. 
252                  * Also remove the contact record, but only if there is no existing relationship
253                  *
254                  */
255
256                 $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel` 
257                         FROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`
258                         WHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0 AND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ");
259                 if(count($r)) {
260                         foreach($r as $rr) {
261                                 if(! $rr['rel']) {
262                                         q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1",
263                                                 intval($rr['cid'])
264                                         );
265                                 }
266                                 q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1",
267                                         intval($rr['iid'])
268                                 );
269                         }
270                 }
271
272                 $url = trim($_POST['dfrn_url']);
273                 if(! strlen($url)) {
274                         notice( t("Invalid locator") . EOL );
275                         return;
276                 }
277
278                 // Canonicalise email-style profile locator
279
280                 $url = webfinger_dfrn($url);
281
282                 if(substr($url,0,5) === 'stat:') {
283                         $network = 'stat';
284                         $url = substr($url,5);
285                 }
286                 else {
287                         $network = 'dfrn';
288                 }
289
290                 logger('dfrn_request: url: ' . $url);
291
292                 if(! strlen($url)) {
293                         notice( t("Unable to resolve your name at the provided location.") . EOL);                      
294                         return;
295                 }
296
297
298                 if($network === NETWORK_DFRN) {
299                         $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1", 
300                                 intval($uid),
301                                 dbesc($url)
302                         );
303
304                         if(count($ret)) {
305                                 if(strlen($ret[0]['issued-id'])) {
306                                         notice( t('You have already introduced yourself here.') . EOL );
307                                         return;
308                                 }
309                                 elseif($ret[0]['rel'] == CONTACT_IS_FRIEND) {
310                                         notice( sprintf( t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL);
311                                         return;
312                                 }
313                                 else {
314                                         $contact_record = $ret[0];
315                                         $parms = array('dfrn-request' => $ret[0]['request']);
316                                 }
317                         }
318
319                         $issued_id = random_string();
320
321                         if(is_array($contact_record)) {
322                                 // There is a contact record but no issued-id, so this
323                                 // is a reciprocal introduction from a known contact
324                                 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1",
325                                         dbesc($issued_id),
326                                         intval($contact_record['id'])
327                                 );
328                         }
329                         else {
330                                 if(! validate_url($url)) {
331                                         notice( t('Invalid profile URL.') . EOL);
332                                         goaway($a->get_baseurl() . '/' . $a->cmd);
333                                         return; // NOTREACHED
334                                 }
335
336                                 if(! allowed_url($url)) {
337                                         notice( t('Disallowed profile URL.') . EOL);
338                                         goaway($a->get_baseurl() . '/' . $a->cmd);
339                                         return; // NOTREACHED
340                                 }
341                         
342
343                                 require_once('Scrape.php');
344
345                                 $parms = scrape_dfrn($url);
346
347                                 if(! count($parms)) {
348                                         notice( t('Profile location is not valid or does not contain profile information.') . EOL );
349                                         goaway($a->get_baseurl() . '/' . $a->cmd);
350                                 }
351                                 else {
352                                         if(! x($parms,'fn'))
353                                                 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
354                                         if(! x($parms,'photo'))
355                                                 notice( t('Warning: profile location has no profile photo.') . EOL );
356                                         $invalid = validate_dfrn($parms);               
357                                         if($invalid) {
358                                                 notice( sprintf( tt("%d required parameter was not found at the given location",
359                                                                                         "%d required parameters were not found at the given location",
360                                                                                         $invalid), $invalid) . EOL );
361         
362                                                 return;
363                                         }
364                                 }
365
366
367                                 $parms['url'] = $url;
368                                 $parms['issued-id'] = $issued_id;
369
370
371                                 dbesc_array($parms);
372                                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
373                                         `request`, `confirm`, `notify`, `poll`, `network` )
374                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
375                                         intval($uid),
376                                         datetime_convert(),
377                                         $parms['url'],
378                                         $parms['fn'],
379                                         $parms['nick'],
380                                         $parms['issued-id'],
381                                         $parms['photo'],
382                                         $parms['key'],
383                                         $parms['dfrn-request'],
384                                         $parms['dfrn-confirm'],
385                                         $parms['dfrn-notify'],
386                                         $parms['dfrn-poll'],
387                                         dbesc(NETWORK_DFRN)
388                                 );
389
390                                 // find the contact record we just created
391                                 if($r) {        
392                                         $r = q("SELECT `id` FROM `contact` 
393                                                 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
394                                                 intval($uid),
395                                                 $parms['url'],
396                                                 $parms['issued-id']
397                                         );
398                                         if(count($r)) 
399                                                 $contact_record = $r[0];
400                                 }
401         
402                         }
403                         if($r === false) {
404                                 notice( t('Failed to update contact record.') . EOL );
405                                 return;
406                         }
407
408                         $hash = random_string() . (string) time();   // Generate a confirm_key
409         
410                         if(is_array($contact_record)) {
411                                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
412                                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
413                                         intval($uid),
414                                         intval($contact_record['id']),
415                                         ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
416                                         dbesc(notags(trim($_POST['dfrn-request-message']))),
417                                         dbesc($hash),
418                                         dbesc(datetime_convert())
419                                 );
420                         }
421         
422                         // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
423
424                         if(! $failed) 
425                                 info( t('Your introduction has been sent.') . EOL );
426
427                         // "Homecoming" - send the requestor back to their site to record the introduction.
428
429                         $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
430                         $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
431
432                         goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url" 
433                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION 
434                                 . '&confirm_key='  . $hash 
435                                 . (($aes_allow) ? "&aes_allow=1" : "")
436                         );
437                         // NOTREACHED
438                         // END $network === NETWORK_DFRN
439                 }
440                 elseif($network === NETWORK_OSTATUS) {
441                         
442                         /**
443                          *
444                          * OStatus network
445                          * Check contact existence
446                          * Try and scrape together enough information to create a contact record, 
447                          * with us as CONTACT_IS_FOLLOWER
448                          * Substitute our user's feed URL into $url template
449                          * Send the subscriber home to subscribe
450                          *
451                          */
452
453                         $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url);
454                         goaway($url);
455                         // NOTREACHED
456                         // END $network === NETWORK_OSTATUS
457                 }
458
459         }       return;
460 }}
461
462
463
464
465 if(! function_exists('dfrn_request_content')) {
466 function dfrn_request_content(&$a) {
467
468         if(($a->argc != 2) || (! count($a->profile)))
469                 return "";
470
471
472         // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
473         // to send us to the post section to record the introduction.
474
475         if(x($_GET,'dfrn_url')) {
476
477                 if(! local_user()) {
478                         info( t("Please login to confirm introduction.") . EOL );
479
480                         /* setup the return URL to come back to this page if they use openid */
481
482                         $stripped = str_replace('q=','',$a->query_string);
483                         $_SESSION['return_url'] = trim($stripped,'/');
484
485                         return login();
486                 }
487
488                 // Edge case, but can easily happen in the wild. This person is authenticated, 
489                 // but not as the person who needs to deal with this request.
490
491                 if ($a->user['nickname'] != $a->argv[1]) {
492                         notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
493                         return login();
494                 }
495
496                 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
497                 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
498                 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
499                 $tpl = get_markup_template("dfrn_req_confirm.tpl");
500                 $o  = replace_macros($tpl,array(
501                         '$dfrn_url' => $dfrn_url,
502                         '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
503                         '$confirm_key' => $confirm_key,
504                         '$welcome' => sprintf( t('Welcome home %s.'), $a->user['username']),
505                         '$please' => sprintf( t('Please confirm your introduction/connection request to %s.'), $dfrn_url),
506                         '$submit' => t('Confirm'),
507                         '$uid' => $_SESSION['uid'],
508                         '$nickname' => $a->user['nickname'],
509                         'dfrn_rawurl' => $_GET['dfrn_url']
510                         ));
511                 return $o;
512
513         }
514         elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) { 
515
516                 // we are the requestee and it is now safe to send our user their introduction,
517                 // We could just unblock it, but first we have to jump through a few hoops to 
518                 // send an email, or even to find out if we need to send an email. 
519
520                 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
521                         dbesc($_GET['confirm_key'])
522                 );
523
524                 if(count($intro)) {
525
526                         $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
527                                 WHERE `contact`.`id` = %d LIMIT 1",
528                                 intval($intro[0]['contact-id'])
529                         );
530
531                         $auto_confirm = false;
532
533                         if(count($r)) {
534                                 if($r[0]['page-flags'] != PAGE_NORMAL)
535                                         $auto_confirm = true;                           
536                                 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && (! $auto_confirm)) {
537                                         $email_tpl = get_intltext_template('request_notify_eml.tpl');
538                                         $email = replace_macros($email_tpl, array(
539                                                 '$requestor' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
540                                                 '$url' => stripslashes($r[0]['url']),
541                                                 '$myname' => $r[0]['username'],
542                                                 '$siteurl' => $a->get_baseurl(),
543                                                 '$sitename' => $a->config['sitename']
544                                         ));
545                                         $res = mail($r[0]['email'], 
546                                             t("Introduction received at ") . $a->config['sitename'],
547                                                 $email,
548                                                 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
549                                                 . 'Content-type: text/plain; charset=UTF-8' . "\n"
550                                                 . 'Content-transfer-encoding: 8bit' );
551
552                                         // This is a redundant notification - no point throwing errors if it fails.
553                                 }
554                                 if($auto_confirm) {
555                                         require_once('mod/dfrn_confirm.php');
556                                         $handsfree = array(
557                                                 'uid' => $r[0]['uid'],
558                                                 'node' => $r[0]['nickname'],
559                                                 'dfrn_id' => $r[0]['issued-id'],
560                                                 'intro_id' => $intro[0]['id'],
561                                                 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0)
562                                         );
563                                         dfrn_confirm_post($a,$handsfree);
564                                 }
565
566                         }
567
568                         if(! $auto_confirm) {
569
570                                 // If we are auto_confirming, this record will have already been nuked
571                                 // in dfrn_confirm_post()
572
573                                 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s' LIMIT 1",
574                                         dbesc($_GET['confirm_key'])
575                                 );
576                         }
577                 }
578
579                 killme();
580                 return; // NOTREACHED
581         }
582         else {
583
584                 /**
585                  * Normal web request. Display our user's introduction form.
586                  */
587  
588                 if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
589                         notice( t('Public access denied.') . EOL);
590                         return;
591                 }
592
593
594                 /**
595                  * Try to auto-fill the profile address
596                  */
597
598                 if(local_user()) {
599                         if(strlen($a->path)) {
600                                 $myaddr = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
601                         }
602                         else {
603                                 $myaddr = $a->user['nickname'] . '@' . substr(z_root(), strpos(z_root(),'://') + 3 );
604                         }
605                 }
606                 elseif(x($_GET,'addr')) {
607                         $myaddr = hex2bin($_GET['addr']);
608                 }
609                 else {
610                         /* $_GET variables are already urldecoded */ 
611                         $myaddr = ((x($_GET,'address')) ? $_GET['address'] : '');
612                 }
613
614                 /**
615                  *
616                  * The auto_request form only has the profile address
617                  * because nobody is going to read the comments and 
618                  * it doesn't matter if they know you or not.
619                  *
620                  */
621
622                 if($a->profile['page-flags'] == PAGE_NORMAL)
623                         $tpl = get_markup_template('dfrn_request.tpl');
624                 else
625                         $tpl = get_markup_template('auto_request.tpl');
626
627                 $o .= replace_macros($tpl,array(
628                         '$header' => t('Friend/Connection Request'),
629                         '$desc' => t('Examples: jojo@demo.friendika.com, http://demo.friendika.com/profile/jojo, testuser@identi.ca'),
630                         '$pls_answer' => t('Please answer the following:'),
631                         '$does_know' => sprintf( t('Does %s know you?'),$a->profile['name']),
632                         '$yes' => t('Yes'),
633                         '$no' => t('No'),
634                         '$add_note' => t('Add a personal note:'),
635                         '$page_desc' => t("Please enter your 'Identity Address' from one of the following supported social networks:"),
636                         '$friendika' => t('Friendika'),
637                         '$statusnet' => t('StatusNet/Federated Social Web'),
638                         '$private_net' => t("Private \x28secure\x29 network"),
639                         '$public_net' => t("Public \x28insecure\x29 network"),
640                         '$your_address' => t('Your Identity Address:'),
641                         '$submit' => t('Submit Request'),
642                         '$cancel' => t('Cancel'),
643                         '$nickname' => $a->argv[1],
644                         '$name' => $a->profile['name'],
645                         '$myaddr' => $myaddr
646                 ));
647                 return $o;
648         }
649
650         return; // Somebody is fishing.
651 }}