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');
8 function diaspora_dispatch($importer,$msg) {
10 $parsed_xml = parse_xml_string($msg['message'],false);
12 $xmlbase = $parsed_xml->post;
14 if($xmlbase->request) {
15 diaspora_request($importer,$xmlbase->request);
17 elseif($xmlbase->status_message) {
18 diaspora_post($importer,$xmlbase->status_message);
20 elseif($xmlbase->comment) {
21 diaspora_comment($importer,$xmlbase->comment,$msg);
23 elseif($xmlbase->like) {
24 diaspora_like($importer,$xmlbase->like,$msg);
26 elseif($xmlbase->retraction) {
27 diaspora_retraction($importer,$xmlbase->retraction,$msg);
29 elseif($xmlbase->photo) {
30 diaspora_photo($importer,$xmlbase->photo,$msg);
33 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
38 function diaspora_get_contact_by_handle($uid,$handle) {
39 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
40 dbesc(NETWORK_DIASPORA),
49 function find_diaspora_person_by_handle($handle) {
50 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
51 dbesc(NETWORK_DIASPORA),
55 // update record occasionally so it doesn't get stale
56 $d = strtotime($r[0]['updated'] . ' +00:00');
57 if($d < strtotime('now - 14 days')) {
58 q("delete from fcontact where id = %d limit 1",
65 require_once('include/Scrape.php');
66 $r = probe_url($handle, PROBE_DIASPORA);
67 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
75 function get_diaspora_key($uri) {
76 logger('Fetching diaspora key for: ' . $uri);
78 $r = find_diaspora_person_by_handle($uri);
85 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
88 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
90 $inner_aes_key = random_string(32);
91 $b_inner_aes_key = base64_encode($inner_aes_key);
92 $inner_iv = random_string(16);
93 $b_inner_iv = base64_encode($inner_iv);
95 $outer_aes_key = random_string(32);
96 $b_outer_aes_key = base64_encode($outer_aes_key);
97 $outer_iv = random_string(16);
98 $b_outer_iv = base64_encode($outer_iv);
100 $handle = 'acct:' . $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
102 $padded_data = pkcs5_pad($msg,16);
103 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
105 $b64_data = base64_encode($inner_encrypted);
108 $b64url_data = base64url_encode($b64_data);
109 $b64url_stripped = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
110 $lines = str_split($b64url_stripped,60);
111 $data = implode("\n",$lines);
112 $data = $data . (($data[-1] != "\n") ? "\n" : '') ;
113 $type = 'application/atom+xml';
114 $encoding = 'base64url';
117 $signable_data = $data . '.' . base64url_encode($type) . "\n" . '.'
118 . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
120 $signature = rsa_sign($signable_data,$prvkey);
121 $sig = base64url_encode($signature);
123 $decrypted_header = <<< EOT
126 <aes_key>$b_inner_aes_key</aes_key>
128 <name>{$user['username']}</name>
134 $decrypted_header = pkcs5_pad($decrypted_header,16);
136 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
138 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
140 $encrypted_outer_key_bundle = '';
141 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
143 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
145 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
147 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
148 'ciphertext' => base64_encode($ciphertext)));
149 $cipher_json = base64_encode($encrypted_header_json_object);
151 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
154 <?xml version='1.0' encoding='UTF-8'?>
155 <entry xmlns='http://www.w3.org/2005/Atom'>
157 <me:env xmlns:me="http://salmon-protocol.org/ns/magic-env">
158 <me:encoding>base64url</me:encoding>
159 <me:alg>RSA-SHA256</me:alg>
160 <me:data type="application/atom+xml">$data</me:data>
161 <me:sig>$sig</me:sig>
166 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
173 * diaspora_decode($importer,$xml)
174 * array $importer -> from user table
175 * string $xml -> urldecoded Diaspora salmon
178 * 'message' -> decoded Diaspora XML message
179 * 'author' -> author diaspora handle
180 * 'key' -> author public key (converted to pkcs#8)
182 * Author and key are used elsewhere to save a lookup for verifying replies and likes
186 function diaspora_decode($importer,$xml) {
188 $basedom = parse_xml_string($xml);
190 $atom = $basedom->children(NAMESPACE_ATOM1);
192 // Diaspora devs: This is kind of sucky - 'encrypted_header' does not belong in the atom namespace
194 $encrypted_header = json_decode(base64_decode($atom->encrypted_header));
196 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
197 $ciphertext = base64_decode($encrypted_header->ciphertext);
199 $outer_key_bundle = '';
200 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
202 $j_outer_key_bundle = json_decode($outer_key_bundle);
204 $outer_iv = base64_decode($j_outer_key_bundle->iv);
205 $outer_key = base64_decode($j_outer_key_bundle->key);
207 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
210 $decrypted = pkcs5_unpad($decrypted);
213 * $decrypted now contains something like
216 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
217 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
219 * <name>Ryan Hughes</name>
220 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
222 * </decrypted_header>
225 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
226 $idom = parse_xml_string($decrypted,false);
228 $inner_iv = base64_decode($idom->iv);
229 $inner_aes_key = base64_decode($idom->aes_key);
231 $author_link = str_replace('acct:','',$idom->author->uri);
233 $dom = $basedom->children(NAMESPACE_SALMON_ME);
235 // figure out where in the DOM tree our data is hiding
237 if($dom->provenance->data)
238 $base = $dom->provenance;
239 elseif($dom->env->data)
245 logger('mod-diaspora: unable to locate salmon data in xml ');
246 http_status_exit(400);
250 // Stash the signature away for now. We have to find their key or it won't be good for anything.
251 $signature = base64url_decode($base->sig);
255 // strip whitespace so our data element will return to one big base64 blob
256 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
258 // Add back the 60 char linefeeds
260 // This completely violates the entire principle of salmon magic signatures,
261 // which was to have a message signing format that was completely ambivalent to linefeeds
262 // and transport whitespace mangling, and base64 wrapping rules. Guess what? PHP and Ruby
263 // use different linelengths for base64 output.
265 $lines = str_split($data,60);
266 $data = implode("\n",$lines);
269 // stash away some other stuff for later
271 $type = $base->data[0]->attributes()->type[0];
272 $keyhash = $base->sig[0]->attributes()->keyhash[0];
273 $encoding = $base->encoding;
276 // I can't even begin to tell you how sucky this is. Please read the spec.
278 $signed_data = $data . (($data[-1] != "\n") ? "\n" : '') . '.' . base64url_encode($type) . "\n" . '.' . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
282 $data = base64url_decode($data);
284 // Now pull out the inner encrypted blob
286 $inner_encrypted = base64_decode($data);
289 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
291 $inner_decrypted = pkcs5_unpad($inner_decrypted);
294 logger('mod-diaspora: Could not retrieve author URI.');
295 http_status_exit(400);
298 // Once we have the author URI, go to the web and try to find their public key
299 // (first this will look it up locally if it is in the fcontact cache)
300 // This will also convert diaspora public key from pkcs#1 to pkcs#8
302 logger('mod-diaspora: Fetching key for ' . $author_link );
303 $key = get_diaspora_key($author_link);
306 logger('mod-diaspora: Could not retrieve author key.');
307 http_status_exit(400);
310 $verify = rsa_verify($signed_data,$signature,$key);
313 logger('mod-diaspora: Message did not verify. Discarding.');
314 http_status_exit(400);
317 logger('mod-diaspora: Message verified.');
319 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
325 function diaspora_request($importer,$xml) {
327 $sender_handle = unxmlify($xml->sender_handle);
328 $recipient_handle = unxmlify($xml->recipient_handle);
330 if(! $sender_handle || ! $recipient_handle)
333 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
338 // perhaps we were already sharing with this person. Now they're sharing with us.
339 // That makes us friends.
341 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
342 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
343 intval(CONTACT_IS_FRIEND),
344 intval($contact['id']),
345 intval($importer['uid'])
348 // send notification?
352 $ret = find_diaspora_person_by_handle($sender_handle);
355 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
356 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
360 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
361 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
362 intval($importer['uid']),
363 dbesc($ret['network']),
369 dbesc($ret['photo']),
370 dbesc($ret['pubkey']),
371 dbesc($ret['notify']),
377 // find the contact record we just created
379 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
381 $hash = random_string() . (string) time(); // Generate a confirm_key
383 if($contact_record) {
384 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
385 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
386 intval($importer['uid']),
387 intval($contact_record['id']),
390 dbesc( t('Sharing notification from Diaspora network')),
392 dbesc(datetime_convert())
399 function diaspora_post($importer,$xml) {
402 $guid = notags(unxmlify($xml->guid));
403 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
405 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
409 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
410 logger('diaspora_post: Ignoring this author.');
411 http_status_exit(202);
415 $message_id = $diaspora_handle . ':' . $guid;
416 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
417 intval($importer['uid']),
422 logger('diaspora_post: message exists: ' . $guid);
426 // allocate a guid on our system - we aren't fixing any collisions.
427 // we're ignoring them
429 $g = q("select * from guid where guid = '%s' limit 1",
433 q("insert into guid ( guid ) values ( '%s' )",
438 $created = unxmlify($xml->created_at);
439 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
441 $body = diaspora2bb($xml->raw_message);
444 $datarray['uid'] = $importer['uid'];
445 $datarray['contact-id'] = $contact['id'];
446 $datarray['wall'] = 0;
447 $datarray['guid'] = $guid;
448 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
449 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
450 $datarray['private'] = $private;
451 $datarray['parent'] = 0;
452 $datarray['owner-name'] = $contact['name'];
453 $datarray['owner-link'] = $contact['url'];
454 $datarray['owner-avatar'] = $contact['thumb'];
455 $datarray['author-name'] = $contact['name'];
456 $datarray['author-link'] = $contact['url'];
457 $datarray['author-avatar'] = $contact['thumb'];
458 $datarray['body'] = $body;
459 $datarray['app'] = 'Diaspora';
461 $message_id = item_store($datarray);
464 q("update item set plink = '%s' where id = %d limit 1",
465 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
474 function diaspora_comment($importer,$xml,$msg) {
477 $guid = notags(unxmlify($xml->guid));
478 $parent_guid = notags(unxmlify($xml->parent_guid));
479 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
480 $target_type = notags(unxmlify($xml->target_type));
481 $text = unxmlify($xml->text);
482 $author_signature = notags(unxmlify($xml->author_signature));
484 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
488 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
490 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
494 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
495 logger('diaspora_comment: Ignoring this author.');
496 http_status_exit(202);
500 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
501 intval($importer['uid']),
505 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
509 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
510 intval($importer['uid']),
514 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
517 $parent_item = $r[0];
519 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
521 $author_signature = base64_decode($author_signature);
523 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
528 $person = find_diaspora_person_by_handle($diaspora_handle);
530 if(is_array($person) && x($person,'pubkey'))
531 $key = $person['pubkey'];
533 logger('diaspora_comment: unable to find author details');
538 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha')) {
539 logger('diaspora_comment: verification failed.');
544 if($parent_author_signature) {
545 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
547 $parent_author_signature = base64_decode($parent_author_signature);
551 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha')) {
552 logger('diaspora_comment: owner verification failed.');
557 // Phew! Everything checks out. Now create an item.
559 $body = diaspora2bb($text);
561 $message_id = $diaspora_handle . ':' . $guid;
564 $datarray['uid'] = $importer['uid'];
565 $datarray['contact-id'] = $contact['id'];
566 $datarray['wall'] = $parent_item['wall'];
567 $datarray['gravity'] = GRAVITY_COMMENT;
568 $datarray['guid'] = $guid;
569 $datarray['uri'] = $message_id;
570 $datarray['parent-uri'] = $parent_item['uri'];
572 // No timestamps for comments? OK, we'll the use current time.
573 $datarray['created'] = $datarray['edited'] = datetime_convert();
574 $datarray['private'] = $parent_item['private'];
576 $datarray['owner-name'] = $contact['name'];
577 $datarray['owner-link'] = $contact['url'];
578 $datarray['owner-avatar'] = $contact['thumb'];
580 $datarray['author-name'] = $person['name'];
581 $datarray['author-link'] = $person['url'];
582 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
583 $datarray['body'] = $body;
584 $datarray['app'] = 'Diaspora';
586 $message_id = item_store($datarray);
589 q("update item set plink = '%s' where id = %d limit 1",
590 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
595 if(! $parent_author_signature) {
596 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
598 dbesc($author_signed_data),
599 dbesc(base64_encode($author_signature)),
600 dbesc($diaspora_handle)
603 // if the message isn't already being relayed, notify others
604 // the existence of parent_author_signature means the parent_author or owner
605 // is already relaying.
607 proc_run('php','include/notifier.php','comment',$message_id);
612 function diaspora_photo($importer,$xml,$msg) {
615 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
617 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
619 $status_message_guid = notags(unxmlify($xml->status_message_guid));
621 $guid = notags(unxmlify($xml->guid));
623 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
625 $public = notags(unxmlify($xml->public));
627 $created_at = notags(unxmlify($xml_created_at));
630 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
634 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
635 logger('diaspora_photo: Ignoring this author.');
636 http_status_exit(202);
640 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
641 intval($importer['uid']),
642 dbesc($status_message_guid)
645 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
648 $parent_item = $r[0];
650 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
652 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
653 dbesc($link_text . $parent_item['body']),
654 intval($parent_item['id']),
655 intval($parent_item['uid'])
664 function diaspora_like($importer,$xml,$msg) {
667 $guid = notags(unxmlify($xml->guid));
668 $parent_guid = notags(unxmlify($xml->parent_guid));
669 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
670 $target_type = notags(unxmlify($xml->target_type));
671 $positive = notags(unxmlify($xml->positive));
672 $author_signature = notags(unxmlify($xml->author_signature));
674 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
676 // likes on comments not supported here and likes on photos not supported by Diaspora
678 if($target_type !== 'Post')
681 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
683 logger('diaspora_like: cannot find contact: ' . $msg['author']);
687 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
688 logger('diaspora_like: Ignoring this author.');
689 http_status_exit(202);
693 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
694 intval($importer['uid']),
698 logger('diaspora_like: parent item not found: ' . $guid);
702 $parent_item = $r[0];
704 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
705 intval($importer['uid']),
709 if($positive === 'true') {
710 logger('diaspora_like: duplicate like: ' . $guid);
713 if($positive === 'false') {
714 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
716 intval($importer['uid'])
719 // send notification via proc_run()
723 if($positive === 'false') {
724 logger('diaspora_like: unlike received with no corresponding like');
728 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
730 $author_signature = base64_decode($author_signature);
732 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
737 $person = find_diaspora_person_by_handle($diaspora_handle);
738 if(is_array($person) && x($person,'pubkey'))
739 $key = $person['pubkey'];
741 logger('diaspora_like: unable to find author details');
746 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha')) {
747 logger('diaspora_like: verification failed.');
751 if($parent_author_signature) {
753 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
755 $parent_author_signature = base64_decode($parent_author_signature);
759 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha')) {
760 logger('diaspora_like: owner verification failed.');
765 // Phew! Everything checks out. Now create an item.
767 $uri = $diaspora_handle . ':' . $guid;
769 $activity = ACTIVITY_LIKE;
770 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
771 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
772 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
773 $body = $parent_item['body'];
778 <type>$objtype</type>
780 <id>{$parent_item['uri']}</id>
783 <content>$body</content>
786 $bodyverb = t('%1$s likes %2$s\'s %3$s');
791 $arr['uid'] = $importer['uid'];
792 $arr['guid'] = $guid;
793 $arr['contact-id'] = $contact['id'];
794 $arr['type'] = 'activity';
795 $arr['wall'] = $parent_item['wall'];
796 $arr['gravity'] = GRAVITY_LIKE;
797 $arr['parent'] = $parent_item['id'];
798 $arr['parent-uri'] = $parent_item['uri'];
800 $arr['owner-name'] = $contact['name'];
801 $arr['owner-link'] = $contact['url'];
802 $arr['owner-avatar'] = $contact['thumb'];
804 $arr['author-name'] = $person['name'];
805 $arr['author-link'] = $person['url'];
806 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
808 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
809 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
810 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
811 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
813 $arr['app'] = 'Diaspora';
815 $arr['private'] = $parent_item['private'];
816 $arr['verb'] = $activity;
817 $arr['object-type'] = $objtype;
818 $arr['object'] = $obj;
821 $arr['last-child'] = 0;
823 $message_id = item_store($arr);
827 q("update item set plink = '%s' where id = %d limit 1",
828 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
833 if(! $parent_author_signature) {
834 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
836 dbesc($author_signed_data),
837 dbesc(base64_encode($author_signature)),
838 dbesc($diaspora_handle)
842 // if the message isn't already being relayed, notify others
843 // the existence of parent_author_signature means the parent_author or owner
844 // is already relaying.
846 if(! $parent_author_signature)
847 proc_run('php','include/notifier.php','comment',$message_id);
852 function diaspora_retraction($importer,$xml) {
854 $guid = notags(unxmlify($xml->guid));
855 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
856 $type = notags(unxmlify($xml->type));
858 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
862 if($type === 'Person') {
863 contact_remove($contact['id']);
865 elseif($type === 'Post') {
866 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
868 intval($importer['uid'])
871 if(link_compare($r[0]['author-link'],$contact['url'])) {
872 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
873 dbesc(datetime_convert()),
880 http_exit_status(202);
884 function diaspora_share($me,$contact) {
886 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
887 $theiraddr = $contact['addr'];
889 $tpl = get_markup_template('diaspora_share.tpl');
890 $msg = replace_macros($tpl, array(
891 '$sender' => $myaddr,
892 '$recipient' => $theiraddr
895 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
897 return(diaspora_transmit($owner,$contact,$slap));
900 function diaspora_unshare($me,$contact) {
903 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
905 $tpl = get_markup_template('diaspora_retract.tpl');
906 $msg = replace_macros($tpl, array(
907 '$guid' => $me['guid'],
912 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
914 return(diaspora_transmit($owner,$contact,$slap));
920 function diaspora_send_status($item,$owner,$contact) {
923 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
924 $theiraddr = $contact['addr'];
928 $body = $item['body'];
930 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
932 foreach($matches as $mtch) {
934 $detail['str'] = $mtch[0];
935 $detail['path'] = dirname($mtch[1]) . '/';
936 $detail['file'] = basename($mtch[1]);
937 $detail['guid'] = $item['guid'];
938 $detail['handle'] = $myaddr;
940 $body = str_replace($detail['str'],t('link'),$body);
944 $body = xmlify(html_entity_decode(bb2diaspora($body)));
946 $public = (($item['private']) ? 'false' : 'true');
948 require_once('include/datetime.php');
949 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
951 $tpl = get_markup_template('diaspora_post.tpl');
952 $msg = replace_macros($tpl, array(
954 '$guid' => $item['guid'],
955 '$handle' => xmlify($myaddr),
956 '$public' => $public,
957 '$created' => $created
960 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
962 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
964 $return_code = diaspora_transmit($owner,$contact,$slap);
967 diaspora_send_images($item,$owner,$contact,$images);
974 function diaspora_send_images($item,$owner,$contact,$images) {
978 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
980 $tpl = get_markup_template('diaspora_photo.tpl');
981 foreach($images as $image) {
982 if(! stristr($image['path'],$mysite))
984 $resource = str_replace('.jpg','',$image['file']);
985 $resource = substr($resource,0,strpos($resource,'-'));
987 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
989 intval($owner['uid'])
993 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
994 $msg = replace_macros($tpl,array(
995 '$path' => xmlify($image['path']),
996 '$filename' => xmlify($image['file']),
997 '$msg_guid' => xmlify($image['guid']),
998 '$guid' => xmlify($r[0]['guid']),
999 '$handle' => xmlify($image['handle']),
1000 '$public' => xmlify($public),
1001 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1005 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1006 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1008 diaspora_transmit($owner,$contact,$slap);
1013 function diaspora_send_followup($item,$owner,$contact) {
1016 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1017 $theiraddr = $contact['addr'];
1019 $p = q("select guid from item where parent = %d limit 1",
1023 $parent_guid = $p[0]['guid'];
1027 if($item['verb'] === ACTIVITY_LIKE) {
1028 $tpl = get_markup_template('diaspora_like.tpl');
1030 $target_type = 'Post';
1031 $positive = (($item['deleted']) ? 'false' : 'true');
1034 $tpl = get_markup_template('diaspora_comment.tpl');
1038 $text = html_entity_decode(bb2diaspora($item['body']));
1043 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1045 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1047 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha'));
1049 $msg = replace_macros($tpl,array(
1050 '$guid' => xmlify($item['guid']),
1051 '$parent_guid' => xmlify($parent_guid),
1052 '$target_type' =>xmlify($target_type),
1053 '$authorsig' => xmlify($authorsig),
1054 '$body' => xmlify($text),
1055 '$positive' => xmlify($positive),
1056 '$handle' => xmlify($myaddr)
1059 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1061 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1063 return(diaspora_transmit($owner,$contact,$slap));
1067 function diaspora_send_relay($item,$owner,$contact) {
1071 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1072 $theiraddr = $contact['addr'];
1075 $p = q("select guid from item where parent = %d limit 1",
1079 $parent_guid = $p[0]['guid'];
1083 if($item['verb'] === ACTIVITY_LIKE) {
1084 $tpl = get_markup_template('diaspora_like_relay.tpl');
1086 $target_type = 'Post';
1087 $positive = (($item['deleted']) ? 'false' : 'true');
1090 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1094 $body = $item['body'];
1096 $text = html_entity_decode(bb2diaspora($body));
1098 // fetch the original signature if somebody sent the post to us to relay
1099 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1100 // action. It wasn't needed. In that case create the original signature and the
1101 // owner (parent author) signature
1102 // comments from other networks will be relayed under our name, with a brief
1103 // preamble to describe what's happening and noting the real author
1105 $r = q("select * from sign where iid = %d limit 1",
1110 $signed_text = $orig_sign['signed_text'];
1111 $authorsig = $orig_sign['signature'];
1112 $handle = $orig_sign['signer'];
1116 $itemcontact = q("select * from contact where `id` = %d limit 1",
1117 intval($item['contact-id'])
1119 if(count($itemcontact)) {
1120 if(! $itemcontact[0]['self']) {
1121 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1122 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1123 network_to_name($itemcontact['network'])) . "\n";
1124 $body = $prefix . $body;
1130 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1132 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1134 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha'));
1136 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1137 intval($item['id']),
1138 dbesc($signed_text),
1139 dbesc(base64_encode($authorsig)),
1148 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha'));
1150 $msg = replace_macros($tpl,array(
1151 '$guid' => xmlify($item['guid']),
1152 '$parent_guid' => xmlify($parent_guid),
1153 '$target_type' =>xmlify($target_type),
1154 '$authorsig' => xmlify($orig_sign['signature']),
1155 '$parentsig' => xmlify($parentauthorsig),
1156 '$body' => xmlify($text),
1157 '$positive' => xmlify($positive),
1158 '$handle' => xmlify($handle)
1161 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1163 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1165 return(diaspora_transmit($owner,$contact,$slap));
1171 function diaspora_send_retraction($item,$owner,$contact) {
1174 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1176 $tpl = get_markup_template('diaspora_retract.tpl');
1177 $msg = replace_macros($tpl, array(
1178 '$guid' => $item['guid'],
1180 '$handle' => $myaddr
1183 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1185 return(diaspora_transmit($owner,$contact,$slap));
1190 function diaspora_transmit($owner,$contact,$slap) {
1194 post_url($contact['notify'] . '/',$slap);
1195 $return_code = $a->get_curl_code();
1196 logger('diaspora_transmit: returns: ' . $return_code);
1198 if(! $return_code) {
1199 logger('diaspora_transmit: queue message');
1200 // queue message for redelivery
1201 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
1202 VALUES ( %d, '%s', '%s', '%s') ",
1203 intval($contact['id']),
1204 dbesc(datetime_convert()),
1205 dbesc(datetime_convert()),
1210 return(($return_code) ? $return_code : (-1));