3 require_once('include/crypto.php');
4 require_once('include/items.php');
5 require_once('include/bb2diaspora.php');
7 function diaspora_dispatch($importer,$msg) {
9 $parsed_xml = parse_xml_string($msg['message'],false);
11 $xmlbase = $parsed_xml->post;
13 if($xmlbase->request) {
14 diaspora_request($importer,$xmlbase->request);
16 elseif($xmlbase->status_message) {
17 diaspora_post($importer,$xmlbase->status_message);
19 elseif($xmlbase->comment) {
20 diaspora_comment($importer,$xmlbase->comment,$msg);
22 elseif($xmlbase->like) {
23 diaspora_like($importer,$xmlbase->like,$msg);
25 elseif($xmlbase->retraction) {
26 diaspora_retraction($importer,$xmlbase->retraction,$msg);
28 elseif($xmlbase->photo) {
29 diaspora_photo($importer,$xmlbase->photo,$msg);
32 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
37 function diaspora_get_contact_by_handle($uid,$handle) {
38 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
39 dbesc(NETWORK_DIASPORA),
48 function find_diaspora_person_by_handle($handle) {
49 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
50 dbesc(NETWORK_DIASPORA),
54 // update record occasionally so it doesn't get stale
55 $d = strtotime($r[0]['updated'] . ' +00:00');
56 if($d < strtotime('now - 14 days')) {
57 q("delete from fcontact where id = %d limit 1",
64 require_once('include/Scrape.php');
65 $r = probe_url($handle, PROBE_DIASPORA);
66 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
74 function get_diaspora_key($uri) {
75 logger('Fetching diaspora key for: ' . $uri);
77 $r = find_diaspora_person_by_handle($uri);
84 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
87 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
89 $inner_aes_key = random_string(32);
90 $b_inner_aes_key = base64_encode($inner_aes_key);
91 $inner_iv = random_string(16);
92 $b_inner_iv = base64_encode($inner_iv);
94 $outer_aes_key = random_string(32);
95 $b_outer_aes_key = base64_encode($outer_aes_key);
96 $outer_iv = random_string(16);
97 $b_outer_iv = base64_encode($outer_iv);
99 $handle = 'acct:' . $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
101 $padded_data = pkcs5_pad($msg,16);
102 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
104 $b64_data = base64_encode($inner_encrypted);
107 $b64url_data = base64url_encode($b64_data);
108 $b64url_stripped = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
109 $lines = str_split($b64url_stripped,60);
110 $data = implode("\n",$lines);
111 $data = $data . (($data[-1] != "\n") ? "\n" : '') ;
112 $type = 'application/atom+xml';
113 $encoding = 'base64url';
116 $signable_data = $data . '.' . base64url_encode($type) . "\n" . '.'
117 . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
119 $signature = rsa_sign($signable_data,$prvkey);
120 $sig = base64url_encode($signature);
122 $decrypted_header = <<< EOT
125 <aes_key>$b_inner_aes_key</aes_key>
127 <name>{$user['username']}</name>
133 $decrypted_header = pkcs5_pad($decrypted_header,16);
135 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
137 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
139 $encrypted_outer_key_bundle = '';
140 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
142 logger('outer_bundle_encrypt: ' . openssl_error_string());
143 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
145 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey);
147 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
148 'ciphertext' => base64_encode($ciphertext)));
149 $cipher_json = base64_encode($encrypted_header_json_object);
151 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
154 <?xml version='1.0' encoding='UTF-8'?>
155 <entry xmlns='http://www.w3.org/2005/Atom'>
157 <me:env xmlns:me="http://salmon-protocol.org/ns/magic-env">
158 <me:encoding>base64url</me:encoding>
159 <me:alg>RSA-SHA256</me:alg>
160 <me:data type="application/atom+xml">$data</me:data>
161 <me:sig>$sig</me:sig>
166 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
173 * diaspora_decode($importer,$xml)
174 * array $importer -> from user table
175 * string $xml -> urldecoded Diaspora salmon
178 * 'message' -> decoded Diaspora XML message
179 * 'author' -> author diaspora handle
180 * 'key' -> author public key (converted to pkcs#8)
182 * Author and key are used elsewhere to save a lookup for verifying replies and likes
186 function diaspora_decode($importer,$xml) {
188 $basedom = parse_xml_string($xml);
190 $atom = $basedom->children(NAMESPACE_ATOM1);
192 // Diaspora devs: This is kind of sucky - 'encrypted_header' does not belong in the atom namespace
194 $encrypted_header = json_decode(base64_decode($atom->encrypted_header));
196 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
197 $ciphertext = base64_decode($encrypted_header->ciphertext);
199 $outer_key_bundle = '';
200 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
202 $j_outer_key_bundle = json_decode($outer_key_bundle);
204 $outer_iv = base64_decode($j_outer_key_bundle->iv);
205 $outer_key = base64_decode($j_outer_key_bundle->key);
207 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
210 $decrypted = pkcs5_unpad($decrypted);
213 * $decrypted now contains something like
216 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
217 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
219 * <name>Ryan Hughes</name>
220 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
222 * </decrypted_header>
225 logger('decrypted: ' . $decrypted);
226 $idom = parse_xml_string($decrypted,false);
228 $inner_iv = base64_decode($idom->iv);
229 $inner_aes_key = base64_decode($idom->aes_key);
231 $author_link = str_replace('acct:','',$idom->author->uri);
233 $dom = $basedom->children(NAMESPACE_SALMON_ME);
235 // figure out where in the DOM tree our data is hiding
237 if($dom->provenance->data)
238 $base = $dom->provenance;
239 elseif($dom->env->data)
245 logger('mod-diaspora: unable to locate salmon data in xml ');
246 http_status_exit(400);
250 // Stash the signature away for now. We have to find their key or it won't be good for anything.
251 $signature = base64url_decode($base->sig);
255 // strip whitespace so our data element will return to one big base64 blob
256 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
258 // Add back the 60 char linefeeds
260 // This completely violates the entire principle of salmon magic signatures,
261 // which was to have a message signing format that was completely ambivalent to linefeeds
262 // and transport whitespace mangling, and base64 wrapping rules. Guess what? PHP and Ruby
263 // use different linelengths for base64 output.
265 $lines = str_split($data,60);
266 $data = implode("\n",$lines);
269 // stash away some other stuff for later
271 $type = $base->data[0]->attributes()->type[0];
272 $keyhash = $base->sig[0]->attributes()->keyhash[0];
273 $encoding = $base->encoding;
276 // I can't even begin to tell you how sucky this is. Please read the spec.
278 $signed_data = $data . (($data[-1] != "\n") ? "\n" : '') . '.' . base64url_encode($type) . "\n" . '.' . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
282 $data = base64url_decode($data);
284 // Now pull out the inner encrypted blob
286 $inner_encrypted = base64_decode($data);
289 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
291 $inner_decrypted = pkcs5_unpad($inner_decrypted);
294 logger('mod-diaspora: Could not retrieve author URI.');
295 http_status_exit(400);
298 // Once we have the author URI, go to the web and try to find their public key
299 // (first this will look it up locally if it is in the fcontact cache)
300 // This will also convert diaspora public key from pkcs#1 to pkcs#8
302 logger('mod-diaspora: Fetching key for ' . $author_link );
303 $key = get_diaspora_key($author_link);
306 logger('mod-diaspora: Could not retrieve author key.');
307 http_status_exit(400);
310 $verify = rsa_verify($signed_data,$signature,$key);
313 logger('mod-diaspora: Message did not verify. Discarding.');
314 http_status_exit(400);
317 logger('mod-diaspora: Message verified.');
319 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
325 function diaspora_request($importer,$xml) {
327 $sender_handle = unxmlify($xml->sender_handle);
328 $recipient_handle = unxmlify($xml->recipient_handle);
330 if(! $sender_handle || ! $recipient_handle)
333 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
338 // perhaps we were already sharing with this person. Now they're sharing with us.
339 // That makes us friends.
341 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
342 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
343 intval(CONTACT_IS_FRIEND),
344 intval($contact['id']),
345 intval($importer['uid'])
348 // send notification?
352 $ret = find_diaspora_person_by_handle($sender_handle);
355 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
356 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
360 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
361 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
362 intval($importer['uid']),
363 dbesc($ret['network']),
369 dbesc($ret['photo']),
370 dbesc($ret['pubkey']),
371 dbesc($ret['notify']),
377 // find the contact record we just created
379 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
381 $hash = random_string() . (string) time(); // Generate a confirm_key
383 if($contact_record) {
384 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
385 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
386 intval($importer['uid']),
387 intval($contact_record['id']),
390 dbesc( t('Sharing notification from Diaspora network')),
392 dbesc(datetime_convert())
399 function diaspora_post($importer,$xml) {
401 $guid = notags(unxmlify($xml->guid));
402 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
404 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
408 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
409 logger('diaspora_post: Ignoring this author.');
410 http_status_exit(202);
414 $message_id = $diaspora_handle . ':' . $guid;
415 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
416 intval($importer['uid']),
423 // allocate a guid on our system - we aren't fixing any collisions.
424 // we're ignoring them
426 $g = q("select * from guid where guid = '%s' limit 1",
430 q("insert into guid ( guid ) values ( '%s' )",
435 $created = unxmlify($xml->created_at);
436 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
438 $body = unxmlify($xml->raw_message);
440 require_once('library/HTMLPurifier.auto.php');
441 require_once('include/html2bbcode.php');
443 $maxlen = get_max_import_size();
444 if($maxlen && (strlen($body) > $maxlen))
445 $body = substr($body,0, $maxlen);
447 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
449 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
450 '[youtube]$1[/youtube]', $body);
452 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
453 '[youtube]$1[/youtube]', $body);
455 $body = oembed_html2bbcode($body);
457 $config = HTMLPurifier_Config::createDefault();
458 $config->set('Cache.DefinitionImpl', null);
459 $purifier = new HTMLPurifier($config);
460 $body = $purifier->purify($body);
462 $body = html2bbcode($body);
466 $datarray['uid'] = $importer['uid'];
467 $datarray['contact-id'] = $contact['id'];
468 $datarray['wall'] = 0;
469 $datarray['guid'] = $guid;
470 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
471 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
472 $datarray['private'] = $private;
473 $datarray['parent'] = 0;
474 $datarray['owner-name'] = $contact['name'];
475 $datarray['owner-link'] = $contact['url'];
476 $datarray['owner-avatar'] = $contact['thumb'];
477 $datarray['author-name'] = $contact['name'];
478 $datarray['author-link'] = $contact['url'];
479 $datarray['author-avatar'] = $contact['thumb'];
480 $datarray['body'] = $body;
482 item_store($datarray);
488 function diaspora_comment($importer,$xml,$msg) {
490 $guid = notags(unxmlify($xml->guid));
491 $parent_guid = notags(unxmlify($xml->parent_guid));
492 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
493 $target_type = notags(unxmlify($xml->target_type));
494 $text = unxmlify($xml->text);
495 $author_signature = notags(unxmlify($xml->author_signature));
497 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
501 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
505 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
506 logger('diaspora_comment: Ignoring this author.');
507 http_status_exit(202);
511 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
512 intval($importer['uid']),
516 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
519 $parent_item = $r[0];
521 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
523 $author_signature = base64_decode($author_signature);
525 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
530 $person = find_diaspora_person_by_handle($diaspora_handle);
532 if(is_array($person) && x($person,'pubkey'))
533 $key = $person['pubkey'];
535 logger('diaspora_comment: unable to find author details');
540 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha')) {
541 logger('diaspora_comment: verification failed.');
546 if($parent_author_signature) {
547 // $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $msg['author'];
548 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
550 $parent_author_signature = base64_decode($parent_author_signature);
554 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha')) {
555 logger('diaspora_comment: owner verification failed.');
560 // Phew! Everything checks out. Now create an item.
562 require_once('library/HTMLPurifier.auto.php');
563 require_once('include/html2bbcode.php');
567 $maxlen = get_max_import_size();
568 if($maxlen && (strlen($body) > $maxlen))
569 $body = substr($body,0, $maxlen);
571 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
573 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
574 '[youtube]$1[/youtube]', $body);
576 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
577 '[youtube]$1[/youtube]', $body);
579 $body = oembed_html2bbcode($body);
581 $config = HTMLPurifier_Config::createDefault();
582 $config->set('Cache.DefinitionImpl', null);
583 $purifier = new HTMLPurifier($config);
584 $body = $purifier->purify($body);
586 $body = html2bbcode($body);
589 $message_id = $diaspora_handle . ':' . $guid;
592 $datarray['uid'] = $importer['uid'];
593 $datarray['contact-id'] = $contact['id'];
594 $datarray['wall'] = $parent_item['wall'];
595 $datarray['gravity'] = GRAVITY_COMMENT;
596 $datarray['guid'] = $guid;
597 $datarray['uri'] = $message_id;
598 $datarray['parent-uri'] = $parent_item['uri'];
600 // No timestamps for comments? OK, we'll the use current time.
601 $datarray['created'] = $datarray['edited'] = datetime_convert();
602 $datarray['private'] = $parent_item['private'];
604 $datarray['owner-name'] = $contact['name'];
605 $datarray['owner-link'] = $contact['url'];
606 $datarray['owner-avatar'] = $contact['thumb'];
608 $datarray['author-name'] = $person['name'];
609 $datarray['author-link'] = $person['url'];
610 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
611 $datarray['body'] = $body;
613 $message_id = item_store($datarray);
615 if(! $parent_author_signature) {
616 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
618 dbesc($author_signed_data),
619 dbesc(base64_encode($author_signature)),
620 dbesc($diaspora_handle)
625 proc_run('php','include/notifier.php','comment',$message_id);
631 function diaspora_photo($importer,$xml,$msg) {
633 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
635 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
637 $status_message_guid = notags(unxmlify($xml->status_message_guid));
639 $guid = notags(unxmlify($xml->guid));
641 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
643 $public = notags(unxmlify($xml->public));
645 $created_at = notags(unxmlify($xml_created_at));
648 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
652 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
653 logger('diaspora_photo: Ignoring this author.');
654 http_status_exit(202);
658 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
659 intval($importer['uid']),
660 dbesc($status_message_guid)
663 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
666 $parent_item = $r[0];
668 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
670 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
671 dbesc($link_text . $parent_item['body']),
672 intval($parent_item['id']),
673 intval($parent_item['uid'])
682 function diaspora_like($importer,$xml,$msg) {
685 $guid = notags(unxmlify($xml->guid));
686 $parent_guid = notags(unxmlify($xml->parent_guid));
687 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
688 $target_type = notags(unxmlify($xml->target_type));
689 $positive = notags(unxmlify($xml->positive));
690 $author_signature = notags(unxmlify($xml->author_signature));
692 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
694 // likes on comments not supported here and likes on photos not supported by Diaspora
696 if($target_type !== 'Post')
699 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
703 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
704 logger('diaspora_like: Ignoring this author.');
705 http_status_exit(202);
709 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
710 intval($importer['uid']),
714 logger('diaspora_like: parent item not found: ' . $guid);
718 $parent_item = $r[0];
720 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
721 intval($importer['uid']),
725 if($positive === 'true') {
726 logger('diaspora_like: duplicate like: ' . $guid);
729 if($positive === 'false') {
730 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
732 intval($importer['uid'])
735 // send notification via proc_run()
739 if($positive === 'false') {
740 logger('diaspora_like: unlike received with no corresponding like');
744 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
746 $author_signature = base64_decode($author_signature);
748 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
753 $person = find_diaspora_person_by_handle($diaspora_handle);
754 if(is_array($person) && x($person,'pubkey'))
755 $key = $person['pubkey'];
757 logger('diaspora_like: unable to find author details');
762 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha')) {
763 logger('diaspora_like: verification failed.');
767 if($parent_author_signature) {
768 // $owner_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $msg['author'];
769 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $diaspora_handle;
771 $parent_author_signature = base64_decode($parent_author_signature);
775 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha')) {
776 logger('diaspora_like: owner verification failed.');
781 // Phew! Everything checks out. Now create an item.
783 $uri = $diaspora_handle . ':' . $guid;
785 $activity = ACTIVITY_LIKE;
786 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
787 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
788 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
789 $body = $parent_item['body'];
794 <type>$objtype</type>
796 <id>{$parent_item['uri']}</id>
799 <content>$body</content>
802 $bodyverb = t('%1$s likes %2$s\'s %3$s');
807 $arr['uid'] = $importer['uid'];
808 $arr['guid'] = $guid;
809 $arr['contact-id'] = $contact['id'];
810 $arr['type'] = 'activity';
811 $arr['wall'] = $parent_item['wall'];
812 $arr['gravity'] = GRAVITY_LIKE;
813 $arr['parent'] = $parent_item['id'];
814 $arr['parent-uri'] = $parent_item['uri'];
816 $arr['owner-name'] = $contact['name'];
817 $arr['owner-link'] = $contact['url'];
818 $arr['owner-avatar'] = $contact['thumb'];
820 $arr['author-name'] = $person['name'];
821 $arr['author-link'] = $person['url'];
822 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
824 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
825 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
826 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
827 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
829 $arr['private'] = $parent_item['private'];
830 $arr['verb'] = $activity;
831 $arr['object-type'] = $objtype;
832 $arr['object'] = $obj;
835 $arr['last-child'] = 0;
837 $message_id = item_store($arr);
839 if(! $parent_author_signature) {
840 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
842 dbesc($author_signed_data),
843 dbesc(base64_encode($author_signature)),
844 dbesc($diaspora_handle)
849 proc_run('php','include/notifier.php','comment',$message_id);
854 function diaspora_retraction($importer,$xml) {
856 $guid = notags(unxmlify($xml->guid));
857 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
858 $type = notags(unxmlify($xml->type));
860 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
864 if($type === 'Person') {
865 contact_remove($contact['id']);
867 elseif($type === 'Post') {
868 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
870 intval($importer['uid'])
873 if(link_compare($r[0]['author-link'],$contact['url'])) {
874 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
875 dbesc(datetime_convert()),
882 http_exit_status(202);
886 function diaspora_share($me,$contact) {
888 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
889 $theiraddr = $contact['addr'];
891 $tpl = get_markup_template('diaspora_share.tpl');
892 $msg = replace_macros($tpl, array(
893 '$sender' => $myaddr,
894 '$recipient' => $theiraddr
897 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
899 return(diaspora_transmit($owner,$contact,$slap));
902 function diaspora_unshare($me,$contact) {
905 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
907 $tpl = get_markup_template('diaspora_retract.tpl');
908 $msg = replace_macros($tpl, array(
909 '$guid' => $me['guid'],
914 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
916 return(diaspora_transmit($owner,$contact,$slap));
922 function diaspora_send_status($item,$owner,$contact) {
925 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
926 $theiraddr = $contact['addr'];
930 $body = $item['body'];
932 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
934 foreach($matches as $mtch) {
936 $detail['str'] = $mtch[0];
937 $detail['path'] = dirname($mtch[1]) . '/';
938 $detail['file'] = basename($mtch[1]);
939 $detail['guid'] = $item['guid'];
940 $detail['handle'] = $myaddr;
942 $body = str_replace($detail['str'],t('link'),$body);
946 $body = xmlify(bb2diaspora($body));
947 $public = (($item['private']) ? 'false' : 'true');
949 require_once('include/datetime.php');
950 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
952 $tpl = get_markup_template('diaspora_post.tpl');
953 $msg = replace_macros($tpl, array(
955 '$guid' => $item['guid'],
956 '$handle' => xmlify($myaddr),
957 '$public' => $public,
958 '$created' => $created
961 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
963 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
965 $return_code = diaspora_transmit($owner,$contact,$slap);
968 diaspora_send_images($item,$owner,$contact,$images);
975 function diaspora_send_images($item,$owner,$contact,$images) {
979 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
981 $tpl = get_markup_template('diaspora_photo.tpl');
982 foreach($images as $image) {
983 if(! stristr($image['path'],$mysite))
985 $resource = str_replace('.jpg','',$image['file']);
986 $resource = substr($resource,0,strpos($resource,'-'));
988 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
990 intval($owner['uid'])
994 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
995 $msg = replace_macros($tpl,array(
996 '$path' => xmlify($image['path']),
997 '$filename' => xmlify($image['file']),
998 '$msg_guid' => xmlify($image['guid']),
999 '$guid' => xmlify($r[0]['guid']),
1000 '$handle' => xmlify($image['handle']),
1001 '$public' => xmlify($public),
1002 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d h:i:s \U\T\C'))
1006 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1007 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1009 diaspora_transmit($owner,$contact,$slap);
1014 function diaspora_send_followup($item,$owner,$contact) {
1017 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1018 $theiraddr = $contact['addr'];
1020 $p = q("select guid from item where parent = %d limit 1",
1024 $parent_guid = $p[0]['guid'];
1028 if($item['verb'] === ACTIVITY_LIKE) {
1029 $tpl = get_markup_template('diaspora_like.tpl');
1031 $target_type = 'Post';
1032 $positive = (($item['deleted']) ? 'false' : 'true');
1035 $tpl = get_markup_template('diaspora_comment.tpl');
1039 $text = bb2diaspora($item['body']);
1044 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1046 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1048 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha'));
1050 $msg = replace_macros($tpl,array(
1051 '$guid' => xmlify($item['guid']),
1052 '$parent_guid' => xmlify($parent_guid),
1053 '$target_type' =>xmlify($target_type),
1054 '$authorsig' => xmlify($authorsig),
1055 '$body' => xmlify($text),
1056 '$positive' => xmlify($positive),
1057 '$handle' => xmlify($myaddr)
1060 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1062 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1064 return(diaspora_transmit($owner,$contact,$slap));
1068 function diaspora_send_relay($item,$owner,$contact) {
1072 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1073 $theiraddr = $contact['addr'];
1076 $p = q("select guid from item where parent = %d limit 1",
1080 $parent_guid = $p[0]['guid'];
1084 // fetch the original signature
1085 $r = q("select * from sign where iid = %d limit 1",
1092 if($item['verb'] === ACTIVITY_LIKE) {
1093 $tpl = get_markup_template('diaspora_like_relay.tpl');
1095 $target_type = 'Post';
1096 $positive = (($item['deleted']) ? 'false' : 'true');
1099 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1103 $text = bb2diaspora($item['body']);
1108 $parent_signed_text = $orig_sign['signed_text'];
1110 $parent_signed_text = $orig_sign['signed_text'];
1112 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha'));
1114 $msg = replace_macros($tpl,array(
1115 '$guid' => xmlify($item['guid']),
1116 '$parent_guid' => xmlify($parent_guid),
1117 '$target_type' =>xmlify($target_type),
1118 '$authorsig' => xmlify($orig_sign['signature']),
1119 '$parentsig' => xmlify($parentauthorsig),
1120 '$text' => xmlify($text),
1121 '$positive' => xmlify($positive),
1122 '$diaspora_handle' => xmlify($myaddr)
1125 // fetch the original signature
1126 $r = q("select * from sign where iid = %d limit 1",
1132 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1134 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1136 return(diaspora_transmit($owner,$contact,$slap));
1142 function diaspora_send_retraction($item,$owner,$contact) {
1145 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1147 $tpl = get_markup_template('diaspora_retract.tpl');
1148 $msg = replace_macros($tpl, array(
1149 '$guid' => $item['guid'],
1151 '$handle' => $myaddr
1154 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1156 return(diaspora_transmit($owner,$contact,$slap));
1161 function diaspora_transmit($owner,$contact,$slap) {
1165 post_url($contact['notify'] . '/',$slap);
1166 $return_code = $a->get_curl_code();
1167 logger('diaspora_transmit: returns: ' . $return_code);
1169 if(! $return_code) {
1170 logger('diaspora_transmit: queue message');
1171 // queue message for redelivery
1172 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
1173 VALUES ( %d, '%s', '%s', '%s') ",
1174 intval($contact['id']),
1175 dbesc(datetime_convert()),
1176 dbesc(datetime_convert()),
1181 return(($return_code) ? $return_code : (-1));