]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_request.php
Merge branch 'master' of git://github.com/friendika/friendika
[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($a->get_baseurl());
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( $invalid . t(' required parameter') 
127                                                                 . (($invalid == 1) ? t(" was ") : t("s were ") )
128                                                                 . t("not found at the given location.") . 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`, `aes_allow`) 
147                                                 VALUES ( %d, '%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                                                 intval($aes_allow)
160                                         );
161                                 }
162
163                                 if($r) {
164                                         notice( t("Introduction complete.") . EOL);
165                                 }
166
167                                 /**
168                                  * Allow the blocked remote notification to complete
169                                  */
170
171                                 if(is_array($contact_record))
172                                         $dfrn_request = $contact_record['request'];
173
174                                 if(strlen($dfrn_request) && strlen($confirm_key))
175                                         $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key);
176                                 
177                                 // (ignore reply, nothing we can do it failed)
178
179                                 goaway($dfrn_url);
180                                 return; // NOTREACHED
181
182                         }
183
184                 }
185
186                 // invalid/bogus request
187
188                 notice( t('Unrecoverable protocol error.') . EOL );
189                 goaway($a->get_baseurl());
190                 return; // NOTREACHED
191         }
192
193         /**
194          * Otherwise:
195          * 
196          * Scenario 1:
197          * We are the requestee. A person from a remote cell has made an introduction 
198          * on our profile web page and clicked submit. We will use their DFRN-URL to 
199          * figure out how to contact their cell.  
200          *
201          * Scrape the originating DFRN-URL for everything we need. Create a contact record
202          * and an introduction to show our user next time he/she logs in.
203          * Finally redirect back to the requestor so that their site can record the request.
204          * If our user (the requestee) later confirms this request, a record of it will need 
205          * to exist on the requestor's cell in order for the confirmation process to complete.. 
206          *
207          * It's possible that neither the requestor or the requestee are logged in at the moment,
208          * and the requestor does not yet have any credentials to the requestee profile.
209          *
210          * Who is the requestee? We've already loaded their profile which means their nickname should be
211          * in $a->argv[1] and we should have their complete info in $a->profile.
212          *
213          */
214
215         if(! (is_array($a->profile) && count($a->profile))) {
216                 notice( t('Profile unavailable.') . EOL);
217                 return;
218         }
219
220         $nickname = $a->profile['nickname'];
221         $notify_flags = $a->profile['notify-flags'];
222         $uid = $a->profile['uid'];
223
224         $contact_record = null;
225         $failed = false;
226         $parms = null;
227
228
229         if( x($_POST,'dfrn_url')) {
230
231                 $url = trim($_POST['dfrn_url']);
232                 if(! strlen($url)) {
233                         notice( t("Invalid locator") . EOL );
234                         return;
235                 }
236
237                 // Canonicalise email-style profile locator
238
239                 $url = webfinger_dfrn($url);
240
241                 if(substr($url,0,5) === 'stat:') {
242                         $network = 'stat';
243                         $url = substr($url,5);
244                 }
245                 else {
246                         $network = 'dfrn';
247                 }
248
249                 logger('dfrn_request: url: ' . $url);
250
251                 if(! strlen($url)) {
252                         notice( t("Unable to resolve your name at the provided location.") . EOL);                      
253                         return;
254                 }
255
256
257                 if($network === 'dfrn') {
258                         $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1", 
259                                 intval($uid),
260                                 dbesc($url)
261                         );
262
263                         if(count($ret)) {
264                                 if(strlen($ret[0]['issued-id'])) {
265                                         notice( t('You have already introduced yourself here.') . EOL );
266                                         return;
267                                 }
268                                 elseif($ret[0]['rel'] == REL_BUD) {
269                                         notice( t('Apparently you are already friends with .') . $a->profile['name'] . EOL);
270                                         return;
271                                 }
272                                 else {
273                                         $contact_record = $ret[0];
274                                         $parms = array('dfrn-request' => $ret[0]['request']);
275                                 }
276                         }
277
278                         $issued_id = random_string();
279
280                         if(is_array($contact_record)) {
281                                 // There is a contact record but no issued-id, so this
282                                 // is a reciprocal introduction from a known contact
283                                 $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1",
284                                         dbesc($issued_id),
285                                         intval($contact_record['id'])
286                                 );
287                         }
288                         else {
289                                 if(! validate_url($url)) {
290                                         notice( t('Invalid profile URL.') . EOL);
291                                         goaway($a->get_baseurl() . '/' . $a->cmd);
292                                         return; // NOTREACHED
293                                 }
294
295                                 if(! allowed_url($url)) {
296                                         notice( t('Disallowed profile URL.') . EOL);
297                                         goaway($a->get_baseurl() . '/' . $a->cmd);
298                                         return; // NOTREACHED
299                                 }
300                         
301
302                                 require_once('Scrape.php');
303
304                                 $parms = scrape_dfrn($url);
305
306                                 if(! count($parms)) {
307                                         notice( t('Profile location is not valid or does not contain profile information.') . EOL );
308                                         goaway($a->get_baseurl() . '/' . $a->cmd);
309                                 }
310                                 else {
311                                         if(! x($parms,'fn'))
312                                                 notice( t('Warning: profile location has no identifiable owner name.') . EOL );
313                                         if(! x($parms,'photo'))
314                                                 notice( t('Warning: profile location has no profile photo.') . EOL );
315                                         $invalid = validate_dfrn($parms);               
316                                         if($invalid) {
317                                                 notice( $invalid . t(' required parameter') 
318                                                         . (($invalid == 1) ? t(" was ") : t("s were ") )
319                                                         . t("not found at the given location.") . EOL ) ;
320         
321                                                 return;
322                                         }
323                                 }
324
325
326                                 $parms['url'] = $url;
327                                 $parms['issued-id'] = $issued_id;
328
329
330                                 dbesc_array($parms);
331                                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `issued-id`, `photo`, `site-pubkey`,
332                                         `request`, `confirm`, `notify`, `poll` )
333                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )",
334                                         intval($uid),
335                                         datetime_convert(),
336                                         $parms['url'],
337                                         $parms['fn'],
338                                         $parms['nick'],
339                                         $parms['issued-id'],
340                                         $parms['photo'],
341                                         $parms['key'],
342                                         $parms['dfrn-request'],
343                                         $parms['dfrn-confirm'],
344                                         $parms['dfrn-notify'],
345                                         $parms['dfrn-poll']
346                                 );
347
348                                 // find the contact record we just created
349                                 if($r) {        
350                                         $r = q("SELECT `id` FROM `contact` 
351                                                 WHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1",
352                                                 intval($uid),
353                                                 $parms['url'],
354                                                 $parms['issued-id']
355                                         );
356                                         if(count($r)) 
357                                                 $contact_record = $r[0];
358                                 }
359         
360                         }
361                         if($r === false) {
362                                 notice( t('Failed to update contact record.') . EOL );
363                                 return;
364                         }
365
366                         $hash = random_string() . (string) time();   // Generate a confirm_key
367         
368                         if(is_array($contact_record)) {
369                                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
370                                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
371                                         intval($uid),
372                                         intval($contact_record['id']),
373                                         ((x($_POST,'knowyou') && ($_POST['knowyou'] == 1)) ? 1 : 0),
374                                         dbesc(notags(trim($_POST['dfrn-request-message']))),
375                                         dbesc($hash),
376                                         dbesc(datetime_convert())
377                                 );
378                         }
379         
380                         // This notice will only be seen by the requestor if the requestor and requestee are on the same server.
381
382                         if(! $failed) 
383                                 notice( t('Your introduction has been sent.') . EOL );
384
385                         // "Homecoming" - send the requestor back to their site to record the introduction.
386
387                         $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname);
388                         $aes_allow = ((function_exists('openssl_encrypt')) ? 1 : 0);
389
390                         goaway($parms['dfrn-request'] . "?dfrn_url=$dfrn_url" 
391                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION 
392                                 . '&confirm_key='  . $hash 
393                                 . (($aes_allow) ? "&aes_allow=1" : "")
394                         );
395                         // NOTREACHED
396                         // END $network === 'dfrn'
397                 }
398                 elseif($network === 'stat') {
399                         
400                         /**
401                          *
402                          * OStatus network
403                          * Check contact existence
404                          * Try and scrape together enough information to create a contact record, with us as REL_VIP
405                          * Substitute our user's feed URL into $url template
406                          * Send the subscriber home to subscribe
407                          *
408                          */
409
410                         $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url);
411                         goaway($url);
412                         // NOTREACHED
413                         // END $network === 'stat'
414                 }
415
416         }       return;
417 }}
418
419
420
421
422 if(! function_exists('dfrn_request_content')) {
423 function dfrn_request_content(&$a) {
424
425         
426
427         if(($a->argc != 2) || (! count($a->profile)))
428                 return "";
429
430         $a->page['template'] = 'profile';
431
432         // "Homecoming". Make sure we're logged in to this site as the correct user. Then offer a confirm button
433         // to send us to the post section to record the introduction.
434
435         if(x($_GET,'dfrn_url')) {
436
437                 if(! local_user()) {
438                         notice( t("Please login to confirm introduction.") . EOL );
439                         return login();
440                 }
441
442                 // Edge case, but can easily happen in the wild. This person is authenticated, 
443                 // but not as the person who needs to deal with this request.
444
445                 if ($a->user['nickname'] != $a->argv[1]) {
446                         notice( t("Incorrect identity currently logged in. Please login to <strong>this</strong> profile.") . EOL);
447                         return login();
448                 }
449
450                 $dfrn_url = notags(trim(hex2bin($_GET['dfrn_url'])));
451                 $aes_allow = (((x($_GET,'aes_allow')) && ($_GET['aes_allow'] == 1)) ? 1 : 0);
452                 $confirm_key = (x($_GET,'confirm_key') ? $_GET['confirm_key'] : "");
453                 $o .= load_view_file("view/dfrn_req_confirm.tpl");
454                 $o  = replace_macros($o,array(
455                         '$dfrn_url' => $dfrn_url,
456                         '$aes_allow' => (($aes_allow) ? '<input type="hidden" name="aes_allow" value="1" />' : "" ),
457                         '$confirm_key' => $confirm_key,
458                         '$username' => $a->user['username'], 
459                         '$uid' => $_SESSION['uid'],
460                         '$nickname' => $a->user['nickname'],
461                         'dfrn_rawurl' => $_GET['dfrn_url']
462                         ));
463                 return $o;
464
465         }
466         elseif((x($_GET,'confirm_key')) && strlen($_GET['confirm_key'])) { 
467
468                 // we are the requestee and it is now safe to send our user their introduction,
469                 // We could just unblock it, but first we have to jump through a few hoops to 
470                 // send an email, or even to find out if we need to send an email. 
471
472                 $intro = q("SELECT * FROM `intro` WHERE `hash` = '%s' LIMIT 1",
473                         dbesc($_GET['confirm_key'])
474                 );
475
476                 if(count($intro)) {
477
478                         $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
479                                 WHERE `contact`.`id` = %d LIMIT 1",
480                                 intval($intro[0]['contact-id'])
481                         );
482
483                         $auto_confirm = false;
484
485                         if(count($r)) {
486                                 if($r[0]['page-flags'] != PAGE_NORMAL)
487                                         $auto_confirm = true;                           
488                                 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && (! $auto_confirm)) {
489                                         $email_tpl = load_view_file('view/request_notify_eml.tpl');
490                                         $email = replace_macros($email_tpl, array(
491                                                 '$requestor' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : t('[Name Withheld]')),
492                                                 '$url' => stripslashes($r[0]['url']),
493                                                 '$myname' => $r[0]['username'],
494                                                 '$siteurl' => $a->get_baseurl(),
495                                                 '$sitename' => $a->config['sitename']
496                                         ));
497                                         $res = mail($r[0]['email'], 
498                                                 t("Introduction received at ") . $a->config['sitename'],
499                                                 $email,
500                                                 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
501                                         // This is a redundant notification - no point throwing errors if it fails.
502                                 }
503                                 if($auto_confirm) {
504                                         require_once('mod/dfrn_confirm.php');
505                                         $handsfree = array(
506                                                 'uid' => $r[0]['uid'],
507                                                 'node' => $r[0]['nickname'],
508                                                 'dfrn_id' => $r[0]['issued-id'],
509                                                 'intro_id' => $intro[0]['id'],
510                                                 'duplex' => (($r[0]['page-flags'] == PAGE_FREELOVE) ? 1 : 0)
511                                         );
512                                         dfrn_confirm_post($a,$handsfree);
513                                 }
514
515                         }
516
517                         if(! $auto_confirm) {
518
519                                 // If we are auto_confirming, this record will have already been nuked
520                                 // in dfrn_confirm_post()
521
522                                 $r = q("UPDATE `intro` SET `blocked` = 0 WHERE `hash` = '%s' LIMIT 1",
523                                         dbesc($_GET['confirm_key'])
524                                 );
525                         }
526                 }
527                 killme();
528                 return; // NOTREACHED
529         }
530         else {
531                 $myaddr = ((x($_GET,'address')) ? urldecode($_GET['address']) : '');
532                 // Normal web request. Display our user's introduction form. 
533                 if($a->profile['page-flags'] == PAGE_NORMAL)
534                         $tpl = load_view_file('view/dfrn_request.tpl');
535                 else
536                         $tpl = load_view_file('view/auto_request.tpl');
537                 $o .= replace_macros($tpl,array(
538                         '$header' => t('Friend/Connection Request'),
539                         '$pls_answer' => t('Please answer the following:'),
540                         '$does_know' => t('Does $name know you?'),
541                         '$yes' => t('Yes'),
542                         '$no' => t('No'),
543                         '$add_note' => t('Add a personal note:'),
544                         '$page_desc' => t('Please enter your profile address from one of the following supported social networks:'),
545                         '$friendika' => t('Friendika'),
546                         '$statusnet' => t('StatusNet/Federated Social Web'),
547                         '$private_net' => t("Private \x28secure\x29 network"),
548                         '$public_net' => t("Public \x28insecure\x29 network"),
549                         '$your_address' => t('Your profile address:'),
550                         '$submit' => t('Submit Request'),
551                         '$cancel' => t('Cancel'),
552                         '$nickname' => $a->argv[1],
553                         '$name' => $a->profile['name'],
554                         '$myaddr' => $myaddr
555                 ));
556                 return $o;
557         }
558
559         return; // Somebody is fishing.
560 }}