]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
typos
[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'] = $datarray['parent-uri'] = $message_id;
385         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
386         $datarray['private'] = $private;
387         $datarray['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         $datarray['body'] = $body;
395
396         item_store($datarray);
397
398         return;
399
400
401 }
402
403 function diaspora_comment($importer,$contact,$xml) {
404         $guid = notags(unxmlify($xml->guid));
405         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
406         $message_id = $diaspora_handle . ':' . $guid;
407         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
408                 intval($importer['uid']),
409                 dbesc($message_id),
410                 dbesc($guid)
411         );
412         if(count($r))
413                 return;
414
415         $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
416                 intval($importer['uid'])
417         );
418         if(! count($owner))
419                 return;
420
421         $created = unxmlify($xml->created_at);
422         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
423
424 }
425
426 function diaspora_like($importer,$contact,$xml) {
427
428         $guid = notags(unxmlify($xml->guid));
429         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
430         $message_id = $diaspora_handle . ':' . $guid;
431         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
432                 intval($importer['uid']),
433                 dbesc($message_id),
434                 dbesc($guid)
435         );
436         if(count($r))
437                 return;
438
439         $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
440                 intval($importer['uid'])
441         );
442         if(! count($owner))
443                 return;
444
445         $created = unxmlify($xml->created_at);
446         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
447
448         $uri = item_new_uri($a->get_hostname(),$owner_uid);
449
450         $post_type = (($item['resource-id']) ? t('photo') : t('status'));
451         $objtype = (($item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
452         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id'] . '" />' . "\n") ;
453         $body = $item['body'];
454
455         $obj = <<< EOT
456
457         <object>
458                 <type>$objtype</type>
459                 <local>1</local>
460                 <id>{$item['uri']}</id>
461                 <link>$link</link>
462                 <title></title>
463                 <content>$body</content>
464         </object>
465 EOT;
466         if($verb === 'like')
467                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
468         if($verb === 'dislike')
469                 $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
470
471         if(! isset($bodyverb))
472                         return; 
473
474         $arr = array();
475
476         $arr['uri'] = $uri;
477         $arr['uid'] = $owner_uid;
478         $arr['contact-id'] = $contact['id'];
479         $arr['type'] = 'activity';
480         $arr['wall'] = 1;
481         $arr['gravity'] = GRAVITY_LIKE;
482         $arr['parent'] = $item['id'];
483         $arr['parent-uri'] = $item['uri'];
484         $arr['owner-name'] = $owner['name'];
485         $arr['owner-link'] = $owner['url'];
486         $arr['owner-avatar'] = $owner['thumb'];
487         $arr['author-name'] = $contact['name'];
488         $arr['author-link'] = $contact['url'];
489         $arr['author-avatar'] = $contact['thumb'];
490         
491         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
492         $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
493         $plink = '[url=' . $a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
494         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
495
496         $arr['verb'] = $activity;
497         $arr['object-type'] = $objtype;
498         $arr['object'] = $obj;
499         $arr['allow_cid'] = $item['allow_cid'];
500         $arr['allow_gid'] = $item['allow_gid'];
501         $arr['deny_cid'] = $item['deny_cid'];
502         $arr['deny_gid'] = $item['deny_gid'];
503         $arr['visible'] = 1;
504         $arr['unseen'] = 1;
505         $arr['last-child'] = 0;
506
507         $post_id = item_store($arr);    
508
509         if(! $item['visible']) {
510                 $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
511                         intval($item['id']),
512                         intval($owner_uid)
513                 );
514         }                       
515
516         $arr['id'] = $post_id;
517
518
519
520 }
521
522 function diaspora_retraction($importer,$contact,$xml) {
523
524 }
525
526 function diaspora_share($me,$contact) {
527         $a = get_app();
528         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
529         $theiraddr = $contact['addr'];
530
531         $tpl = get_markup_template('diaspora_share.tpl');
532         $msg = replace_macros($tpl, array(
533                 '$sender' => myaddr,
534                 '$recipient' => $theiraddr
535         ));
536
537         $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
538
539         post_url($contact['notify'],$slap);
540         $return_code = $a->get_curl_code();
541         return $return_code;
542 }
543
544 function diaspora_send_status($item,$owner,$contact) {
545
546         $a = get_app();
547         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
548         $theiraddr = $contact['addr'];
549         require_once('include/bbcode.php');
550
551         $body = xmlify(bbcode($item['body']));
552         $public = (($item['private']) ? 'false' : 'true');
553
554         require_once('include/datetime.php');
555         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
556
557         $tpl = get_markup_template('diaspora_post.tpl');
558         $msg = replace_macros($tpl, array(
559                 '$body' => $body,
560                 '$guid' => $item['guid'],
561                 '$handle' => xmlify($myaddr),
562                 '$public' => $public,
563                 '$created' => $created
564         ));
565
566         logger('diaspora_send_status: base message: ' . $msg, LOGGER_DATA);
567
568         $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey']));
569
570         post_url($contact['notify'],$slap);
571         $return_code = $a->get_curl_code();
572         logger('diaspora_send_status: returns: ' . $return_code);
573         return $return_code;
574 }
575