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 `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' ) AND `account_expired` = 0 ",
12 dbesc(NETWORK_DIASPORA),
17 logger('diaspora_public: delivering to: ' . $rr['username']);
18 diaspora_dispatch($rr,$msg);
22 logger('diaspora_public: no subscribers');
27 function diaspora_dispatch($importer,$msg) {
31 $parsed_xml = parse_xml_string($msg['message'],false);
33 $xmlbase = $parsed_xml->post;
35 if($xmlbase->request) {
36 $ret = diaspora_request($importer,$xmlbase->request);
38 elseif($xmlbase->status_message) {
39 $ret = diaspora_post($importer,$xmlbase->status_message);
41 elseif($xmlbase->comment) {
42 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
44 elseif($xmlbase->like) {
45 $ret = diaspora_like($importer,$xmlbase->like,$msg);
47 elseif($xmlbase->retraction) {
48 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
50 elseif($xmlbase->photo) {
51 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
54 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
59 function diaspora_get_contact_by_handle($uid,$handle) {
60 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
61 dbesc(NETWORK_DIASPORA),
70 function find_diaspora_person_by_handle($handle) {
72 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
73 dbesc(NETWORK_DIASPORA),
77 // update record occasionally so it doesn't get stale
78 $d = strtotime($r[0]['updated'] . ' +00:00');
79 if($d > strtotime('now - 14 days'))
83 require_once('include/Scrape.php');
84 $r = probe_url($handle, PROBE_DIASPORA);
85 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
86 add_fcontact($r,$update);
93 function get_diaspora_key($uri) {
94 logger('Fetching diaspora key for: ' . $uri);
96 $r = find_diaspora_person_by_handle($uri);
103 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
106 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
109 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
111 $b64_data = base64_encode($msg);
112 $b64url_data = base64url_encode($b64_data);
114 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
116 $type = 'application/xml';
117 $encoding = 'base64url';
120 $signable_data = $data . '.' . base64url_encode($type) . '.'
121 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
123 $signature = rsa_sign($signable_data,$prvkey);
124 $sig = base64url_encode($signature);
127 <?xml version='1.0' encoding='UTF-8'?>
128 <diaspora xmlns="https://joindiaspora.org/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
130 <author_id>$handle</author_id>
133 <me:encoding>base64url</me:encoding>
134 <me:alg>RSA-SHA256</me:alg>
135 <me:data type="application/xml">$data</me:data>
136 <me:sig>$sig</me:sig>
141 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
149 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
152 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
154 $inner_aes_key = random_string(32);
155 $b_inner_aes_key = base64_encode($inner_aes_key);
156 $inner_iv = random_string(16);
157 $b_inner_iv = base64_encode($inner_iv);
159 $outer_aes_key = random_string(32);
160 $b_outer_aes_key = base64_encode($outer_aes_key);
161 $outer_iv = random_string(16);
162 $b_outer_iv = base64_encode($outer_iv);
164 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
166 $padded_data = pkcs5_pad($msg,16);
167 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
169 $b64_data = base64_encode($inner_encrypted);
172 $b64url_data = base64url_encode($b64_data);
173 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
175 $type = 'application/xml';
176 $encoding = 'base64url';
179 $signable_data = $data . '.' . base64url_encode($type) . '.'
180 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
182 $signature = rsa_sign($signable_data,$prvkey);
183 $sig = base64url_encode($signature);
185 $decrypted_header = <<< EOT
188 <aes_key>$b_inner_aes_key</aes_key>
189 <author_id>$handle</author_id>
193 $decrypted_header = pkcs5_pad($decrypted_header,16);
195 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
197 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
199 $encrypted_outer_key_bundle = '';
200 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
202 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
204 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
206 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
207 'ciphertext' => base64_encode($ciphertext)));
208 $cipher_json = base64_encode($encrypted_header_json_object);
210 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
213 <?xml version='1.0' encoding='UTF-8'?>
214 <diaspora xmlns="https://joindiaspora.org/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
217 <me:encoding>base64url</me:encoding>
218 <me:alg>RSA-SHA256</me:alg>
219 <me:data type="application/xml">$data</me:data>
220 <me:sig>$sig</me:sig>
225 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
232 * diaspora_decode($importer,$xml)
233 * array $importer -> from user table
234 * string $xml -> urldecoded Diaspora salmon
237 * 'message' -> decoded Diaspora XML message
238 * 'author' -> author diaspora handle
239 * 'key' -> author public key (converted to pkcs#8)
241 * Author and key are used elsewhere to save a lookup for verifying replies and likes
245 function diaspora_decode($importer,$xml) {
248 $basedom = parse_xml_string($xml);
250 $children = $basedom->children('https://joindiaspora.com/protocol');
252 if($children->header) {
254 $author_link = str_replace('acct:','',$children->header->author_id);
258 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
260 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
261 $ciphertext = base64_decode($encrypted_header->ciphertext);
263 $outer_key_bundle = '';
264 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
266 $j_outer_key_bundle = json_decode($outer_key_bundle);
268 $outer_iv = base64_decode($j_outer_key_bundle->iv);
269 $outer_key = base64_decode($j_outer_key_bundle->key);
271 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
274 $decrypted = pkcs5_unpad($decrypted);
277 * $decrypted now contains something like
280 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
281 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
286 * <name>Ryan Hughes</name>
287 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
292 * <author_id>acct:galaxor@diaspora.priateship.org</author_id>
296 * </decrypted_header>
299 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
300 $idom = parse_xml_string($decrypted,false);
302 $inner_iv = base64_decode($idom->iv);
303 $inner_aes_key = base64_decode($idom->aes_key);
305 $author_link = str_replace('acct:','',$idom->author_id);
309 $dom = $basedom->children(NAMESPACE_SALMON_ME);
311 // figure out where in the DOM tree our data is hiding
313 if($dom->provenance->data)
314 $base = $dom->provenance;
315 elseif($dom->env->data)
321 logger('mod-diaspora: unable to locate salmon data in xml ');
322 http_status_exit(400);
326 // Stash the signature away for now. We have to find their key or it won't be good for anything.
327 $signature = base64url_decode($base->sig);
331 // strip whitespace so our data element will return to one big base64 blob
332 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
335 // stash away some other stuff for later
337 $type = $base->data[0]->attributes()->type[0];
338 $keyhash = $base->sig[0]->attributes()->keyhash[0];
339 $encoding = $base->encoding;
343 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
347 $data = base64url_decode($data);
351 $inner_decrypted = $data;
355 // Decode the encrypted blob
357 $inner_encrypted = base64_decode($data);
358 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
359 $inner_decrypted = pkcs5_unpad($inner_decrypted);
363 logger('mod-diaspora: Could not retrieve author URI.');
364 http_status_exit(400);
367 // Once we have the author URI, go to the web and try to find their public key
368 // (first this will look it up locally if it is in the fcontact cache)
369 // This will also convert diaspora public key from pkcs#1 to pkcs#8
371 logger('mod-diaspora: Fetching key for ' . $author_link );
372 $key = get_diaspora_key($author_link);
375 logger('mod-diaspora: Could not retrieve author key.');
376 http_status_exit(400);
379 $verify = rsa_verify($signed_data,$signature,$key);
382 logger('mod-diaspora: Message did not verify. Discarding.');
383 http_status_exit(400);
386 logger('mod-diaspora: Message verified.');
388 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
393 function diaspora_request($importer,$xml) {
395 $sender_handle = unxmlify($xml->sender_handle);
396 $recipient_handle = unxmlify($xml->recipient_handle);
398 if(! $sender_handle || ! $recipient_handle)
401 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
405 // perhaps we were already sharing with this person. Now they're sharing with us.
406 // That makes us friends.
408 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
409 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
410 intval(CONTACT_IS_FRIEND),
411 intval($contact['id']),
412 intval($importer['uid'])
415 // send notification?
419 $ret = find_diaspora_person_by_handle($sender_handle);
422 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
423 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
427 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
428 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
429 intval($importer['uid']),
430 dbesc($ret['network']),
436 dbesc($ret['photo']),
437 dbesc($ret['pubkey']),
438 dbesc($ret['notify']),
444 // find the contact record we just created
446 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
448 $hash = random_string() . (string) time(); // Generate a confirm_key
450 if($contact_record) {
451 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
452 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
453 intval($importer['uid']),
454 intval($contact_record['id']),
457 dbesc( t('Sharing notification from Diaspora network')),
459 dbesc(datetime_convert())
466 function diaspora_post($importer,$xml) {
469 $guid = notags(unxmlify($xml->guid));
470 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
472 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
476 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
477 logger('diaspora_post: Ignoring this author.');
481 $message_id = $diaspora_handle . ':' . $guid;
482 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
483 intval($importer['uid']),
488 logger('diaspora_post: message exists: ' . $guid);
492 // allocate a guid on our system - we aren't fixing any collisions.
493 // we're ignoring them
495 $g = q("select * from guid where guid = '%s' limit 1",
499 q("insert into guid ( guid ) values ( '%s' )",
504 $created = unxmlify($xml->created_at);
505 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
507 $body = diaspora2bb($xml->raw_message);
510 $datarray['uid'] = $importer['uid'];
511 $datarray['contact-id'] = $contact['id'];
512 $datarray['wall'] = 0;
513 $datarray['guid'] = $guid;
514 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
515 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
516 $datarray['private'] = $private;
517 $datarray['parent'] = 0;
518 $datarray['owner-name'] = $contact['name'];
519 $datarray['owner-link'] = $contact['url'];
520 $datarray['owner-avatar'] = $contact['thumb'];
521 $datarray['author-name'] = $contact['name'];
522 $datarray['author-link'] = $contact['url'];
523 $datarray['author-avatar'] = $contact['thumb'];
524 $datarray['body'] = $body;
525 $datarray['app'] = 'Diaspora';
527 $message_id = item_store($datarray);
530 q("update item set plink = '%s' where id = %d limit 1",
531 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
540 function diaspora_comment($importer,$xml,$msg) {
543 $guid = notags(unxmlify($xml->guid));
544 $parent_guid = notags(unxmlify($xml->parent_guid));
545 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
546 $target_type = notags(unxmlify($xml->target_type));
547 $text = unxmlify($xml->text);
548 $author_signature = notags(unxmlify($xml->author_signature));
550 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
554 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
556 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
560 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
561 logger('diaspora_comment: Ignoring this author.');
565 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
566 intval($importer['uid']),
570 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
574 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
575 intval($importer['uid']),
579 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
582 $parent_item = $r[0];
584 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
586 $author_signature = base64_decode($author_signature);
588 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
593 $person = find_diaspora_person_by_handle($diaspora_handle);
595 if(is_array($person) && x($person,'pubkey'))
596 $key = $person['pubkey'];
598 logger('diaspora_comment: unable to find author details');
603 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
604 logger('diaspora_comment: verification failed.');
609 if($parent_author_signature) {
610 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
612 $parent_author_signature = base64_decode($parent_author_signature);
616 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
617 logger('diaspora_comment: owner verification failed.');
622 // Phew! Everything checks out. Now create an item.
624 $body = diaspora2bb($text);
626 $message_id = $diaspora_handle . ':' . $guid;
629 $datarray['uid'] = $importer['uid'];
630 $datarray['contact-id'] = $contact['id'];
631 $datarray['wall'] = $parent_item['wall'];
632 $datarray['gravity'] = GRAVITY_COMMENT;
633 $datarray['guid'] = $guid;
634 $datarray['uri'] = $message_id;
635 $datarray['parent-uri'] = $parent_item['uri'];
637 // No timestamps for comments? OK, we'll the use current time.
638 $datarray['created'] = $datarray['edited'] = datetime_convert();
639 $datarray['private'] = $parent_item['private'];
641 $datarray['owner-name'] = $contact['name'];
642 $datarray['owner-link'] = $contact['url'];
643 $datarray['owner-avatar'] = $contact['thumb'];
645 $datarray['author-name'] = $person['name'];
646 $datarray['author-link'] = $person['url'];
647 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
648 $datarray['body'] = $body;
649 $datarray['app'] = 'Diaspora';
651 $message_id = item_store($datarray);
654 q("update item set plink = '%s' where id = %d limit 1",
655 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
660 if(! $parent_author_signature) {
661 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
663 dbesc($author_signed_data),
664 dbesc(base64_encode($author_signature)),
665 dbesc($diaspora_handle)
668 // if the message isn't already being relayed, notify others
669 // the existence of parent_author_signature means the parent_author or owner
670 // is already relaying.
672 proc_run('php','include/notifier.php','comment',$message_id);
677 function diaspora_photo($importer,$xml,$msg) {
680 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
682 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
684 $status_message_guid = notags(unxmlify($xml->status_message_guid));
686 $guid = notags(unxmlify($xml->guid));
688 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
690 $public = notags(unxmlify($xml->public));
692 $created_at = notags(unxmlify($xml_created_at));
695 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
699 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
700 logger('diaspora_photo: Ignoring this author.');
704 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
705 intval($importer['uid']),
706 dbesc($status_message_guid)
709 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
712 $parent_item = $r[0];
714 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
716 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
717 dbesc($link_text . $parent_item['body']),
718 intval($parent_item['id']),
719 intval($parent_item['uid'])
728 function diaspora_like($importer,$xml,$msg) {
731 $guid = notags(unxmlify($xml->guid));
732 $parent_guid = notags(unxmlify($xml->parent_guid));
733 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
734 $target_type = notags(unxmlify($xml->target_type));
735 $positive = notags(unxmlify($xml->positive));
736 $author_signature = notags(unxmlify($xml->author_signature));
738 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
740 // likes on comments not supported here and likes on photos not supported by Diaspora
742 if($target_type !== 'Post')
745 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
747 logger('diaspora_like: cannot find contact: ' . $msg['author']);
751 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
752 logger('diaspora_like: Ignoring this author.');
756 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
757 intval($importer['uid']),
761 logger('diaspora_like: parent item not found: ' . $guid);
765 $parent_item = $r[0];
767 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
768 intval($importer['uid']),
772 if($positive === 'true') {
773 logger('diaspora_like: duplicate like: ' . $guid);
776 if($positive === 'false') {
777 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
779 intval($importer['uid'])
782 // send notification via proc_run()
786 if($positive === 'false') {
787 logger('diaspora_like: unlike received with no corresponding like');
791 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
793 $author_signature = base64_decode($author_signature);
795 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
800 $person = find_diaspora_person_by_handle($diaspora_handle);
801 if(is_array($person) && x($person,'pubkey'))
802 $key = $person['pubkey'];
804 logger('diaspora_like: unable to find author details');
809 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
810 logger('diaspora_like: verification failed.');
814 if($parent_author_signature) {
816 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
818 $parent_author_signature = base64_decode($parent_author_signature);
822 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
823 logger('diaspora_like: owner verification failed.');
828 // Phew! Everything checks out. Now create an item.
830 $uri = $diaspora_handle . ':' . $guid;
832 $activity = ACTIVITY_LIKE;
833 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
834 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
835 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
836 $body = $parent_item['body'];
841 <type>$objtype</type>
843 <id>{$parent_item['uri']}</id>
846 <content>$body</content>
849 $bodyverb = t('%1$s likes %2$s\'s %3$s');
854 $arr['uid'] = $importer['uid'];
855 $arr['guid'] = $guid;
856 $arr['contact-id'] = $contact['id'];
857 $arr['type'] = 'activity';
858 $arr['wall'] = $parent_item['wall'];
859 $arr['gravity'] = GRAVITY_LIKE;
860 $arr['parent'] = $parent_item['id'];
861 $arr['parent-uri'] = $parent_item['uri'];
863 $arr['owner-name'] = $contact['name'];
864 $arr['owner-link'] = $contact['url'];
865 $arr['owner-avatar'] = $contact['thumb'];
867 $arr['author-name'] = $person['name'];
868 $arr['author-link'] = $person['url'];
869 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
871 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
872 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
873 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
874 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
876 $arr['app'] = 'Diaspora';
878 $arr['private'] = $parent_item['private'];
879 $arr['verb'] = $activity;
880 $arr['object-type'] = $objtype;
881 $arr['object'] = $obj;
884 $arr['last-child'] = 0;
886 $message_id = item_store($arr);
890 q("update item set plink = '%s' where id = %d limit 1",
891 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
896 if(! $parent_author_signature) {
897 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
899 dbesc($author_signed_data),
900 dbesc(base64_encode($author_signature)),
901 dbesc($diaspora_handle)
905 // if the message isn't already being relayed, notify others
906 // the existence of parent_author_signature means the parent_author or owner
907 // is already relaying.
909 if(! $parent_author_signature)
910 proc_run('php','include/notifier.php','comment',$message_id);
915 function diaspora_retraction($importer,$xml) {
917 $guid = notags(unxmlify($xml->guid));
918 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
919 $type = notags(unxmlify($xml->type));
921 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
925 if($type === 'Person') {
926 contact_remove($contact['id']);
928 elseif($type === 'Post') {
929 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
931 intval($importer['uid'])
934 if(link_compare($r[0]['author-link'],$contact['url'])) {
935 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
936 dbesc(datetime_convert()),
947 function diaspora_share($me,$contact) {
949 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
950 $theiraddr = $contact['addr'];
952 $tpl = get_markup_template('diaspora_share.tpl');
953 $msg = replace_macros($tpl, array(
954 '$sender' => $myaddr,
955 '$recipient' => $theiraddr
958 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
960 return(diaspora_transmit($owner,$contact,$slap));
963 function diaspora_unshare($me,$contact) {
966 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
968 $tpl = get_markup_template('diaspora_retract.tpl');
969 $msg = replace_macros($tpl, array(
970 '$guid' => $me['guid'],
975 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
977 return(diaspora_transmit($owner,$contact,$slap));
983 function diaspora_send_status($item,$owner,$contact) {
986 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
987 $theiraddr = $contact['addr'];
991 $body = $item['body'];
993 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
995 foreach($matches as $mtch) {
997 $detail['str'] = $mtch[0];
998 $detail['path'] = dirname($mtch[1]) . '/';
999 $detail['file'] = basename($mtch[1]);
1000 $detail['guid'] = $item['guid'];
1001 $detail['handle'] = $myaddr;
1002 $images[] = $detail;
1003 $body = str_replace($detail['str'],t('link'),$body);
1007 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1009 $public = (($item['private']) ? 'false' : 'true');
1011 require_once('include/datetime.php');
1012 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1014 $tpl = get_markup_template('diaspora_post.tpl');
1015 $msg = replace_macros($tpl, array(
1017 '$guid' => $item['guid'],
1018 '$handle' => xmlify($myaddr),
1019 '$public' => $public,
1020 '$created' => $created
1023 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1025 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1027 $return_code = diaspora_transmit($owner,$contact,$slap);
1029 if(count($images)) {
1030 diaspora_send_images($item,$owner,$contact,$images);
1033 return $return_code;
1037 function diaspora_send_images($item,$owner,$contact,$images) {
1039 if(! count($images))
1041 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1043 $tpl = get_markup_template('diaspora_photo.tpl');
1044 foreach($images as $image) {
1045 if(! stristr($image['path'],$mysite))
1047 $resource = str_replace('.jpg','',$image['file']);
1048 $resource = substr($resource,0,strpos($resource,'-'));
1050 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1052 intval($owner['uid'])
1056 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1057 $msg = replace_macros($tpl,array(
1058 '$path' => xmlify($image['path']),
1059 '$filename' => xmlify($image['file']),
1060 '$msg_guid' => xmlify($image['guid']),
1061 '$guid' => xmlify($r[0]['guid']),
1062 '$handle' => xmlify($image['handle']),
1063 '$public' => xmlify($public),
1064 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1068 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1069 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1071 diaspora_transmit($owner,$contact,$slap);
1076 function diaspora_send_followup($item,$owner,$contact) {
1079 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1080 $theiraddr = $contact['addr'];
1082 $p = q("select guid from item where parent = %d limit 1",
1086 $parent_guid = $p[0]['guid'];
1090 if($item['verb'] === ACTIVITY_LIKE) {
1091 $tpl = get_markup_template('diaspora_like.tpl');
1093 $target_type = 'Post';
1094 $positive = (($item['deleted']) ? 'false' : 'true');
1097 $tpl = get_markup_template('diaspora_comment.tpl');
1101 $text = html_entity_decode(bb2diaspora($item['body']));
1106 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1108 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1110 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1112 $msg = replace_macros($tpl,array(
1113 '$guid' => xmlify($item['guid']),
1114 '$parent_guid' => xmlify($parent_guid),
1115 '$target_type' =>xmlify($target_type),
1116 '$authorsig' => xmlify($authorsig),
1117 '$body' => xmlify($text),
1118 '$positive' => xmlify($positive),
1119 '$handle' => xmlify($myaddr)
1122 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1124 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1126 return(diaspora_transmit($owner,$contact,$slap));
1130 function diaspora_send_relay($item,$owner,$contact) {
1134 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1135 $theiraddr = $contact['addr'];
1138 $p = q("select guid from item where parent = %d limit 1",
1142 $parent_guid = $p[0]['guid'];
1146 if($item['verb'] === ACTIVITY_LIKE) {
1147 $tpl = get_markup_template('diaspora_like_relay.tpl');
1149 $target_type = 'Post';
1150 $positive = (($item['deleted']) ? 'false' : 'true');
1153 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1157 $body = $item['body'];
1159 $text = html_entity_decode(bb2diaspora($body));
1161 // fetch the original signature if somebody sent the post to us to relay
1162 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1163 // action. It wasn't needed. In that case create the original signature and the
1164 // owner (parent author) signature
1165 // comments from other networks will be relayed under our name, with a brief
1166 // preamble to describe what's happening and noting the real author
1168 $r = q("select * from sign where iid = %d limit 1",
1173 $signed_text = $orig_sign['signed_text'];
1174 $authorsig = $orig_sign['signature'];
1175 $handle = $orig_sign['signer'];
1179 $itemcontact = q("select * from contact where `id` = %d limit 1",
1180 intval($item['contact-id'])
1182 if(count($itemcontact)) {
1183 if(! $itemcontact[0]['self']) {
1184 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1185 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1186 network_to_name($itemcontact['network'])) . "\n";
1187 $body = $prefix . $body;
1193 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1195 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1197 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1199 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1200 intval($item['id']),
1201 dbesc($signed_text),
1202 dbesc(base64_encode($authorsig)),
1211 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1213 $msg = replace_macros($tpl,array(
1214 '$guid' => xmlify($item['guid']),
1215 '$parent_guid' => xmlify($parent_guid),
1216 '$target_type' =>xmlify($target_type),
1217 '$authorsig' => xmlify($orig_sign['signature']),
1218 '$parentsig' => xmlify($parentauthorsig),
1219 '$body' => xmlify($text),
1220 '$positive' => xmlify($positive),
1221 '$handle' => xmlify($handle)
1224 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1226 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1228 return(diaspora_transmit($owner,$contact,$slap));
1234 function diaspora_send_retraction($item,$owner,$contact) {
1237 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1239 $tpl = get_markup_template('diaspora_retract.tpl');
1240 $msg = replace_macros($tpl, array(
1241 '$guid' => $item['guid'],
1243 '$handle' => $myaddr
1246 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1248 return(diaspora_transmit($owner,$contact,$slap));
1253 function diaspora_transmit($owner,$contact,$slap) {
1257 post_url($contact['notify'] . '/',$slap);
1258 $return_code = $a->get_curl_code();
1259 logger('diaspora_transmit: returns: ' . $return_code);
1261 if(! $return_code) {
1262 logger('diaspora_transmit: queue message');
1263 // queue message for redelivery
1264 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
1265 VALUES ( %d, '%s', '%s', '%s') ",
1266 intval($contact['id']),
1267 dbesc(datetime_convert()),
1268 dbesc(datetime_convert()),
1273 return(($return_code) ? $return_code : (-1));