3 require_once('include/crypto.php');
4 require_once('include/items.php');
6 function get_diaspora_key($uri) {
9 logger('Fetching diaspora key for: ' . $uri);
15 if($a['@attributes']['rel'] === 'diaspora-public-key') {
16 $key = base64_decode($a['@attributes']['href']);
25 return rsatopem($key);
30 function diaspora_base_message($type,$data) {
32 $tpl = get_markup_template('diaspora_' . $type . '.tpl');
35 return replace_macros($tpl,$data);
40 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
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);
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);
53 $handle = 'acct:' . $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
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);
58 $b64_data = base64_encode($inner_encrypted);
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';
70 $signable_data = $data . '.' . base64url_encode($type) . "\n" . '.'
71 . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
73 $signature = rsa_sign($signable_data,$prvkey);
74 $sig = base64url_encode($signature);
76 $decrypted_header = <<< EOT
79 <aes_key>$b_inner_aes_key</aes_key>
81 <name>{$user['username']}</name>
87 $decrypted_header = pkcs5_pad($decrypted_header,16);
89 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
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);
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>';
101 <?xml version='1.0' encoding='UTF-8'?>
102 <entry xmlns='http://www.w3.org/2005/Atom'>
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>
118 function diaspora_decode($importer,$xml) {
122 $basedom = parse_xml_string($xml);
124 $atom = $basedom->children(NAMESPACE_ATOM1);
126 $encrypted_header = json_decode(base64_decode($atom->encrypted_header));
128 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
129 $ciphertext = base64_decode($encrypted_header->ciphertext);
131 $outer_key_bundle = '';
132 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
134 $j_outer_key_bundle = json_decode($outer_key_bundle);
136 $outer_iv = base64_decode($j_outer_key_bundle->iv);
137 $outer_key = base64_decode($j_outer_key_bundle->key);
139 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
141 $decrypted = pkcs5_unpad($decrypted);
144 * $decrypted now contains something like
147 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
148 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
150 * <name>Ryan Hughes</name>
151 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
153 * </decrypted_header>
156 logger('decrypted: ' . $decrypted);
157 $idom = parse_xml_string($decrypted,false);
159 $inner_iv = base64_decode($idom->iv);
160 $inner_aes_key = base64_decode($idom->aes_key);
162 $author_link = str_replace('acct:','',$idom->author->uri);
164 $dom = $basedom->children(NAMESPACE_SALMON_ME);
166 // figure out where in the DOM tree our data is hiding
168 if($dom->provenance->data)
169 $base = $dom->provenance;
170 elseif($dom->env->data)
176 logger('mod-diaspora: unable to locate salmon data in xml ');
177 http_status_exit(400);
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);
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);
193 // stash away some other stuff for later
195 $type = $base->data[0]->attributes()->type[0];
196 $keyhash = $base->sig[0]->attributes()->keyhash[0];
197 $encoding = $base->encoding;
200 $signed_data = $data . (($data[-1] != "\n") ? "\n" : '') . '.' . base64url_encode($type) . "\n" . '.' . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
204 $data = base64url_decode($data);
206 // Now pull out the inner encrypted blob
208 $inner_encrypted = base64_decode($data);
211 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
213 $inner_decrypted = pkcs5_unpad($inner_decrypted);
216 logger('mod-diaspora: Could not retrieve author URI.');
217 http_status_exit(400);
220 // Once we have the author URI, go to the web and try to find their public key
221 // *** or look it up locally ***
223 logger('mod-diaspora: Fetching key for ' . $author_link );
225 // Get diaspora public key (pkcs#1) and convert to pkcs#8
227 $key = get_diaspora_key($author_link);
230 logger('mod-diaspora: Could not retrieve author key.');
231 http_status_exit(400);
234 $verify = rsa_verify($signed_data,$signature,$key);
237 logger('mod-diaspora: Message did not verify. Discarding.');
238 http_status_exit(400);
241 logger('mod-diaspora: Message verified.');
243 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
247 function diaspora_get_contact_by_handle($uid,$handle) {
248 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
249 dbesc(NETWORK_DIASPORA),
259 function diaspora_request($importer,$xml) {
261 $sender_handle = unxmlify($xml->sender_handle);
262 $recipient_handle = unxmlify($xml->recipient_handle);
264 if(! $sender_handle || ! $recipient_handle)
267 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
270 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
271 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
272 intval(CONTACT_IS_FRIEND),
273 intval($contact['id']),
274 intval($importer['uid'])
277 // send notification?
281 require_once('include/Scrape.php');
282 $ret = probe_url($sender_handle);
284 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
285 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
289 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
290 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
291 intval($importer['uid']),
292 dbesc($ret['network']),
298 dbesc($ret['photo']),
299 dbesc($ret['pubkey']),
300 dbesc($ret['notify']),
306 // find the contact record we just created
308 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
310 $hash = random_string() . (string) time(); // Generate a confirm_key
312 if($contact_record) {
313 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`,`blocked`)
314 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s', 0 )",
315 intval($importer['uid']),
316 intval($contact_record['id']),
318 dbesc( t('Sharing notification from Diaspora network')),
320 dbesc(datetime_convert())
327 function diaspora_post($importer,$xml) {
329 $guid = notags(unxmlify($xml->guid));
330 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
332 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
336 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
337 logger('diaspora_post: Ignoring this author.');
338 http_status_exit(202);
342 $message_id = $diaspora_handle . ':' . $guid;
343 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
344 intval($importer['uid']),
351 // allocate a guid on our system - we aren't fixing any collisions.
352 // we're ignoring them
354 $g = q("select * from guid where guid = '%s' limit 1",
358 q("insert into guid ( guid ) values ( '%s' )",
363 $created = unxmlify($xml->created_at);
364 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
366 $body = unxmlify($xml->raw_message);
368 require_once('library/HTMLPurifier.auto.php');
369 require_once('include/html2bbcode.php');
371 $maxlen = get_max_import_size();
372 if($maxlen && (strlen($body) > $maxlen))
373 $body = substr($body,0, $maxlen);
375 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
377 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
378 '[youtube]$1[/youtube]', $body);
380 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
381 '[youtube]$1[/youtube]', $body);
383 $body = oembed_html2bbcode($body);
385 $config = HTMLPurifier_Config::createDefault();
386 $config->set('Cache.DefinitionImpl', null);
387 $purifier = new HTMLPurifier($config);
388 $body = $purifier->purify($body);
390 $body = html2bbcode($body);
394 $datarray['uid'] = $importer['uid'];
395 $datarray['contact-id'] = $contact['id'];
396 $datarray['wall'] = 0;
397 $datarray['guid'] = $guid;
398 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
399 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
400 $datarray['private'] = $private;
401 $datarray['parent'] = 0;
402 $datarray['owner-name'] = $contact['name'];
403 $datarray['owner-link'] = $contact['url'];
404 $datarray['owner-avatar'] = $contact['thumb'];
405 $datarray['author-name'] = $contact['name'];
406 $datarray['author-link'] = $contact['url'];
407 $datarray['author-avatar'] = $contact['thumb'];
408 $datarray['body'] = $body;
410 item_store($datarray);
416 function diaspora_comment($importer,$xml,$msg) {
417 $guid = notags(unxmlify($xml->guid));
418 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
421 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
425 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
426 logger('diaspora_comment: Ignoring this author.');
427 http_status_exit(202);
433 $message_id = $diaspora_handle . ':' . $guid;
434 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
435 intval($importer['uid']),
441 $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
442 intval($importer['uid'])
447 $created = unxmlify($xml->created_at);
448 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
452 function diaspora_like($importer,$xml,$msg) {
454 $guid = notags(unxmlify($xml->guid));
455 $parent_guid = notags(unxmlify($xml->parent_guid));
456 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
457 $target_type = notags(unxmlify($xml->target_type));
458 $positive = notags(unxmlify($xml->positive));
460 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
462 // likes on comments not supported here
463 if($target_type !== 'Post')
466 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg->author);
470 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
471 logger('diaspora_like: Ignoring this author.');
472 http_status_exit(202);
476 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
477 intval($importer['uid']),
481 logger('diaspora_like: parent item not found: ' . $guid);
485 $parent_item = $r[0];
487 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '$s' LIMIT 1",
488 intval($importer['uid']),
492 if($positive === 'true') {
493 logger('diaspora_like: duplicate like: ' . $guid);
496 if($positive === 'false') {
497 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
499 intval($importer['uid'])
502 // send notification via proc_run()
506 if($positive === 'false') {
507 logger('diaspora_like: unlike received with no corresponding like');
511 $author_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $diaspora_handle;
513 $author_signature = base64_decode($author_signature);
515 if(stricmp($diaspora_handle,$msg['author']) == 0)
518 $key = get_diaspora_key($diaspora_handle);
520 if(! rsa_verify($author_signed_data,$author_signature,$key)) {
521 logger('diaspora_like: verification failed.');
525 if($parent_author_signature) {
526 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $msg['author'];
528 $parent_author_signature = base64_decode($parent_author_signature);
532 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key)) {
533 logger('diaspora_like: owner verification failed.');
538 // Phew! Everything checks out. Now create an item.
540 $uri = $diaspora_handle . ':' . $guid;
542 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
543 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
544 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
545 $body = $parent_item['body'];
550 <type>$objtype</type>
552 <id>{$parent_item['uri']}</id>
555 <content>$body</content>
558 $bodyverb = t('%1$s likes %2$s\'s %3$s');
563 $arr['uid'] = $importer['uid'];
564 $arr['contact-id'] = $contact['id'];
565 $arr['type'] = 'activity';
566 $arr['wall'] = $parent_item['wall'];
567 $arr['gravity'] = GRAVITY_LIKE;
568 $arr['parent'] = $parent_item['id'];
569 $arr['parent-uri'] = $parent_item['uri'];
571 // $arr['owner-name'] = $owner['name']; // FIXME
572 // $arr['owner-link'] = $owner['url'];
573 // $arr['owner-avatar'] = $owner['thumb'];
575 $arr['author-name'] = $contact['name'];
576 $arr['author-link'] = $contact['url'];
577 $arr['author-avatar'] = $contact['thumb'];
579 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
580 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
581 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
582 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
584 $arr['verb'] = $activity;
585 $arr['object-type'] = $objtype;
586 $arr['object'] = $obj;
587 $arr['allow_cid'] = $parent_item['allow_cid'];
588 $arr['allow_gid'] = $parent_item['allow_gid'];
589 $arr['deny_cid'] = $parent_item['deny_cid'];
590 $arr['deny_gid'] = $parent_item['deny_gid'];
593 $arr['last-child'] = 0;
595 $post_id = item_store($arr);
598 // FIXME send notification
603 function diaspora_retraction($importer,$xml) {
605 $guid = notags(unxmlify($xml->guid));
606 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
608 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
612 // if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
613 // logger('diaspora_retraction: Ignoring this author.');
614 // http_status_exit(202);
622 function diaspora_share($me,$contact) {
624 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
625 $theiraddr = $contact['addr'];
627 $tpl = get_markup_template('diaspora_share.tpl');
628 $msg = replace_macros($tpl, array(
630 '$recipient' => $theiraddr
633 $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
635 post_url($contact['notify'],$slap);
636 $return_code = $a->get_curl_code();
640 function diaspora_send_status($item,$owner,$contact) {
643 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
644 $theiraddr = $contact['addr'];
645 require_once('include/bbcode.php');
647 $body = xmlify(bbcode($item['body']));
648 $public = (($item['private']) ? 'false' : 'true');
650 require_once('include/datetime.php');
651 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
653 $tpl = get_markup_template('diaspora_post.tpl');
654 $msg = replace_macros($tpl, array(
656 '$guid' => $item['guid'],
657 '$handle' => xmlify($myaddr),
658 '$public' => $public,
659 '$created' => $created
662 logger('diaspora_send_status: base message: ' . $msg, LOGGER_DATA);
664 $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey']));
666 post_url($contact['notify'],$slap);
667 $return_code = $a->get_curl_code();
668 logger('diaspora_send_status: returns: ' . $return_code);