]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
dd0debe69ae2fd01b61c2ea658c0529f8dbe3f36
[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
120
121         $basedom = parse_xml_string($xml);
122
123         $atom = $basedom->children(NAMESPACE_ATOM1);
124
125         $encrypted_header = json_decode(base64_decode($atom->encrypted_header));
126         
127         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
128         $ciphertext = base64_decode($encrypted_header->ciphertext);
129
130         $outer_key_bundle = '';
131         openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
132
133         $j_outer_key_bundle = json_decode($outer_key_bundle);
134
135         $outer_iv = base64_decode($j_outer_key_bundle->iv);
136         $outer_key = base64_decode($j_outer_key_bundle->key);
137
138         $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
139
140         $decrypted = pkcs5_unpad($decrypted);
141
142         /**
143          * $decrypted now contains something like
144          *
145          *  <decrypted_header>
146          *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
147          *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
148          *     <author>
149          *       <name>Ryan Hughes</name>
150          *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
151          *     </author>
152          *  </decrypted_header>
153          */
154
155         logger('decrypted: ' . $decrypted);
156         $idom = parse_xml_string($decrypted,false);
157
158         $inner_iv = base64_decode($idom->iv);
159         $inner_aes_key = base64_decode($idom->aes_key);
160
161         $author_link = str_replace('acct:','',$idom->author->uri);
162
163         $dom = $basedom->children(NAMESPACE_SALMON_ME);
164
165         // figure out where in the DOM tree our data is hiding
166
167         if($dom->provenance->data)
168                 $base = $dom->provenance;
169         elseif($dom->env->data)
170                 $base = $dom->env;
171         elseif($dom->data)
172                 $base = $dom;
173         
174         if(! $base) {
175                 logger('mod-diaspora: unable to locate salmon data in xml ');
176                 http_status_exit(400);
177         }
178
179
180         // Stash the signature away for now. We have to find their key or it won't be good for anything.
181         $signature = base64url_decode($base->sig);
182
183         // unpack the  data
184
185         // strip whitespace so our data element will return to one big base64 blob
186         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
187         // Add back the 60 char linefeeds
188     $lines = str_split($data,60);
189     $data = implode("\n",$lines);
190
191
192         // stash away some other stuff for later
193
194         $type = $base->data[0]->attributes()->type[0];
195         $keyhash = $base->sig[0]->attributes()->keyhash[0];
196         $encoding = $base->encoding;
197         $alg = $base->alg;
198
199         $signed_data = $data  . (($data[-1] != "\n") ? "\n" : '') . '.' . base64url_encode($type) . "\n" . '.' . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
200
201
202         // decode the data
203         $data = base64url_decode($data);
204
205         // Now pull out the inner encrypted blob
206
207         $inner_encrypted = base64_decode($data);
208
209         $inner_decrypted = 
210         $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
211
212         $inner_decrypted = pkcs5_unpad($inner_decrypted);
213
214         if(! $author_link) {
215                 logger('mod-diaspora: Could not retrieve author URI.');
216                 http_status_exit(400);
217         }
218
219         // Once we have the author URI, go to the web and try to find their public key
220         // *** or look it up locally ***
221
222         logger('mod-diaspora: Fetching key for ' . $author_link );
223
224         // Get diaspora public key (pkcs#1) and convert to pkcs#8
225         $key = get_diaspora_key($author_link);
226
227         if(! $key) {
228                 logger('mod-diaspora: Could not retrieve author key.');
229                 http_status_exit(400);
230         }
231
232         $verify = rsa_verify($signed_data,$signature,$key);
233
234         if(! $verify) {
235                 logger('mod-diaspora: Message did not verify. Discarding.');
236                 http_status_exit(400);
237         }
238
239         logger('mod-diaspora: Message verified.');
240
241         return $inner_decrypted;
242
243 }
244
245
246
247
248 function diaspora_request($importer,$contact,$xml) {
249
250         $sender_handle = $xml->sender_handle;
251         $recipient_handle = $xml->recipient_handle;
252
253         if(! $sender_handle || ! $recipient_handle)
254                 return;
255         
256         if($contact && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) {
257                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
258                         intval(CONTACT_IS_FRIEND),
259                         intval($contact['id']),
260                         intval($importer['uid'])
261                 );
262                 // send notification
263                 return;
264         }
265         
266         require_once('include/Scrape.php');
267         $ret = probe_url($sender_handle);
268
269         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
270                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
271                 return;
272         }
273
274         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
275                 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
276                 intval($importer['uid']),
277                 dbesc($ret['network']),
278                 dbesc($ret['addr']),
279                 datetime_convert(),
280                 dbesc($ret['url']),
281                 dbesc($ret['name']),
282                 dbesc($ret['nick']),
283                 dbesc($ret['photo']),
284                 dbesc($ret['pubkey']),
285                 dbesc($ret['notify']),
286                 dbesc($ret['poll']),
287                 1,
288                 2
289         );
290                  
291         // find the contact record we just created
292         $contact_record = null;
293         if($r) {        
294                 $r = q("SELECT `id` FROM `contact` 
295                                 WHERE `uid` = %d AND `addr` = '%s' AND `poll` = '%s' LIMIT 1",
296                                 intval($importer['uid']),
297                                 $ret['addr'],
298                                 $ret['poll']
299                 );
300                 if(count($r)) 
301                         $contact_record = $r[0];
302         }
303
304         $hash = random_string() . (string) time();   // Generate a confirm_key
305         
306         if(is_array($contact_record)) {
307                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`,`blocked`)
308                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s', 0 )",
309                         intval($importer['uid']),
310                         intval($contact_record['id']),
311                         0,
312                         dbesc( t('Sharing notification from Diaspora network')),
313                         dbesc($hash),
314                         dbesc(datetime_convert())
315                 );
316         }
317         
318
319         return;
320
321 }
322
323 function diaspora_post($importer,$contact,$xml) {
324
325         $guid = notags(unxmlify($xml->guid));
326         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
327         $message_id = $diaspora_handle . ':' . $guid;
328         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
329                 intval($importer['uid']),
330                 dbesc($message_id),
331                 dbesc($guid)
332         );
333         if(count($r))
334                 return;
335
336     // allocate a guid on our system - we aren't fixing any collisions.
337         // we're ignoring them
338
339         $g = q("select * from guid where guid = '%s' limit 1",
340                 dbesc($guid)
341         );
342         if(! count($g)) {
343                 q("insert into guid ( guid ) values ( '%s' )",
344                         dbesc($guid)
345                 );
346         }
347
348
349         $created = unxmlify($xml->created_at);
350         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
351
352         $body = unxmlify($xml->raw_message);
353
354         require_once('library/HTMLPurifier.auto.php');
355         require_once('include/html2bbcode.php');
356
357         $maxlen = get_max_import_size();
358         if($maxlen && (strlen($body) > $maxlen))
359                 $body = substr($body,0, $maxlen);
360
361         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
362
363                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
364                         '[youtube]$1[/youtube]', $body);
365
366                 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
367                         '[youtube]$1[/youtube]', $body);
368
369                 $body = oembed_html2bbcode($body);
370
371                 $config = HTMLPurifier_Config::createDefault();
372                 $config->set('Cache.DefinitionImpl', null);
373                 $purifier = new HTMLPurifier($config);
374                 $body = $purifier->purify($body);
375
376                 $body = html2bbcode($body);
377         }
378
379         $datarray = array();
380         $datarray['uid'] = $importer['uid'];
381         $datarray['contact-id'] = $contact['id'];
382         $datarray['wall'] = 0;
383         $datarray['guid'] = $guid;
384         $datarray['uri'] = $message_id;
385         $dattarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
386         $dattarray['private'] = $private;
387         $dattarray['parent'] = 0;
388         $datarray['owner-name'] = $contact['name'];
389         $datarray['owner-link'] = $contact['url'];
390         $datarray['owner-avatar'] = $contact['thumb'];
391         $datarray['author-name'] = $contact['name'];
392         $datarray['author-link'] = $contact['url'];
393         $datarray['author-avatar'] = $contact['thumb'];
394
395         item_store($datarray);
396
397         return;
398
399
400 }
401
402 function diaspora_comment($importer,$contact,$xml) {
403         $guid = notags(unxmlify($xml->guid));
404         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
405         $message_id = $diaspora_handle . ':' . $guid;
406         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
407                 intval($importer['uid']),
408                 dbesc($message_id),
409                 dbesc($guid)
410         );
411         if(count($r))
412                 return;
413
414         $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
415                 intval($importer['uid'])
416         );
417         if(! count($owner))
418                 return;
419
420         $created = unxmlify($xml->created_at);
421         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
422
423 }
424
425 function diaspora_like($importer,$contact,$xml) {
426
427         $guid = notags(unxmlify($xml->guid));
428         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
429         $message_id = $diaspora_handle . ':' . $guid;
430         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
431                 intval($importer['uid']),
432                 dbesc($message_id),
433                 dbesc($guid)
434         );
435         if(count($r))
436                 return;
437
438         $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
439                 intval($importer['uid'])
440         );
441         if(! count($owner))
442                 return;
443
444         $created = unxmlify($xml->created_at);
445         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
446
447         $uri = item_new_uri($a->get_hostname(),$owner_uid);
448
449         $post_type = (($item['resource-id']) ? t('photo') : t('status'));
450         $objtype = (($item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
451         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id'] . '" />' . "\n") ;
452         $body = $item['body'];
453
454         $obj = <<< EOT
455
456         <object>
457                 <type>$objtype</type>
458                 <local>1</local>
459                 <id>{$item['uri']}</id>
460                 <link>$link</link>
461                 <title></title>
462                 <content>$body</content>
463         </object>
464 EOT;
465         if($verb === 'like')
466                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
467         if($verb === 'dislike')
468                 $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
469
470         if(! isset($bodyverb))
471                         return; 
472
473         $arr = array();
474
475         $arr['uri'] = $uri;
476         $arr['uid'] = $owner_uid;
477         $arr['contact-id'] = $contact['id'];
478         $arr['type'] = 'activity';
479         $arr['wall'] = 1;
480         $arr['gravity'] = GRAVITY_LIKE;
481         $arr['parent'] = $item['id'];
482         $arr['parent-uri'] = $item['uri'];
483         $arr['owner-name'] = $owner['name'];
484         $arr['owner-link'] = $owner['url'];
485         $arr['owner-avatar'] = $owner['thumb'];
486         $arr['author-name'] = $contact['name'];
487         $arr['author-link'] = $contact['url'];
488         $arr['author-avatar'] = $contact['thumb'];
489         
490         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
491         $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
492         $plink = '[url=' . $a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
493         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
494
495         $arr['verb'] = $activity;
496         $arr['object-type'] = $objtype;
497         $arr['object'] = $obj;
498         $arr['allow_cid'] = $item['allow_cid'];
499         $arr['allow_gid'] = $item['allow_gid'];
500         $arr['deny_cid'] = $item['deny_cid'];
501         $arr['deny_gid'] = $item['deny_gid'];
502         $arr['visible'] = 1;
503         $arr['unseen'] = 1;
504         $arr['last-child'] = 0;
505
506         $post_id = item_store($arr);    
507
508         if(! $item['visible']) {
509                 $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
510                         intval($item['id']),
511                         intval($owner_uid)
512                 );
513         }                       
514
515         $arr['id'] = $post_id;
516
517
518
519 }
520
521 function diaspora_retraction($importer,$contact,$xml) {
522
523 }
524
525 function diaspora_share($me,$contact) {
526         $a = get_app();
527         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
528         $theiraddr = $contact['addr'];
529
530         $tpl = get_markup_template('diaspora_share.tpl');
531         $msg = replace_macros($tpl, array(
532                 '$sender' => myaddr,
533                 '$recipient' => $theiraddr
534         ));
535
536         $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
537
538         post_url($contact['notify'],$slap);
539         $return_code = $a->get_curl_code();
540         return $return_code;
541 }
542
543 function diaspora_send_status($item,$owner,$contact) {
544
545         $a = get_app();
546         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
547         $theiraddr = $contact['addr'];
548         require_once('include/bbcode.php');
549
550         $body = xmlify(bbcode($item['body']));
551         $public = (($item['private']) ? 'false' : 'true');
552
553         require_once('include/datetime.php');
554         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
555
556         $tpl = get_markup_template('diaspora_post.tpl');
557         $msg = replace_macros($tpl, array(
558                 '$body' => $body,
559                 '$guid' => $item['guid'],
560                 '$handle' => xmlify($myaddr),
561                 '$public' => $public,
562                 '$created' => $created
563         ));
564
565         logger('diaspora_send_status: base message: ' . $msg, LOGGER_DATA);
566
567         $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey']));
568
569         post_url($contact['notify'],$slap);
570         $return_code = $a->get_curl_code();
571         logger('diaspora_send_status: returns: ' . $return_code);
572         return $return_code;
573 }
574