3 require_once('include/crypto.php');
4 require_once('include/items.php');
5 require_once('include/bb2diaspora.php');
6 require_once('include/contact_selectors.php');
9 function diaspora_dispatch_public($msg) {
11 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN ( SELECT `uid` FROM `contact` WHERE `network` = '%s' AND `addr` = '%s' ) ",
12 dbesc(NETWORK_DIASPORA),
17 diaspora_dispatch($rr,$msg);
24 function diaspora_dispatch($importer,$msg) {
28 $parsed_xml = parse_xml_string($msg['message'],false);
30 $xmlbase = $parsed_xml->post;
32 if($xmlbase->request) {
33 $ret = diaspora_request($importer,$xmlbase->request);
35 elseif($xmlbase->status_message) {
36 $ret = diaspora_post($importer,$xmlbase->status_message);
38 elseif($xmlbase->comment) {
39 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
41 elseif($xmlbase->like) {
42 $ret = diaspora_like($importer,$xmlbase->like,$msg);
44 elseif($xmlbase->retraction) {
45 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
47 elseif($xmlbase->photo) {
48 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
51 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
56 function diaspora_get_contact_by_handle($uid,$handle) {
57 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
58 dbesc(NETWORK_DIASPORA),
67 function find_diaspora_person_by_handle($handle) {
68 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
69 dbesc(NETWORK_DIASPORA),
73 // update record occasionally so it doesn't get stale
74 $d = strtotime($r[0]['updated'] . ' +00:00');
75 if($d < strtotime('now - 14 days')) {
76 q("delete from fcontact where id = %d limit 1",
83 require_once('include/Scrape.php');
84 $r = probe_url($handle, PROBE_DIASPORA);
85 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
93 function get_diaspora_key($uri) {
94 logger('Fetching diaspora key for: ' . $uri);
96 $r = find_diaspora_person_by_handle($uri);
103 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
106 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
108 $inner_aes_key = random_string(32);
109 $b_inner_aes_key = base64_encode($inner_aes_key);
110 $inner_iv = random_string(16);
111 $b_inner_iv = base64_encode($inner_iv);
113 $outer_aes_key = random_string(32);
114 $b_outer_aes_key = base64_encode($outer_aes_key);
115 $outer_iv = random_string(16);
116 $b_outer_iv = base64_encode($outer_iv);
118 $handle = 'acct:' . $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
120 $padded_data = pkcs5_pad($msg,16);
121 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
123 $b64_data = base64_encode($inner_encrypted);
126 $b64url_data = base64url_encode($b64_data);
127 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
129 $type = 'application/atom+xml';
130 $encoding = 'base64url';
133 $signable_data = $data . '.' . base64url_encode($type) . '.'
134 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
136 $signature = rsa_sign($signable_data,$prvkey);
137 $sig = base64url_encode($signature);
139 $decrypted_header = <<< EOT
142 <aes_key>$b_inner_aes_key</aes_key>
144 <name>{$user['username']}</name>
150 $decrypted_header = pkcs5_pad($decrypted_header,16);
152 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
154 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
156 $encrypted_outer_key_bundle = '';
157 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
159 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
161 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
163 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
164 'ciphertext' => base64_encode($ciphertext)));
165 $cipher_json = base64_encode($encrypted_header_json_object);
167 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
170 <?xml version='1.0' encoding='UTF-8'?>
171 <entry xmlns='http://www.w3.org/2005/Atom'>
173 <me:env xmlns:me="http://salmon-protocol.org/ns/magic-env">
174 <me:encoding>base64url</me:encoding>
175 <me:alg>RSA-SHA256</me:alg>
176 <me:data type="application/xml">$data</me:data>
177 <me:sig>$sig</me:sig>
182 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
189 * diaspora_decode($importer,$xml)
190 * array $importer -> from user table
191 * string $xml -> urldecoded Diaspora salmon
194 * 'message' -> decoded Diaspora XML message
195 * 'author' -> author diaspora handle
196 * 'key' -> author public key (converted to pkcs#8)
198 * Author and key are used elsewhere to save a lookup for verifying replies and likes
202 function diaspora_decode($importer,$xml) {
205 $basedom = parse_xml_string($xml);
207 $children = $basedom->children(NAMESPACE_DIASPORA_PROTOCOL);
209 if($children->header) {
211 $author_link = str_replace('acct:','',$children->author_id);
215 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
217 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
218 $ciphertext = base64_decode($encrypted_header->ciphertext);
220 $outer_key_bundle = '';
221 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
223 $j_outer_key_bundle = json_decode($outer_key_bundle);
225 $outer_iv = base64_decode($j_outer_key_bundle->iv);
226 $outer_key = base64_decode($j_outer_key_bundle->key);
228 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
231 $decrypted = pkcs5_unpad($decrypted);
234 * $decrypted now contains something like
237 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
238 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
243 * <name>Ryan Hughes</name>
244 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
249 * <author_id>acct:galaxor@diaspora.priateship.org</author_id>
253 * </decrypted_header>
256 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
257 $idom = parse_xml_string($decrypted,false);
259 $inner_iv = base64_decode($idom->iv);
260 $inner_aes_key = base64_decode($idom->aes_key);
262 $author_link = str_replace('acct:','',$idom->author_id);
266 $dom = $basedom->children(NAMESPACE_SALMON_ME);
268 // figure out where in the DOM tree our data is hiding
270 if($dom->provenance->data)
271 $base = $dom->provenance;
272 elseif($dom->env->data)
278 logger('mod-diaspora: unable to locate salmon data in xml ');
279 http_status_exit(400);
283 // Stash the signature away for now. We have to find their key or it won't be good for anything.
284 $signature = base64url_decode($base->sig);
288 // strip whitespace so our data element will return to one big base64 blob
289 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
291 // Add back the 60 char linefeeds
293 // This completely violates the entire principle of salmon magic signatures,
294 // which was to have a message signing format that was completely ambivalent to linefeeds
295 // and transport whitespace mangling, and base64 wrapping rules. Guess what? PHP and Ruby
296 // use different linelengths for base64 output.
298 // $lines = str_split($data,60);
299 // $data = implode("\n",$lines);
302 // stash away some other stuff for later
304 $type = $base->data[0]->attributes()->type[0];
305 $keyhash = $base->sig[0]->attributes()->keyhash[0];
306 $encoding = $base->encoding;
310 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
314 $data = base64url_decode($data);
318 $inner_decrypted = $data;
322 // Decode the encrypted blob
324 $inner_encrypted = base64_decode($data);
325 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
326 $inner_decrypted = pkcs5_unpad($inner_decrypted);
330 logger('mod-diaspora: Could not retrieve author URI.');
331 http_status_exit(400);
334 // Once we have the author URI, go to the web and try to find their public key
335 // (first this will look it up locally if it is in the fcontact cache)
336 // This will also convert diaspora public key from pkcs#1 to pkcs#8
338 logger('mod-diaspora: Fetching key for ' . $author_link );
339 $key = get_diaspora_key($author_link);
342 logger('mod-diaspora: Could not retrieve author key.');
343 http_status_exit(400);
346 $verify = rsa_verify($signed_data,$signature,$key);
349 logger('mod-diaspora: Message did not verify. Discarding.');
350 http_status_exit(400);
353 logger('mod-diaspora: Message verified.');
355 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
360 function diaspora_request($importer,$xml) {
362 $sender_handle = unxmlify($xml->sender_handle);
363 $recipient_handle = unxmlify($xml->recipient_handle);
365 if(! $sender_handle || ! $recipient_handle)
368 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
372 // perhaps we were already sharing with this person. Now they're sharing with us.
373 // That makes us friends.
375 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
376 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
377 intval(CONTACT_IS_FRIEND),
378 intval($contact['id']),
379 intval($importer['uid'])
382 // send notification?
386 $ret = find_diaspora_person_by_handle($sender_handle);
389 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
390 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
394 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
395 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
396 intval($importer['uid']),
397 dbesc($ret['network']),
403 dbesc($ret['photo']),
404 dbesc($ret['pubkey']),
405 dbesc($ret['notify']),
411 // find the contact record we just created
413 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
415 $hash = random_string() . (string) time(); // Generate a confirm_key
417 if($contact_record) {
418 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
419 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
420 intval($importer['uid']),
421 intval($contact_record['id']),
424 dbesc( t('Sharing notification from Diaspora network')),
426 dbesc(datetime_convert())
433 function diaspora_post($importer,$xml) {
436 $guid = notags(unxmlify($xml->guid));
437 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
439 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
443 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
444 logger('diaspora_post: Ignoring this author.');
448 $message_id = $diaspora_handle . ':' . $guid;
449 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
450 intval($importer['uid']),
455 logger('diaspora_post: message exists: ' . $guid);
459 // allocate a guid on our system - we aren't fixing any collisions.
460 // we're ignoring them
462 $g = q("select * from guid where guid = '%s' limit 1",
466 q("insert into guid ( guid ) values ( '%s' )",
471 $created = unxmlify($xml->created_at);
472 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
474 $body = diaspora2bb($xml->raw_message);
477 $datarray['uid'] = $importer['uid'];
478 $datarray['contact-id'] = $contact['id'];
479 $datarray['wall'] = 0;
480 $datarray['guid'] = $guid;
481 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
482 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
483 $datarray['private'] = $private;
484 $datarray['parent'] = 0;
485 $datarray['owner-name'] = $contact['name'];
486 $datarray['owner-link'] = $contact['url'];
487 $datarray['owner-avatar'] = $contact['thumb'];
488 $datarray['author-name'] = $contact['name'];
489 $datarray['author-link'] = $contact['url'];
490 $datarray['author-avatar'] = $contact['thumb'];
491 $datarray['body'] = $body;
492 $datarray['app'] = 'Diaspora';
494 $message_id = item_store($datarray);
497 q("update item set plink = '%s' where id = %d limit 1",
498 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
507 function diaspora_comment($importer,$xml,$msg) {
510 $guid = notags(unxmlify($xml->guid));
511 $parent_guid = notags(unxmlify($xml->parent_guid));
512 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
513 $target_type = notags(unxmlify($xml->target_type));
514 $text = unxmlify($xml->text);
515 $author_signature = notags(unxmlify($xml->author_signature));
517 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
521 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
523 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
527 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
528 logger('diaspora_comment: Ignoring this author.');
532 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
533 intval($importer['uid']),
537 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
541 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
542 intval($importer['uid']),
546 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
549 $parent_item = $r[0];
551 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
553 $author_signature = base64_decode($author_signature);
555 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
560 $person = find_diaspora_person_by_handle($diaspora_handle);
562 if(is_array($person) && x($person,'pubkey'))
563 $key = $person['pubkey'];
565 logger('diaspora_comment: unable to find author details');
570 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
571 logger('diaspora_comment: verification failed.');
576 if($parent_author_signature) {
577 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
579 $parent_author_signature = base64_decode($parent_author_signature);
583 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
584 logger('diaspora_comment: owner verification failed.');
589 // Phew! Everything checks out. Now create an item.
591 $body = diaspora2bb($text);
593 $message_id = $diaspora_handle . ':' . $guid;
596 $datarray['uid'] = $importer['uid'];
597 $datarray['contact-id'] = $contact['id'];
598 $datarray['wall'] = $parent_item['wall'];
599 $datarray['gravity'] = GRAVITY_COMMENT;
600 $datarray['guid'] = $guid;
601 $datarray['uri'] = $message_id;
602 $datarray['parent-uri'] = $parent_item['uri'];
604 // No timestamps for comments? OK, we'll the use current time.
605 $datarray['created'] = $datarray['edited'] = datetime_convert();
606 $datarray['private'] = $parent_item['private'];
608 $datarray['owner-name'] = $contact['name'];
609 $datarray['owner-link'] = $contact['url'];
610 $datarray['owner-avatar'] = $contact['thumb'];
612 $datarray['author-name'] = $person['name'];
613 $datarray['author-link'] = $person['url'];
614 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
615 $datarray['body'] = $body;
616 $datarray['app'] = 'Diaspora';
618 $message_id = item_store($datarray);
621 q("update item set plink = '%s' where id = %d limit 1",
622 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
627 if(! $parent_author_signature) {
628 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
630 dbesc($author_signed_data),
631 dbesc(base64_encode($author_signature)),
632 dbesc($diaspora_handle)
635 // if the message isn't already being relayed, notify others
636 // the existence of parent_author_signature means the parent_author or owner
637 // is already relaying.
639 proc_run('php','include/notifier.php','comment',$message_id);
644 function diaspora_photo($importer,$xml,$msg) {
647 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
649 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
651 $status_message_guid = notags(unxmlify($xml->status_message_guid));
653 $guid = notags(unxmlify($xml->guid));
655 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
657 $public = notags(unxmlify($xml->public));
659 $created_at = notags(unxmlify($xml_created_at));
662 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
666 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
667 logger('diaspora_photo: Ignoring this author.');
671 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
672 intval($importer['uid']),
673 dbesc($status_message_guid)
676 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
679 $parent_item = $r[0];
681 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
683 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
684 dbesc($link_text . $parent_item['body']),
685 intval($parent_item['id']),
686 intval($parent_item['uid'])
695 function diaspora_like($importer,$xml,$msg) {
698 $guid = notags(unxmlify($xml->guid));
699 $parent_guid = notags(unxmlify($xml->parent_guid));
700 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
701 $target_type = notags(unxmlify($xml->target_type));
702 $positive = notags(unxmlify($xml->positive));
703 $author_signature = notags(unxmlify($xml->author_signature));
705 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
707 // likes on comments not supported here and likes on photos not supported by Diaspora
709 if($target_type !== 'Post')
712 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
714 logger('diaspora_like: cannot find contact: ' . $msg['author']);
718 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
719 logger('diaspora_like: Ignoring this author.');
723 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
724 intval($importer['uid']),
728 logger('diaspora_like: parent item not found: ' . $guid);
732 $parent_item = $r[0];
734 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
735 intval($importer['uid']),
739 if($positive === 'true') {
740 logger('diaspora_like: duplicate like: ' . $guid);
743 if($positive === 'false') {
744 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
746 intval($importer['uid'])
749 // send notification via proc_run()
753 if($positive === 'false') {
754 logger('diaspora_like: unlike received with no corresponding like');
758 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
760 $author_signature = base64_decode($author_signature);
762 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
767 $person = find_diaspora_person_by_handle($diaspora_handle);
768 if(is_array($person) && x($person,'pubkey'))
769 $key = $person['pubkey'];
771 logger('diaspora_like: unable to find author details');
776 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
777 logger('diaspora_like: verification failed.');
781 if($parent_author_signature) {
783 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
785 $parent_author_signature = base64_decode($parent_author_signature);
789 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
790 logger('diaspora_like: owner verification failed.');
795 // Phew! Everything checks out. Now create an item.
797 $uri = $diaspora_handle . ':' . $guid;
799 $activity = ACTIVITY_LIKE;
800 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
801 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
802 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
803 $body = $parent_item['body'];
808 <type>$objtype</type>
810 <id>{$parent_item['uri']}</id>
813 <content>$body</content>
816 $bodyverb = t('%1$s likes %2$s\'s %3$s');
821 $arr['uid'] = $importer['uid'];
822 $arr['guid'] = $guid;
823 $arr['contact-id'] = $contact['id'];
824 $arr['type'] = 'activity';
825 $arr['wall'] = $parent_item['wall'];
826 $arr['gravity'] = GRAVITY_LIKE;
827 $arr['parent'] = $parent_item['id'];
828 $arr['parent-uri'] = $parent_item['uri'];
830 $arr['owner-name'] = $contact['name'];
831 $arr['owner-link'] = $contact['url'];
832 $arr['owner-avatar'] = $contact['thumb'];
834 $arr['author-name'] = $person['name'];
835 $arr['author-link'] = $person['url'];
836 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
838 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
839 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
840 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
841 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
843 $arr['app'] = 'Diaspora';
845 $arr['private'] = $parent_item['private'];
846 $arr['verb'] = $activity;
847 $arr['object-type'] = $objtype;
848 $arr['object'] = $obj;
851 $arr['last-child'] = 0;
853 $message_id = item_store($arr);
857 q("update item set plink = '%s' where id = %d limit 1",
858 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
863 if(! $parent_author_signature) {
864 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
866 dbesc($author_signed_data),
867 dbesc(base64_encode($author_signature)),
868 dbesc($diaspora_handle)
872 // if the message isn't already being relayed, notify others
873 // the existence of parent_author_signature means the parent_author or owner
874 // is already relaying.
876 if(! $parent_author_signature)
877 proc_run('php','include/notifier.php','comment',$message_id);
882 function diaspora_retraction($importer,$xml) {
884 $guid = notags(unxmlify($xml->guid));
885 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
886 $type = notags(unxmlify($xml->type));
888 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
892 if($type === 'Person') {
893 contact_remove($contact['id']);
895 elseif($type === 'Post') {
896 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
898 intval($importer['uid'])
901 if(link_compare($r[0]['author-link'],$contact['url'])) {
902 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
903 dbesc(datetime_convert()),
914 function diaspora_share($me,$contact) {
916 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
917 $theiraddr = $contact['addr'];
919 $tpl = get_markup_template('diaspora_share.tpl');
920 $msg = replace_macros($tpl, array(
921 '$sender' => $myaddr,
922 '$recipient' => $theiraddr
925 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
927 return(diaspora_transmit($owner,$contact,$slap));
930 function diaspora_unshare($me,$contact) {
933 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
935 $tpl = get_markup_template('diaspora_retract.tpl');
936 $msg = replace_macros($tpl, array(
937 '$guid' => $me['guid'],
942 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
944 return(diaspora_transmit($owner,$contact,$slap));
950 function diaspora_send_status($item,$owner,$contact) {
953 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
954 $theiraddr = $contact['addr'];
958 $body = $item['body'];
960 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
962 foreach($matches as $mtch) {
964 $detail['str'] = $mtch[0];
965 $detail['path'] = dirname($mtch[1]) . '/';
966 $detail['file'] = basename($mtch[1]);
967 $detail['guid'] = $item['guid'];
968 $detail['handle'] = $myaddr;
970 $body = str_replace($detail['str'],t('link'),$body);
974 $body = xmlify(html_entity_decode(bb2diaspora($body)));
976 $public = (($item['private']) ? 'false' : 'true');
978 require_once('include/datetime.php');
979 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
981 $tpl = get_markup_template('diaspora_post.tpl');
982 $msg = replace_macros($tpl, array(
984 '$guid' => $item['guid'],
985 '$handle' => xmlify($myaddr),
986 '$public' => $public,
987 '$created' => $created
990 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
992 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
994 $return_code = diaspora_transmit($owner,$contact,$slap);
997 diaspora_send_images($item,$owner,$contact,$images);
1000 return $return_code;
1004 function diaspora_send_images($item,$owner,$contact,$images) {
1006 if(! count($images))
1008 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1010 $tpl = get_markup_template('diaspora_photo.tpl');
1011 foreach($images as $image) {
1012 if(! stristr($image['path'],$mysite))
1014 $resource = str_replace('.jpg','',$image['file']);
1015 $resource = substr($resource,0,strpos($resource,'-'));
1017 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1019 intval($owner['uid'])
1023 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1024 $msg = replace_macros($tpl,array(
1025 '$path' => xmlify($image['path']),
1026 '$filename' => xmlify($image['file']),
1027 '$msg_guid' => xmlify($image['guid']),
1028 '$guid' => xmlify($r[0]['guid']),
1029 '$handle' => xmlify($image['handle']),
1030 '$public' => xmlify($public),
1031 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1035 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1036 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1038 diaspora_transmit($owner,$contact,$slap);
1043 function diaspora_send_followup($item,$owner,$contact) {
1046 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1047 $theiraddr = $contact['addr'];
1049 $p = q("select guid from item where parent = %d limit 1",
1053 $parent_guid = $p[0]['guid'];
1057 if($item['verb'] === ACTIVITY_LIKE) {
1058 $tpl = get_markup_template('diaspora_like.tpl');
1060 $target_type = 'Post';
1061 $positive = (($item['deleted']) ? 'false' : 'true');
1064 $tpl = get_markup_template('diaspora_comment.tpl');
1068 $text = html_entity_decode(bb2diaspora($item['body']));
1073 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1075 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1077 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1079 $msg = replace_macros($tpl,array(
1080 '$guid' => xmlify($item['guid']),
1081 '$parent_guid' => xmlify($parent_guid),
1082 '$target_type' =>xmlify($target_type),
1083 '$authorsig' => xmlify($authorsig),
1084 '$body' => xmlify($text),
1085 '$positive' => xmlify($positive),
1086 '$handle' => xmlify($myaddr)
1089 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1091 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1093 return(diaspora_transmit($owner,$contact,$slap));
1097 function diaspora_send_relay($item,$owner,$contact) {
1101 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1102 $theiraddr = $contact['addr'];
1105 $p = q("select guid from item where parent = %d limit 1",
1109 $parent_guid = $p[0]['guid'];
1113 if($item['verb'] === ACTIVITY_LIKE) {
1114 $tpl = get_markup_template('diaspora_like_relay.tpl');
1116 $target_type = 'Post';
1117 $positive = (($item['deleted']) ? 'false' : 'true');
1120 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1124 $body = $item['body'];
1126 $text = html_entity_decode(bb2diaspora($body));
1128 // fetch the original signature if somebody sent the post to us to relay
1129 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1130 // action. It wasn't needed. In that case create the original signature and the
1131 // owner (parent author) signature
1132 // comments from other networks will be relayed under our name, with a brief
1133 // preamble to describe what's happening and noting the real author
1135 $r = q("select * from sign where iid = %d limit 1",
1140 $signed_text = $orig_sign['signed_text'];
1141 $authorsig = $orig_sign['signature'];
1142 $handle = $orig_sign['signer'];
1146 $itemcontact = q("select * from contact where `id` = %d limit 1",
1147 intval($item['contact-id'])
1149 if(count($itemcontact)) {
1150 if(! $itemcontact[0]['self']) {
1151 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1152 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1153 network_to_name($itemcontact['network'])) . "\n";
1154 $body = $prefix . $body;
1160 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1162 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1164 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1166 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1167 intval($item['id']),
1168 dbesc($signed_text),
1169 dbesc(base64_encode($authorsig)),
1178 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1180 $msg = replace_macros($tpl,array(
1181 '$guid' => xmlify($item['guid']),
1182 '$parent_guid' => xmlify($parent_guid),
1183 '$target_type' =>xmlify($target_type),
1184 '$authorsig' => xmlify($orig_sign['signature']),
1185 '$parentsig' => xmlify($parentauthorsig),
1186 '$body' => xmlify($text),
1187 '$positive' => xmlify($positive),
1188 '$handle' => xmlify($handle)
1191 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1193 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1195 return(diaspora_transmit($owner,$contact,$slap));
1201 function diaspora_send_retraction($item,$owner,$contact) {
1204 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1206 $tpl = get_markup_template('diaspora_retract.tpl');
1207 $msg = replace_macros($tpl, array(
1208 '$guid' => $item['guid'],
1210 '$handle' => $myaddr
1213 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1215 return(diaspora_transmit($owner,$contact,$slap));
1220 function diaspora_transmit($owner,$contact,$slap) {
1224 post_url($contact['notify'] . '/',$slap);
1225 $return_code = $a->get_curl_code();
1226 logger('diaspora_transmit: returns: ' . $return_code);
1228 if(! $return_code) {
1229 logger('diaspora_transmit: queue message');
1230 // queue message for redelivery
1231 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
1232 VALUES ( %d, '%s', '%s', '%s') ",
1233 intval($contact['id']),
1234 dbesc(datetime_convert()),
1235 dbesc(datetime_convert()),
1240 return(($return_code) ? $return_code : (-1));