3 require_once('include/crypto.php');
5 function get_diaspora_key($uri) {
8 logger('Fetching diaspora key for: ' . $uri);
14 if($a['@attributes']['rel'] === 'diaspora-public-key') {
15 $key = base64_decode($a['@attributes']['href']);
24 return rsatopem($key);
29 function diaspora_base_message($type,$data) {
31 $tpl = get_markup_template('diaspora_' . $type . '.tpl');
34 return replace_macros($tpl,$data);
39 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
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);
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);
52 $handle = 'acct:' . $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
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);
57 $b64_data = base64_encode($inner_encrypted);
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';
69 $signable_data = $data . '.' . base64url_encode($type) . "\n" . '.'
70 . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
72 $signature = rsa_sign($signable_data,$prvkey);
73 $sig = base64url_encode($signature);
75 $decrypted_header = <<< EOT
78 <aes_key>$b_inner_aes_key</aes_key>
80 <name>{$user['username']}</name>
86 $decrypted_header = pkcs5_pad($decrypted_header,16);
88 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
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);
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>';
100 <?xml version='1.0' encoding='UTF-8'?>
101 <entry xmlns='http://www.w3.org/2005/Atom'>
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>
117 function diaspora_decode($importer,$xml) {
121 $basedom = parse_xml_string($xml);
123 $atom = $basedom->children(NAMESPACE_ATOM1);
125 $encrypted_header = json_decode(base64_decode($atom->encrypted_header));
127 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
128 $ciphertext = base64_decode($encrypted_header->ciphertext);
130 $outer_key_bundle = '';
131 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
133 $j_outer_key_bundle = json_decode($outer_key_bundle);
135 $outer_iv = base64_decode($j_outer_key_bundle->iv);
136 $outer_key = base64_decode($j_outer_key_bundle->key);
138 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
140 $decrypted = pkcs5_unpad($decrypted);
143 * $decrypted now contains something like
146 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
147 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
149 * <name>Ryan Hughes</name>
150 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
152 * </decrypted_header>
155 logger('decrypted: ' . $decrypted);
156 $idom = parse_xml_string($decrypted,false);
158 $inner_iv = base64_decode($idom->iv);
159 $inner_aes_key = base64_decode($idom->aes_key);
161 $author_link = str_replace('acct:','',$idom->author->uri);
163 $dom = $basedom->children(NAMESPACE_SALMON_ME);
165 // figure out where in the DOM tree our data is hiding
167 if($dom->provenance->data)
168 $base = $dom->provenance;
169 elseif($dom->env->data)
175 logger('mod-diaspora: unable to locate salmon data in xml ');
176 http_status_exit(400);
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);
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);
192 // stash away some other stuff for later
194 $type = $base->data[0]->attributes()->type[0];
195 $keyhash = $base->sig[0]->attributes()->keyhash[0];
196 $encoding = $base->encoding;
199 $signed_data = $data . (($data[-1] != "\n") ? "\n" : '') . '.' . base64url_encode($type) . "\n" . '.' . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
203 $data = base64url_decode($data);
205 // Now pull out the inner encrypted blob
207 $inner_encrypted = base64_decode($data);
210 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
212 $inner_decrypted = pkcs5_unpad($inner_decrypted);
215 logger('mod-diaspora: Could not retrieve author URI.');
216 http_status_exit(400);
219 // Once we have the author URI, go to the web and try to find their public key
220 // *** or look it up locally ***
222 logger('mod-diaspora: Fetching key for ' . $author_link );
224 // Get diaspora public key (pkcs#1) and convert to pkcs#8
225 $key = get_diaspora_key($author_link);
228 logger('mod-diaspora: Could not retrieve author key.');
229 http_status_exit(400);
232 $verify = rsa_verify($signed_data,$signature,$key);
235 logger('mod-diaspora: Message did not verify. Discarding.');
236 http_status_exit(400);
239 logger('mod-diaspora: Message verified.');
241 return $inner_decrypted;
248 function diaspora_request($importer,$contact,$xml) {
250 $sender_handle = $xml->sender_handle;
251 $recipient_handle = $xml->recipient_handle;
253 if(! $sender_handle || ! $recipient_handle)
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'])
266 require_once('include/Scrape.php');
267 $ret = probe_url($sender_handle);
269 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
270 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
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']),
283 dbesc($ret['photo']),
284 dbesc($ret['pubkey']),
285 dbesc($ret['notify']),
291 // find the contact record we just created
292 $contact_record = null;
294 $r = q("SELECT `id` FROM `contact`
295 WHERE `uid` = %d AND `addr` = '%s' AND `poll` = '%s' LIMIT 1",
296 intval($importer['uid']),
301 $contact_record = $r[0];
304 $hash = random_string() . (string) time(); // Generate a confirm_key
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']),
312 dbesc( t('Sharing notification from Diaspora network')),
314 dbesc(datetime_convert())
323 function diaspora_post($importer,$contact,$xml) {
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']),
336 // allocate a guid on our system - we aren't fixing any collisions.
337 // we're ignoring them
339 $g = q("select * from guid where guid = '%s' limit 1",
343 q("insert into guid ( guid ) values ( '%s' )",
349 $created = unxmlify($xml->created_at);
350 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
352 $body = unxmlify($xml->raw_message);
354 require_once('library/HTMLPurifier.auto.php');
355 require_once('include/html2bbcode.php');
357 $maxlen = get_max_import_size();
358 if($maxlen && (strlen($body) > $maxlen))
359 $body = substr($body,0, $maxlen);
361 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
363 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
364 '[youtube]$1[/youtube]', $body);
366 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
367 '[youtube]$1[/youtube]', $body);
369 $body = oembed_html2bbcode($body);
371 $config = HTMLPurifier_Config::createDefault();
372 $config->set('Cache.DefinitionImpl', null);
373 $purifier = new HTMLPurifier($config);
374 $body = $purifier->purify($body);
376 $body = html2bbcode($body);
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'];
395 item_store($datarray);
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']),
414 $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
415 intval($importer['uid'])
420 $created = unxmlify($xml->created_at);
421 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
425 function diaspora_like($importer,$contact,$xml) {
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']),
438 $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
439 intval($importer['uid'])
444 $created = unxmlify($xml->created_at);
445 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
447 $uri = item_new_uri($a->get_hostname(),$owner_uid);
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'];
457 <type>$objtype</type>
459 <id>{$item['uri']}</id>
462 <content>$body</content>
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');
470 if(! isset($bodyverb))
476 $arr['uid'] = $owner_uid;
477 $arr['contact-id'] = $contact['id'];
478 $arr['type'] = 'activity';
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'];
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 );
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'];
504 $arr['last-child'] = 0;
506 $post_id = item_store($arr);
508 if(! $item['visible']) {
509 $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
515 $arr['id'] = $post_id;
521 function diaspora_retraction($importer,$contact,$xml) {
525 function diaspora_share($me,$contact) {
527 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
528 $theiraddr = $contact['addr'];
530 $tpl = get_markup_template('diaspora_share.tpl');
531 $msg = replace_macros($tpl, array(
533 '$recipient' => $theiraddr
536 $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
538 post_url($contact['notify'],$slap);
539 $return_code = $a->get_curl_code();
543 function diaspora_send_status($item,$owner,$contact) {
546 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
547 $theiraddr = $contact['addr'];
548 require_once('include/bbcode.php');
550 $body = xmlify(bbcode($item['body']));
551 $public = (($item['private']) ? 'false' : 'true');
553 require_once('include/datetime.php');
554 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
556 $tpl = get_markup_template('diaspora_post.tpl');
557 $msg = replace_macros($tpl, array(
559 '$guid' => $item['guid'],
560 '$handle' => xmlify($myaddr),
561 '$public' => $public,
562 '$created' => $created
565 logger('diaspora_send_status: base message: ' . $msg, LOGGER_DATA);
567 $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey']));
569 post_url($contact['notify'],$slap);
570 $return_code = $a->get_curl_code();
571 logger('diaspora_send_status: returns: ' . $return_code);