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' ) ",
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) {
71 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
72 dbesc(NETWORK_DIASPORA),
76 // update record occasionally so it doesn't get stale
77 $d = strtotime($r[0]['updated'] . ' +00:00');
78 if($d < strtotime('now - 14 days')) {
79 q("delete from fcontact where id = %d limit 1",
86 require_once('include/Scrape.php');
87 $r = probe_url($handle, PROBE_DIASPORA);
88 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
96 function get_diaspora_key($uri) {
97 logger('Fetching diaspora key for: ' . $uri);
99 $r = find_diaspora_person_by_handle($uri);
106 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
109 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
111 $inner_aes_key = random_string(32);
112 $b_inner_aes_key = base64_encode($inner_aes_key);
113 $inner_iv = random_string(16);
114 $b_inner_iv = base64_encode($inner_iv);
116 $outer_aes_key = random_string(32);
117 $b_outer_aes_key = base64_encode($outer_aes_key);
118 $outer_iv = random_string(16);
119 $b_outer_iv = base64_encode($outer_iv);
121 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
123 $padded_data = pkcs5_pad($msg,16);
124 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
126 $b64_data = base64_encode($inner_encrypted);
129 $b64url_data = base64url_encode($b64_data);
130 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
132 $type = 'application/xml';
133 $encoding = 'base64url';
136 $signable_data = $data . '.' . base64url_encode($type) . '.'
137 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
139 $signature = rsa_sign($signable_data,$prvkey);
140 $sig = base64url_encode($signature);
142 $decrypted_header = <<< EOT
145 <aes_key>$b_inner_aes_key</aes_key>
146 <author_id>$handle</author_id>
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 <diaspora xmlns="https://joindiaspora.org/protocol" 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('https://joindiaspora.com/protocol');
209 if($children->header) {
211 $author_link = str_replace('acct:','',$children->header->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);
292 // stash away some other stuff for later
294 $type = $base->data[0]->attributes()->type[0];
295 $keyhash = $base->sig[0]->attributes()->keyhash[0];
296 $encoding = $base->encoding;
300 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
304 $data = base64url_decode($data);
308 $inner_decrypted = $data;
312 // Decode the encrypted blob
314 $inner_encrypted = base64_decode($data);
315 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
316 $inner_decrypted = pkcs5_unpad($inner_decrypted);
320 logger('mod-diaspora: Could not retrieve author URI.');
321 http_status_exit(400);
324 // Once we have the author URI, go to the web and try to find their public key
325 // (first this will look it up locally if it is in the fcontact cache)
326 // This will also convert diaspora public key from pkcs#1 to pkcs#8
328 logger('mod-diaspora: Fetching key for ' . $author_link );
329 $key = get_diaspora_key($author_link);
332 logger('mod-diaspora: Could not retrieve author key.');
333 http_status_exit(400);
336 $verify = rsa_verify($signed_data,$signature,$key);
339 logger('mod-diaspora: Message did not verify. Discarding.');
340 // http_status_exit(400);
343 logger('mod-diaspora: Message verified.');
345 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
350 function diaspora_request($importer,$xml) {
352 $sender_handle = unxmlify($xml->sender_handle);
353 $recipient_handle = unxmlify($xml->recipient_handle);
355 if(! $sender_handle || ! $recipient_handle)
358 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
362 // perhaps we were already sharing with this person. Now they're sharing with us.
363 // That makes us friends.
365 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
366 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
367 intval(CONTACT_IS_FRIEND),
368 intval($contact['id']),
369 intval($importer['uid'])
372 // send notification?
376 $ret = find_diaspora_person_by_handle($sender_handle);
379 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
380 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
384 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
385 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
386 intval($importer['uid']),
387 dbesc($ret['network']),
393 dbesc($ret['photo']),
394 dbesc($ret['pubkey']),
395 dbesc($ret['notify']),
401 // find the contact record we just created
403 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
405 $hash = random_string() . (string) time(); // Generate a confirm_key
407 if($contact_record) {
408 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
409 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
410 intval($importer['uid']),
411 intval($contact_record['id']),
414 dbesc( t('Sharing notification from Diaspora network')),
416 dbesc(datetime_convert())
423 function diaspora_post($importer,$xml) {
426 $guid = notags(unxmlify($xml->guid));
427 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
429 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
433 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
434 logger('diaspora_post: Ignoring this author.');
438 $message_id = $diaspora_handle . ':' . $guid;
439 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
440 intval($importer['uid']),
445 logger('diaspora_post: message exists: ' . $guid);
449 // allocate a guid on our system - we aren't fixing any collisions.
450 // we're ignoring them
452 $g = q("select * from guid where guid = '%s' limit 1",
456 q("insert into guid ( guid ) values ( '%s' )",
461 $created = unxmlify($xml->created_at);
462 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
464 $body = diaspora2bb($xml->raw_message);
467 $datarray['uid'] = $importer['uid'];
468 $datarray['contact-id'] = $contact['id'];
469 $datarray['wall'] = 0;
470 $datarray['guid'] = $guid;
471 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
472 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
473 $datarray['private'] = $private;
474 $datarray['parent'] = 0;
475 $datarray['owner-name'] = $contact['name'];
476 $datarray['owner-link'] = $contact['url'];
477 $datarray['owner-avatar'] = $contact['thumb'];
478 $datarray['author-name'] = $contact['name'];
479 $datarray['author-link'] = $contact['url'];
480 $datarray['author-avatar'] = $contact['thumb'];
481 $datarray['body'] = $body;
482 $datarray['app'] = 'Diaspora';
484 $message_id = item_store($datarray);
487 q("update item set plink = '%s' where id = %d limit 1",
488 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
497 function diaspora_comment($importer,$xml,$msg) {
500 $guid = notags(unxmlify($xml->guid));
501 $parent_guid = notags(unxmlify($xml->parent_guid));
502 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
503 $target_type = notags(unxmlify($xml->target_type));
504 $text = unxmlify($xml->text);
505 $author_signature = notags(unxmlify($xml->author_signature));
507 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
511 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
513 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
517 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
518 logger('diaspora_comment: Ignoring this author.');
522 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
523 intval($importer['uid']),
527 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
531 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
532 intval($importer['uid']),
536 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
539 $parent_item = $r[0];
541 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
543 $author_signature = base64_decode($author_signature);
545 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
550 $person = find_diaspora_person_by_handle($diaspora_handle);
552 if(is_array($person) && x($person,'pubkey'))
553 $key = $person['pubkey'];
555 logger('diaspora_comment: unable to find author details');
560 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
561 logger('diaspora_comment: verification failed.');
566 if($parent_author_signature) {
567 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
569 $parent_author_signature = base64_decode($parent_author_signature);
573 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
574 logger('diaspora_comment: owner verification failed.');
579 // Phew! Everything checks out. Now create an item.
581 $body = diaspora2bb($text);
583 $message_id = $diaspora_handle . ':' . $guid;
586 $datarray['uid'] = $importer['uid'];
587 $datarray['contact-id'] = $contact['id'];
588 $datarray['wall'] = $parent_item['wall'];
589 $datarray['gravity'] = GRAVITY_COMMENT;
590 $datarray['guid'] = $guid;
591 $datarray['uri'] = $message_id;
592 $datarray['parent-uri'] = $parent_item['uri'];
594 // No timestamps for comments? OK, we'll the use current time.
595 $datarray['created'] = $datarray['edited'] = datetime_convert();
596 $datarray['private'] = $parent_item['private'];
598 $datarray['owner-name'] = $contact['name'];
599 $datarray['owner-link'] = $contact['url'];
600 $datarray['owner-avatar'] = $contact['thumb'];
602 $datarray['author-name'] = $person['name'];
603 $datarray['author-link'] = $person['url'];
604 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
605 $datarray['body'] = $body;
606 $datarray['app'] = 'Diaspora';
608 $message_id = item_store($datarray);
611 q("update item set plink = '%s' where id = %d limit 1",
612 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
617 if(! $parent_author_signature) {
618 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
620 dbesc($author_signed_data),
621 dbesc(base64_encode($author_signature)),
622 dbesc($diaspora_handle)
625 // if the message isn't already being relayed, notify others
626 // the existence of parent_author_signature means the parent_author or owner
627 // is already relaying.
629 proc_run('php','include/notifier.php','comment',$message_id);
634 function diaspora_photo($importer,$xml,$msg) {
637 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
639 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
641 $status_message_guid = notags(unxmlify($xml->status_message_guid));
643 $guid = notags(unxmlify($xml->guid));
645 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
647 $public = notags(unxmlify($xml->public));
649 $created_at = notags(unxmlify($xml_created_at));
652 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
656 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
657 logger('diaspora_photo: Ignoring this author.');
661 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
662 intval($importer['uid']),
663 dbesc($status_message_guid)
666 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
669 $parent_item = $r[0];
671 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
673 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
674 dbesc($link_text . $parent_item['body']),
675 intval($parent_item['id']),
676 intval($parent_item['uid'])
685 function diaspora_like($importer,$xml,$msg) {
688 $guid = notags(unxmlify($xml->guid));
689 $parent_guid = notags(unxmlify($xml->parent_guid));
690 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
691 $target_type = notags(unxmlify($xml->target_type));
692 $positive = notags(unxmlify($xml->positive));
693 $author_signature = notags(unxmlify($xml->author_signature));
695 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
697 // likes on comments not supported here and likes on photos not supported by Diaspora
699 if($target_type !== 'Post')
702 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
704 logger('diaspora_like: cannot find contact: ' . $msg['author']);
708 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
709 logger('diaspora_like: Ignoring this author.');
713 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
714 intval($importer['uid']),
718 logger('diaspora_like: parent item not found: ' . $guid);
722 $parent_item = $r[0];
724 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
725 intval($importer['uid']),
729 if($positive === 'true') {
730 logger('diaspora_like: duplicate like: ' . $guid);
733 if($positive === 'false') {
734 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
736 intval($importer['uid'])
739 // send notification via proc_run()
743 if($positive === 'false') {
744 logger('diaspora_like: unlike received with no corresponding like');
748 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
750 $author_signature = base64_decode($author_signature);
752 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
757 $person = find_diaspora_person_by_handle($diaspora_handle);
758 if(is_array($person) && x($person,'pubkey'))
759 $key = $person['pubkey'];
761 logger('diaspora_like: unable to find author details');
766 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
767 logger('diaspora_like: verification failed.');
771 if($parent_author_signature) {
773 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
775 $parent_author_signature = base64_decode($parent_author_signature);
779 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
780 logger('diaspora_like: owner verification failed.');
785 // Phew! Everything checks out. Now create an item.
787 $uri = $diaspora_handle . ':' . $guid;
789 $activity = ACTIVITY_LIKE;
790 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
791 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
792 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
793 $body = $parent_item['body'];
798 <type>$objtype</type>
800 <id>{$parent_item['uri']}</id>
803 <content>$body</content>
806 $bodyverb = t('%1$s likes %2$s\'s %3$s');
811 $arr['uid'] = $importer['uid'];
812 $arr['guid'] = $guid;
813 $arr['contact-id'] = $contact['id'];
814 $arr['type'] = 'activity';
815 $arr['wall'] = $parent_item['wall'];
816 $arr['gravity'] = GRAVITY_LIKE;
817 $arr['parent'] = $parent_item['id'];
818 $arr['parent-uri'] = $parent_item['uri'];
820 $arr['owner-name'] = $contact['name'];
821 $arr['owner-link'] = $contact['url'];
822 $arr['owner-avatar'] = $contact['thumb'];
824 $arr['author-name'] = $person['name'];
825 $arr['author-link'] = $person['url'];
826 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
828 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
829 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
830 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
831 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
833 $arr['app'] = 'Diaspora';
835 $arr['private'] = $parent_item['private'];
836 $arr['verb'] = $activity;
837 $arr['object-type'] = $objtype;
838 $arr['object'] = $obj;
841 $arr['last-child'] = 0;
843 $message_id = item_store($arr);
847 q("update item set plink = '%s' where id = %d limit 1",
848 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
853 if(! $parent_author_signature) {
854 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
856 dbesc($author_signed_data),
857 dbesc(base64_encode($author_signature)),
858 dbesc($diaspora_handle)
862 // if the message isn't already being relayed, notify others
863 // the existence of parent_author_signature means the parent_author or owner
864 // is already relaying.
866 if(! $parent_author_signature)
867 proc_run('php','include/notifier.php','comment',$message_id);
872 function diaspora_retraction($importer,$xml) {
874 $guid = notags(unxmlify($xml->guid));
875 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
876 $type = notags(unxmlify($xml->type));
878 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
882 if($type === 'Person') {
883 contact_remove($contact['id']);
885 elseif($type === 'Post') {
886 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
888 intval($importer['uid'])
891 if(link_compare($r[0]['author-link'],$contact['url'])) {
892 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
893 dbesc(datetime_convert()),
904 function diaspora_share($me,$contact) {
906 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
907 $theiraddr = $contact['addr'];
909 $tpl = get_markup_template('diaspora_share.tpl');
910 $msg = replace_macros($tpl, array(
911 '$sender' => $myaddr,
912 '$recipient' => $theiraddr
915 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
917 return(diaspora_transmit($owner,$contact,$slap));
920 function diaspora_unshare($me,$contact) {
923 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
925 $tpl = get_markup_template('diaspora_retract.tpl');
926 $msg = replace_macros($tpl, array(
927 '$guid' => $me['guid'],
932 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
934 return(diaspora_transmit($owner,$contact,$slap));
940 function diaspora_send_status($item,$owner,$contact) {
943 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
944 $theiraddr = $contact['addr'];
948 $body = $item['body'];
950 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
952 foreach($matches as $mtch) {
954 $detail['str'] = $mtch[0];
955 $detail['path'] = dirname($mtch[1]) . '/';
956 $detail['file'] = basename($mtch[1]);
957 $detail['guid'] = $item['guid'];
958 $detail['handle'] = $myaddr;
960 $body = str_replace($detail['str'],t('link'),$body);
964 $body = xmlify(html_entity_decode(bb2diaspora($body)));
966 $public = (($item['private']) ? 'false' : 'true');
968 require_once('include/datetime.php');
969 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
971 $tpl = get_markup_template('diaspora_post.tpl');
972 $msg = replace_macros($tpl, array(
974 '$guid' => $item['guid'],
975 '$handle' => xmlify($myaddr),
976 '$public' => $public,
977 '$created' => $created
980 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
982 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
984 $return_code = diaspora_transmit($owner,$contact,$slap);
987 diaspora_send_images($item,$owner,$contact,$images);
994 function diaspora_send_images($item,$owner,$contact,$images) {
998 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1000 $tpl = get_markup_template('diaspora_photo.tpl');
1001 foreach($images as $image) {
1002 if(! stristr($image['path'],$mysite))
1004 $resource = str_replace('.jpg','',$image['file']);
1005 $resource = substr($resource,0,strpos($resource,'-'));
1007 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1009 intval($owner['uid'])
1013 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1014 $msg = replace_macros($tpl,array(
1015 '$path' => xmlify($image['path']),
1016 '$filename' => xmlify($image['file']),
1017 '$msg_guid' => xmlify($image['guid']),
1018 '$guid' => xmlify($r[0]['guid']),
1019 '$handle' => xmlify($image['handle']),
1020 '$public' => xmlify($public),
1021 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1025 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1026 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1028 diaspora_transmit($owner,$contact,$slap);
1033 function diaspora_send_followup($item,$owner,$contact) {
1036 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1037 $theiraddr = $contact['addr'];
1039 $p = q("select guid from item where parent = %d limit 1",
1043 $parent_guid = $p[0]['guid'];
1047 if($item['verb'] === ACTIVITY_LIKE) {
1048 $tpl = get_markup_template('diaspora_like.tpl');
1050 $target_type = 'Post';
1051 $positive = (($item['deleted']) ? 'false' : 'true');
1054 $tpl = get_markup_template('diaspora_comment.tpl');
1058 $text = html_entity_decode(bb2diaspora($item['body']));
1063 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1065 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1067 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1069 $msg = replace_macros($tpl,array(
1070 '$guid' => xmlify($item['guid']),
1071 '$parent_guid' => xmlify($parent_guid),
1072 '$target_type' =>xmlify($target_type),
1073 '$authorsig' => xmlify($authorsig),
1074 '$body' => xmlify($text),
1075 '$positive' => xmlify($positive),
1076 '$handle' => xmlify($myaddr)
1079 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1081 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1083 return(diaspora_transmit($owner,$contact,$slap));
1087 function diaspora_send_relay($item,$owner,$contact) {
1091 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1092 $theiraddr = $contact['addr'];
1095 $p = q("select guid from item where parent = %d limit 1",
1099 $parent_guid = $p[0]['guid'];
1103 if($item['verb'] === ACTIVITY_LIKE) {
1104 $tpl = get_markup_template('diaspora_like_relay.tpl');
1106 $target_type = 'Post';
1107 $positive = (($item['deleted']) ? 'false' : 'true');
1110 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1114 $body = $item['body'];
1116 $text = html_entity_decode(bb2diaspora($body));
1118 // fetch the original signature if somebody sent the post to us to relay
1119 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1120 // action. It wasn't needed. In that case create the original signature and the
1121 // owner (parent author) signature
1122 // comments from other networks will be relayed under our name, with a brief
1123 // preamble to describe what's happening and noting the real author
1125 $r = q("select * from sign where iid = %d limit 1",
1130 $signed_text = $orig_sign['signed_text'];
1131 $authorsig = $orig_sign['signature'];
1132 $handle = $orig_sign['signer'];
1136 $itemcontact = q("select * from contact where `id` = %d limit 1",
1137 intval($item['contact-id'])
1139 if(count($itemcontact)) {
1140 if(! $itemcontact[0]['self']) {
1141 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1142 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1143 network_to_name($itemcontact['network'])) . "\n";
1144 $body = $prefix . $body;
1150 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1152 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1154 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1156 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1157 intval($item['id']),
1158 dbesc($signed_text),
1159 dbesc(base64_encode($authorsig)),
1168 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1170 $msg = replace_macros($tpl,array(
1171 '$guid' => xmlify($item['guid']),
1172 '$parent_guid' => xmlify($parent_guid),
1173 '$target_type' =>xmlify($target_type),
1174 '$authorsig' => xmlify($orig_sign['signature']),
1175 '$parentsig' => xmlify($parentauthorsig),
1176 '$body' => xmlify($text),
1177 '$positive' => xmlify($positive),
1178 '$handle' => xmlify($handle)
1181 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1183 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1185 return(diaspora_transmit($owner,$contact,$slap));
1191 function diaspora_send_retraction($item,$owner,$contact) {
1194 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1196 $tpl = get_markup_template('diaspora_retract.tpl');
1197 $msg = replace_macros($tpl, array(
1198 '$guid' => $item['guid'],
1200 '$handle' => $myaddr
1203 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1205 return(diaspora_transmit($owner,$contact,$slap));
1210 function diaspora_transmit($owner,$contact,$slap) {
1214 post_url($contact['notify'] . '/',$slap);
1215 $return_code = $a->get_curl_code();
1216 logger('diaspora_transmit: returns: ' . $return_code);
1218 if(! $return_code) {
1219 logger('diaspora_transmit: queue message');
1220 // queue message for redelivery
1221 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
1222 VALUES ( %d, '%s', '%s', '%s') ",
1223 intval($contact['id']),
1224 dbesc(datetime_convert()),
1225 dbesc(datetime_convert()),
1230 return(($return_code) ? $return_code : (-1));