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>{$contact['name']}</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) {
119 $basedom = parse_xml_string($xml);
121 $atom = $basedom->children(NAMESPACE_ATOM1);
123 $encrypted_header = json_decode(base64_decode($atom->encrypted_header));
125 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
126 $ciphertext = base64_decode($encrypted_header->ciphertext);
128 $outer_key_bundle = '';
129 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
131 $j_outer_key_bundle = json_decode($outer_key_bundle);
133 $outer_iv = base64_decode($j_outer_key_bundle->iv);
134 $outer_key = base64_decode($j_outer_key_bundle->key);
136 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
138 $decrypted = pkcs5_unpad($decrypted);
141 * $decrypted now contains something like
144 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
145 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
147 * <name>Ryan Hughes</name>
148 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
150 * </decrypted_header>
153 $idom = parse_xml_string($decrypted,false);
155 $inner_iv = base64_decode($idom->iv);
156 $inner_aes_key = base64_decode($idom->aes_key);
158 $author_link = str_replace('acct:','',$idom->author->uri);
160 $dom = $basedom->children(NAMESPACE_SALMON_ME);
162 // figure out where in the DOM tree our data is hiding
164 if($dom->provenance->data)
165 $base = $dom->provenance;
166 elseif($dom->env->data)
172 logger('mod-diaspora: unable to locate salmon data in xml ');
177 // Stash the signature away for now. We have to find their key or it won't be good for anything.
178 $signature = base64url_decode($base->sig);
182 // strip whitespace so our data element will return to one big base64 blob
183 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
184 // Add back the 60 char linefeeds
185 $lines = str_split($data,60);
186 $data = implode("\n",$lines);
189 // stash away some other stuff for later
191 $type = $base->data[0]->attributes()->type[0];
192 $keyhash = $base->sig[0]->attributes()->keyhash[0];
193 $encoding = $base->encoding;
196 $signed_data = $data . (($data[-1] != "\n") ? "\n" : '') . '.' . base64url_encode($type) . "\n" . '.' . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
200 $data = base64url_decode($data);
202 // Now pull out the inner encrypted blob
204 $inner_encrypted = base64_decode($data);
207 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
209 $inner_decrypted = pkcs5_unpad($inner_decrypted);
212 logger('mod-diaspora: Could not retrieve author URI.');
213 http_status_exit(400);
216 // Once we have the author URI, go to the web and try to find their public key
217 // *** or look it up locally ***
219 logger('mod-diaspora: Fetching key for ' . $author_link );
221 // Get diaspora public key (pkcs#1) and convert to pkcs#8
222 $key = get_diaspora_key($author_link);
225 logger('mod-diaspora: Could not retrieve author key.');
226 http_status_exit(400);
229 $verify = rsa_verify($signed_data,$signature,$key);
232 logger('mod-diaspora: Message did not verify. Discarding.');
233 http_status_exit(400);
236 logger('mod-diaspora: Message verified.');
238 return $inner_decrypted;
245 function diaspora_request($importer,$contact,$xml) {
247 $sender_handle = $xml->sender_handle;
248 $recipient_handle = $xml->recipient_handle;
250 if(! $sender_handle || ! $recipient_handle)
253 if($contact && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) {
254 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
255 intval(CONTACT_IS_FRIEND),
256 intval($contact['id']),
257 intval($importer['uid'])
263 require_once('include/Scrape.php');
264 $ret = probe_url($sender_handle);
266 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
267 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
271 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
272 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
273 intval($importer['uid']),
274 dbesc($ret['network']),
280 dbesc($ret['photo']),
281 dbesc($ret['pubkey']),
282 dbesc($ret['notify']),
288 // find the contact record we just created
289 $contact_record = null;
291 $r = q("SELECT `id` FROM `contact`
292 WHERE `uid` = %d AND `addr` = '%s' AND `poll` = '%s' LIMIT 1",
293 intval($importer['uid']),
298 $contact_record = $r[0];
301 $hash = random_string() . (string) time(); // Generate a confirm_key
303 if(is_array($contact_record)) {
304 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
305 VALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )",
306 intval($importer['uid']),
307 intval($contact_record['id']),
309 dbesc( t('Sharing notification from Diaspora network')),
311 dbesc(datetime_convert())
320 function diaspora_post($importer,$contact,$xml) {
322 $guid = notags(unxmlify($xml->guid));
323 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
324 $message_id = $diaspora_handle . ':' . $guid;
325 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
326 intval($importer['uid']),
333 // allocate a guid on our system - we aren't fixing any collisions.
334 // we're ignoring them
336 $g = q("select * from guid where guid = '%s' limit 1",
340 q("insert into guid ( guid ) values ( '%s' )",
346 $created = unxmlify($xml->created_at);
347 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
349 $body = unxmlify($xml->raw_message);
351 require_once('library/HTMLPurifier.auto.php');
352 require_once('include/html2bbcode.php');
354 $maxlen = get_max_import_size();
355 if($maxlen && (strlen($body) > $maxlen))
356 $body = substr($body,0, $maxlen);
358 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
360 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
361 '[youtube]$1[/youtube]', $body);
363 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
364 '[youtube]$1[/youtube]', $body);
366 $body = oembed_html2bbcode($body);
368 $config = HTMLPurifier_Config::createDefault();
369 $config->set('Cache.DefinitionImpl', null);
370 $purifier = new HTMLPurifier($config);
371 $body = $purifier->purify($body);
373 $body = html2bbcode($body);
377 $datarray['uid'] = $importer['uid'];
378 $datarray['contact-id'] = $contact['id'];
379 $datarray['wall'] = 0;
380 $datarray['guid'] = $guid;
381 $datarray['uri'] = $message_id;
382 $dattarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
383 $dattarray['private'] = $private;
384 $dattarray['parent'] = 0;
385 $datarray['owner-name'] = $contact['name'];
386 $datarray['owner-link'] = $contact['url'];
387 $datarray['owner-avatar'] = $contact['thumb'];
388 $datarray['author-name'] = $contact['name'];
389 $datarray['author-link'] = $contact['url'];
390 $datarray['author-avatar'] = $contact['thumb'];
392 item_store($datarray);
399 function diaspora_comment($importer,$contact,$xml) {
400 $guid = notags(unxmlify($xml->guid));
401 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
402 $message_id = $diaspora_handle . ':' . $guid;
403 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
404 intval($importer['uid']),
411 $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
412 intval($importer['uid'])
417 $created = unxmlify($xml->created_at);
418 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
422 function diaspora_like($importer,$contact,$xml) {
424 $guid = notags(unxmlify($xml->guid));
425 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
426 $message_id = $diaspora_handle . ':' . $guid;
427 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
428 intval($importer['uid']),
435 $owner = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
436 intval($importer['uid'])
441 $created = unxmlify($xml->created_at);
442 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
444 $uri = item_new_uri($a->get_hostname(),$owner_uid);
446 $post_type = (($item['resource-id']) ? t('photo') : t('status'));
447 $objtype = (($item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
448 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id'] . '" />' . "\n") ;
449 $body = $item['body'];
454 <type>$objtype</type>
456 <id>{$item['uri']}</id>
459 <content>$body</content>
463 $bodyverb = t('%1$s likes %2$s\'s %3$s');
464 if($verb === 'dislike')
465 $bodyverb = t('%1$s doesn\'t like %2$s\'s %3$s');
467 if(! isset($bodyverb))
473 $arr['uid'] = $owner_uid;
474 $arr['contact-id'] = $contact['id'];
475 $arr['type'] = 'activity';
477 $arr['gravity'] = GRAVITY_LIKE;
478 $arr['parent'] = $item['id'];
479 $arr['parent-uri'] = $item['uri'];
480 $arr['owner-name'] = $owner['name'];
481 $arr['owner-link'] = $owner['url'];
482 $arr['owner-avatar'] = $owner['thumb'];
483 $arr['author-name'] = $contact['name'];
484 $arr['author-link'] = $contact['url'];
485 $arr['author-avatar'] = $contact['thumb'];
487 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
488 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
489 $plink = '[url=' . $a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
490 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
492 $arr['verb'] = $activity;
493 $arr['object-type'] = $objtype;
494 $arr['object'] = $obj;
495 $arr['allow_cid'] = $item['allow_cid'];
496 $arr['allow_gid'] = $item['allow_gid'];
497 $arr['deny_cid'] = $item['deny_cid'];
498 $arr['deny_gid'] = $item['deny_gid'];
501 $arr['last-child'] = 0;
503 $post_id = item_store($arr);
505 if(! $item['visible']) {
506 $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
512 $arr['id'] = $post_id;
518 function diaspora_retraction($importer,$contact,$xml) {