]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
95673996feac085e945c2e41d89f0cd7d6552a71
[friendica.git] / include / diaspora.php
1 <?php
2
3 require_once('include/crypto.php');
4 require_once('include/items.php');
5
6 function get_diaspora_key($uri) {
7         $key = '';
8
9         logger('Fetching diaspora key for: ' . $uri);
10
11         $arr = lrdd($uri);
12
13         if(is_array($arr)) {
14                 foreach($arr as $a) {
15                         if($a['@attributes']['rel'] === 'diaspora-public-key') {
16                                 $key = base64_decode($a['@attributes']['href']);
17                         }
18                 }
19         }
20         else {
21                 return '';
22         }
23
24         if($key)
25                 return rsatopem($key);
26         return '';
27 }
28
29
30 function diaspora_base_message($type,$data) {
31
32         $tpl = get_markup_template('diaspora_' . $type . '.tpl');
33         if(! $tpl) 
34                 return '';
35         return replace_macros($tpl,$data);
36
37 }
38
39
40 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
41         $a = get_app();
42
43         $inner_aes_key = random_string(32);
44         $b_inner_aes_key = base64_encode($inner_aes_key);
45         $inner_iv = random_string(32);
46         $b_inner_iv = base64_encode($inner_iv);
47
48         $outer_aes_key = random_string(32);
49         $b_outer_aes_key = base64_encode($outer_aes_key);
50         $outer_iv = random_string(32);
51         $b_outer_iv = base64_encode($outer_iv);
52         
53         $handle = 'acct:' . $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
54
55         $padded_data = pkcs5_pad($msg,16);
56         $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
57
58         $b64_data = base64_encode($inner_encrypted);
59
60
61         $b64url_data = base64url_encode($b64_data);
62         $b64url_stripped = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
63     $lines = str_split($b64url_stripped,60);
64     $data = implode("\n",$lines);
65         $data = $data . (($data[-1] != "\n") ? "\n" : '') ;
66         $type = 'application/atom+xml';
67         $encoding = 'base64url';
68         $alg = 'RSA-SHA256';
69
70         $signable_data = $data  . '.' . base64url_encode($type) . "\n" . '.' 
71                 . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
72
73         $signature = rsa_sign($signable_data,$prvkey);
74         $sig = base64url_encode($signature);
75
76 $decrypted_header = <<< EOT
77 <decrypted_header>
78   <iv>$b_inner_iv</iv>
79   <aes_key>$b_inner_aes_key</aes_key>
80   <author>
81     <name>{$user['username']}</name>
82     <uri>$handle</uri>
83   </author>
84 </decrypted_header>
85 EOT;
86
87         $decrypted_header = pkcs5_pad($decrypted_header,16);
88
89         $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
90
91         $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
92         $encrypted_outer_key_bundle = '';
93         openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
94         
95         $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
96         $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle), 
97                 'ciphertext' => base64_encode($ciphertext)));
98         $encrypted_header = '<encrypted_header>' . base64_encode($encrypted_header_json_object) . '</encrypted_header>';
99
100 $magic_env = <<< EOT
101 <?xml version='1.0' encoding='UTF-8'?>
102 <entry xmlns='http://www.w3.org/2005/Atom'>
103   $encrypted_header
104   <me:env xmlns:me="http://salmon-protocol.org/ns/magic-env">
105     <me:encoding>base64url</me:encoding>
106     <me:alg>RSA-SHA256</me:alg>
107     <me:data type="application/atom+xml">$data</me:data>
108     <me:sig>$sig</me:sig>
109   </me:env>
110 </entry>
111 EOT;
112
113         return $magic_env;
114
115 }
116
117
118 function diaspora_decode($importer,$xml) {
119
120
121
122         $basedom = parse_xml_string($xml);
123
124         $atom = $basedom->children(NAMESPACE_ATOM1);
125
126         $encrypted_header = json_decode(base64_decode($atom->encrypted_header));
127         
128         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
129         $ciphertext = base64_decode($encrypted_header->ciphertext);
130
131         $outer_key_bundle = '';
132         openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
133
134         $j_outer_key_bundle = json_decode($outer_key_bundle);
135
136         $outer_iv = base64_decode($j_outer_key_bundle->iv);
137         $outer_key = base64_decode($j_outer_key_bundle->key);
138
139         $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
140
141         $decrypted = pkcs5_unpad($decrypted);
142
143         /**
144          * $decrypted now contains something like
145          *
146          *  <decrypted_header>
147          *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
148          *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
149          *     <author>
150          *       <name>Ryan Hughes</name>
151          *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
152          *     </author>
153          *  </decrypted_header>
154          */
155
156         logger('decrypted: ' . $decrypted);
157         $idom = parse_xml_string($decrypted,false);
158
159         $inner_iv = base64_decode($idom->iv);
160         $inner_aes_key = base64_decode($idom->aes_key);
161
162         $author_link = str_replace('acct:','',$idom->author->uri);
163
164         $dom = $basedom->children(NAMESPACE_SALMON_ME);
165
166         // figure out where in the DOM tree our data is hiding
167
168         if($dom->provenance->data)
169                 $base = $dom->provenance;
170         elseif($dom->env->data)
171                 $base = $dom->env;
172         elseif($dom->data)
173                 $base = $dom;
174         
175         if(! $base) {
176                 logger('mod-diaspora: unable to locate salmon data in xml ');
177                 http_status_exit(400);
178         }
179
180
181         // Stash the signature away for now. We have to find their key or it won't be good for anything.
182         $signature = base64url_decode($base->sig);
183
184         // unpack the  data
185
186         // strip whitespace so our data element will return to one big base64 blob
187         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
188         // Add back the 60 char linefeeds
189     $lines = str_split($data,60);
190     $data = implode("\n",$lines);
191
192
193         // stash away some other stuff for later
194
195         $type = $base->data[0]->attributes()->type[0];
196         $keyhash = $base->sig[0]->attributes()->keyhash[0];
197         $encoding = $base->encoding;
198         $alg = $base->alg;
199
200         $signed_data = $data  . (($data[-1] != "\n") ? "\n" : '') . '.' . base64url_encode($type) . "\n" . '.' . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
201
202
203         // decode the data
204         $data = base64url_decode($data);
205
206         // Now pull out the inner encrypted blob
207
208         $inner_encrypted = base64_decode($data);
209
210         $inner_decrypted = 
211         $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
212
213         $inner_decrypted = pkcs5_unpad($inner_decrypted);
214
215         if(! $author_link) {
216                 logger('mod-diaspora: Could not retrieve author URI.');
217                 http_status_exit(400);
218         }
219
220         // Once we have the author URI, go to the web and try to find their public key
221         // *** or look it up locally ***
222
223         logger('mod-diaspora: Fetching key for ' . $author_link );
224
225         // Get diaspora public key (pkcs#1) and convert to pkcs#8
226         $key = get_diaspora_key($author_link);
227
228         if(! $key) {
229                 logger('mod-diaspora: Could not retrieve author key.');
230                 http_status_exit(400);
231         }
232
233         $verify = rsa_verify($signed_data,$signature,$key);
234
235         if(! $verify) {
236                 logger('mod-diaspora: Message did not verify. Discarding.');
237                 http_status_exit(400);
238         }
239
240         logger('mod-diaspora: Message verified.');
241
242         return $inner_decrypted;
243
244 }
245
246 function diaspora_get_contact_by_handle($uid,$handle) {
247         $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
248                 dbesc(NETWORK_DIASPORA),
249                 intval($uid),
250                 dbesc($handle)
251         );
252         if($r && count($r))
253                 return $r[0];
254         return false;
255 }
256
257
258 function diaspora_request($importer,$xml) {
259
260         $sender_handle = $xml->sender_handle;
261         $recipient_handle = $xml->recipient_handle;
262
263         if(! $sender_handle || ! $recipient_handle)
264                 return;
265          
266         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
267
268         if($contact) {
269                 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
270                         q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
271                                 intval(CONTACT_IS_FRIEND),
272                                 intval($contact['id']),
273                                 intval($importer['uid'])
274                         );
275                 }
276                 // send notification?
277                 return;
278         }
279         
280         require_once('include/Scrape.php');
281         $ret = probe_url($sender_handle);
282
283         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
284                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
285                 return;
286         }
287
288         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
289                 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
290                 intval($importer['uid']),
291                 dbesc($ret['network']),
292                 dbesc($ret['addr']),
293                 datetime_convert(),
294                 dbesc($ret['url']),
295                 dbesc($ret['name']),
296                 dbesc($ret['nick']),
297                 dbesc($ret['photo']),
298                 dbesc($ret['pubkey']),
299                 dbesc($ret['notify']),
300                 dbesc($ret['poll']),
301                 1,
302                 2
303         );
304                  
305         // find the contact record we just created
306         $contact_record = null;
307         if($r) {        
308                 $r = q("SELECT `id` FROM `contact` 
309                                 WHERE `uid` = %d AND `addr` = '%s' AND `poll` = '%s' LIMIT 1",
310                                 intval($importer['uid']),
311                                 $ret['addr'],
312                                 $ret['poll']
313                 );
314                 if(count($r)) 
315                         $contact_record = $r[0];
316         }
317
318         $hash = random_string() . (string) time();   // Generate a confirm_key
319         
320         if(is_array($contact_record)) {
321                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`,`blocked`)
322                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s', 0 )",
323                         intval($importer['uid']),
324                         intval($contact_record['id']),
325                         0,
326                         dbesc( t('Sharing notification from Diaspora network')),
327                         dbesc($hash),
328                         dbesc(datetime_convert())
329                 );
330         }
331         
332
333         return;
334
335 }
336
337 function diaspora_post($importer,$xml) {
338
339         $guid = notags(unxmlify($xml->guid));
340         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
341
342         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
343         if(! $contact)
344                 return;
345
346         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
347                 logger('diaspora_post: Ignoring this author.');
348                 http_status_exit(202);
349                 // NOTREACHED
350         }
351
352         $message_id = $diaspora_handle . ':' . $guid;
353         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
354                 intval($importer['uid']),
355                 dbesc($message_id),
356                 dbesc($guid)
357         );
358         if(count($r))
359                 return;
360
361     // allocate a guid on our system - we aren't fixing any collisions.
362         // we're ignoring them
363
364         $g = q("select * from guid where guid = '%s' limit 1",
365                 dbesc($guid)
366         );
367         if(! count($g)) {
368                 q("insert into guid ( guid ) values ( '%s' )",
369                         dbesc($guid)
370                 );
371         }
372
373
374         $created = unxmlify($xml->created_at);
375         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
376
377         $body = unxmlify($xml->raw_message);
378
379         require_once('library/HTMLPurifier.auto.php');
380         require_once('include/html2bbcode.php');
381
382         $maxlen = get_max_import_size();
383         if($maxlen && (strlen($body) > $maxlen))
384                 $body = substr($body,0, $maxlen);
385
386         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
387
388                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
389                         '[youtube]$1[/youtube]', $body);
390
391                 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
392                         '[youtube]$1[/youtube]', $body);
393
394                 $body = oembed_html2bbcode($body);
395
396                 $config = HTMLPurifier_Config::createDefault();
397                 $config->set('Cache.DefinitionImpl', null);
398                 $purifier = new HTMLPurifier($config);
399                 $body = $purifier->purify($body);
400
401                 $body = html2bbcode($body);
402         }
403
404         $datarray = array();
405         $datarray['uid'] = $importer['uid'];
406         $datarray['contact-id'] = $contact['id'];
407         $datarray['wall'] = 0;
408         $datarray['guid'] = $guid;
409         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
410         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
411         $datarray['private'] = $private;
412         $datarray['parent'] = 0;
413         $datarray['owner-name'] = $contact['name'];
414         $datarray['owner-link'] = $contact['url'];
415         $datarray['owner-avatar'] = $contact['thumb'];
416         $datarray['author-name'] = $contact['name'];
417         $datarray['author-link'] = $contact['url'];
418         $datarray['author-avatar'] = $contact['thumb'];
419         $datarray['body'] = $body;
420
421         item_store($datarray);
422
423         return;
424
425
426 }
427
428 function diaspora_comment($importer,$xml) {
429         $guid = notags(unxmlify($xml->guid));
430         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
431
432
433         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
434         if(! $contact)
435                 return;
436
437         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
438                 logger('diaspora_comment: Ignoring this author.');
439                 http_status_exit(202);
440                 // NOTREACHED
441         }
442
443
444
445         $message_id = $diaspora_handle . ':' . $guid;
446         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
447                 intval($importer['uid']),
448                 dbesc($message_id),
449                 dbesc($guid)
450         );
451         if(count($r))
452                 return;
453
454         $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
455                 intval($importer['uid'])
456         );
457         if(! count($owner))
458                 return;
459
460         $created = unxmlify($xml->created_at);
461         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
462
463 }
464
465 function diaspora_like($importer,$xml) {
466
467         $guid = notags(unxmlify($xml->guid));
468         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
469
470
471         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
472         if(! $contact)
473                 return;
474
475         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
476                 logger('diaspora_like: Ignoring this author.');
477                 http_status_exit(202);
478                 // NOTREACHED
479         }
480
481
482         $message_id = $diaspora_handle . ':' . $guid;
483         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
484                 intval($importer['uid']),
485                 dbesc($message_id),
486                 dbesc($guid)
487         );
488         if(count($r))
489                 return;
490
491         $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
492                 intval($importer['uid'])
493         );
494         if(! count($owner))
495                 return;
496
497         $created = unxmlify($xml->created_at);
498         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
499
500         $uri = item_new_uri($a->get_hostname(),$owner_uid);
501
502         $post_type = (($item['resource-id']) ? t('photo') : t('status'));
503         $objtype = (($item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
504         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id'] . '" />' . "\n") ;
505         $body = $item['body'];
506
507         $obj = <<< EOT
508
509         <object>
510                 <type>$objtype</type>
511                 <local>1</local>
512                 <id>{$item['uri']}</id>
513                 <link>$link</link>
514                 <title></title>
515                 <content>$body</content>
516         </object>
517 EOT;
518         if($verb === 'like')
519                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
520         if($verb === 'dislike')
521                 $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
522
523         if(! isset($bodyverb))
524                         return; 
525
526         $arr = array();
527
528         $arr['uri'] = $uri;
529         $arr['uid'] = $owner_uid;
530         $arr['contact-id'] = $contact['id'];
531         $arr['type'] = 'activity';
532         $arr['wall'] = 1;
533         $arr['gravity'] = GRAVITY_LIKE;
534         $arr['parent'] = $item['id'];
535         $arr['parent-uri'] = $item['uri'];
536         $arr['owner-name'] = $owner['name'];
537         $arr['owner-link'] = $owner['url'];
538         $arr['owner-avatar'] = $owner['thumb'];
539         $arr['author-name'] = $contact['name'];
540         $arr['author-link'] = $contact['url'];
541         $arr['author-avatar'] = $contact['thumb'];
542         
543         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
544         $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
545         $plink = '[url=' . $a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
546         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
547
548         $arr['verb'] = $activity;
549         $arr['object-type'] = $objtype;
550         $arr['object'] = $obj;
551         $arr['allow_cid'] = $item['allow_cid'];
552         $arr['allow_gid'] = $item['allow_gid'];
553         $arr['deny_cid'] = $item['deny_cid'];
554         $arr['deny_gid'] = $item['deny_gid'];
555         $arr['visible'] = 1;
556         $arr['unseen'] = 1;
557         $arr['last-child'] = 0;
558
559         $post_id = item_store($arr);    
560
561         if(! $item['visible']) {
562                 $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
563                         intval($item['id']),
564                         intval($owner_uid)
565                 );
566         }                       
567
568         $arr['id'] = $post_id;
569
570
571
572 }
573
574 function diaspora_retraction($importer,$xml) {
575
576         $guid = notags(unxmlify($xml->guid));
577         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
578
579         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
580         if(! $contact)
581                 return;
582
583 //      if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
584 //              logger('diaspora_retraction: Ignoring this author.');
585 //              http_status_exit(202);
586 //              // NOTREACHED
587 //      }
588
589
590
591 }
592
593 function diaspora_share($me,$contact) {
594         $a = get_app();
595         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
596         $theiraddr = $contact['addr'];
597
598         $tpl = get_markup_template('diaspora_share.tpl');
599         $msg = replace_macros($tpl, array(
600                 '$sender' => myaddr,
601                 '$recipient' => $theiraddr
602         ));
603
604         $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
605
606         post_url($contact['notify'],$slap);
607         $return_code = $a->get_curl_code();
608         return $return_code;
609 }
610
611 function diaspora_send_status($item,$owner,$contact) {
612
613         $a = get_app();
614         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
615         $theiraddr = $contact['addr'];
616         require_once('include/bbcode.php');
617
618         $body = xmlify(bbcode($item['body']));
619         $public = (($item['private']) ? 'false' : 'true');
620
621         require_once('include/datetime.php');
622         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
623
624         $tpl = get_markup_template('diaspora_post.tpl');
625         $msg = replace_macros($tpl, array(
626                 '$body' => $body,
627                 '$guid' => $item['guid'],
628                 '$handle' => xmlify($myaddr),
629                 '$public' => $public,
630                 '$created' => $created
631         ));
632
633         logger('diaspora_send_status: base message: ' . $msg, LOGGER_DATA);
634
635         $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey']));
636
637         post_url($contact['notify'],$slap);
638         $return_code = $a->get_curl_code();
639         logger('diaspora_send_status: returns: ' . $return_code);
640         return $return_code;
641 }
642