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
226 $key = get_diaspora_key($author_link);
229 logger('mod-diaspora: Could not retrieve author key.');
230 http_status_exit(400);
233 $verify = rsa_verify($signed_data,$signature,$key);
236 logger('mod-diaspora: Message did not verify. Discarding.');
237 http_status_exit(400);
240 logger('mod-diaspora: Message verified.');
242 return $inner_decrypted;
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),
258 function diaspora_request($importer,$xml) {
260 $sender_handle = $xml->sender_handle;
261 $recipient_handle = $xml->recipient_handle;
263 if(! $sender_handle || ! $recipient_handle)
266 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
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'])
276 // send notification?
280 require_once('include/Scrape.php');
281 $ret = probe_url($sender_handle);
283 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
284 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
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']),
297 dbesc($ret['photo']),
298 dbesc($ret['pubkey']),
299 dbesc($ret['notify']),
305 // find the contact record we just created
306 $contact_record = null;
308 $r = q("SELECT `id` FROM `contact`
309 WHERE `uid` = %d AND `addr` = '%s' AND `poll` = '%s' LIMIT 1",
310 intval($importer['uid']),
315 $contact_record = $r[0];
318 $hash = random_string() . (string) time(); // Generate a confirm_key
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']),
326 dbesc( t('Sharing notification from Diaspora network')),
328 dbesc(datetime_convert())
337 function diaspora_post($importer,$xml) {
339 $guid = notags(unxmlify($xml->guid));
340 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
342 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
346 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
347 logger('diaspora_post: Ignoring this author.');
348 http_status_exit(202);
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']),
361 // allocate a guid on our system - we aren't fixing any collisions.
362 // we're ignoring them
364 $g = q("select * from guid where guid = '%s' limit 1",
368 q("insert into guid ( guid ) values ( '%s' )",
374 $created = unxmlify($xml->created_at);
375 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
377 $body = unxmlify($xml->raw_message);
379 require_once('library/HTMLPurifier.auto.php');
380 require_once('include/html2bbcode.php');
382 $maxlen = get_max_import_size();
383 if($maxlen && (strlen($body) > $maxlen))
384 $body = substr($body,0, $maxlen);
386 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
388 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
389 '[youtube]$1[/youtube]', $body);
391 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
392 '[youtube]$1[/youtube]', $body);
394 $body = oembed_html2bbcode($body);
396 $config = HTMLPurifier_Config::createDefault();
397 $config->set('Cache.DefinitionImpl', null);
398 $purifier = new HTMLPurifier($config);
399 $body = $purifier->purify($body);
401 $body = html2bbcode($body);
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;
421 item_store($datarray);
428 function diaspora_comment($importer,$xml) {
429 $guid = notags(unxmlify($xml->guid));
430 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
433 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
437 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
438 logger('diaspora_comment: Ignoring this author.');
439 http_status_exit(202);
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']),
454 $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
455 intval($importer['uid'])
460 $created = unxmlify($xml->created_at);
461 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
465 function diaspora_like($importer,$xml) {
467 $guid = notags(unxmlify($xml->guid));
468 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
471 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
475 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
476 logger('diaspora_like: Ignoring this author.');
477 http_status_exit(202);
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']),
491 $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
492 intval($importer['uid'])
497 $created = unxmlify($xml->created_at);
498 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
500 $uri = item_new_uri($a->get_hostname(),$owner_uid);
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'];
510 <type>$objtype</type>
512 <id>{$item['uri']}</id>
515 <content>$body</content>
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');
523 if(! isset($bodyverb))
529 $arr['uid'] = $owner_uid;
530 $arr['contact-id'] = $contact['id'];
531 $arr['type'] = 'activity';
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'];
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 );
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'];
557 $arr['last-child'] = 0;
559 $post_id = item_store($arr);
561 if(! $item['visible']) {
562 $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
568 $arr['id'] = $post_id;
574 function diaspora_retraction($importer,$xml) {
576 $guid = notags(unxmlify($xml->guid));
577 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
579 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
583 // if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
584 // logger('diaspora_retraction: Ignoring this author.');
585 // http_status_exit(202);
593 function diaspora_share($me,$contact) {
595 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
596 $theiraddr = $contact['addr'];
598 $tpl = get_markup_template('diaspora_share.tpl');
599 $msg = replace_macros($tpl, array(
601 '$recipient' => $theiraddr
604 $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
606 post_url($contact['notify'],$slap);
607 $return_code = $a->get_curl_code();
611 function diaspora_send_status($item,$owner,$contact) {
614 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
615 $theiraddr = $contact['addr'];
616 require_once('include/bbcode.php');
618 $body = xmlify(bbcode($item['body']));
619 $public = (($item['private']) ? 'false' : 'true');
621 require_once('include/datetime.php');
622 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
624 $tpl = get_markup_template('diaspora_post.tpl');
625 $msg = replace_macros($tpl, array(
627 '$guid' => $item['guid'],
628 '$handle' => xmlify($myaddr),
629 '$public' => $public,
630 '$created' => $created
633 logger('diaspora_send_status: base message: ' . $msg, LOGGER_DATA);
635 $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey']));
637 post_url($contact['notify'],$slap);
638 $return_code = $a->get_curl_code();
639 logger('diaspora_send_status: returns: ' . $return_code);