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