3 require_once('include/crypto.php');
4 require_once('include/items.php');
5 require_once('include/bb2diaspora.php');
6 require_once('include/contact_selectors.php');
9 function diaspora_dispatch_public($msg) {
11 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN ( SELECT `uid` FROM `contact` WHERE `network` = '%s' AND `addr` = '%s' ) ",
12 dbesc(NETWORK_DIASPORA),
17 diaspora_dispatch($rr,$msg);
24 function diaspora_dispatch($importer,$msg) {
28 $parsed_xml = parse_xml_string($msg['message'],false);
30 $xmlbase = $parsed_xml->post;
32 if($xmlbase->request) {
33 $ret = diaspora_request($importer,$xmlbase->request);
35 elseif($xmlbase->status_message) {
36 $ret = diaspora_post($importer,$xmlbase->status_message);
38 elseif($xmlbase->comment) {
39 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
41 elseif($xmlbase->like) {
42 $ret = diaspora_like($importer,$xmlbase->like,$msg);
44 elseif($xmlbase->retraction) {
45 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
47 elseif($xmlbase->photo) {
48 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
51 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
56 function diaspora_get_contact_by_handle($uid,$handle) {
57 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
58 dbesc(NETWORK_DIASPORA),
67 function find_diaspora_person_by_handle($handle) {
68 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
69 dbesc(NETWORK_DIASPORA),
73 // update record occasionally so it doesn't get stale
74 $d = strtotime($r[0]['updated'] . ' +00:00');
75 if($d < strtotime('now - 14 days')) {
76 q("delete from fcontact where id = %d limit 1",
83 require_once('include/Scrape.php');
84 $r = probe_url($handle, PROBE_DIASPORA);
85 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
93 function get_diaspora_key($uri) {
94 logger('Fetching diaspora key for: ' . $uri);
96 $r = find_diaspora_person_by_handle($uri);
103 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
106 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
108 $inner_aes_key = random_string(32);
109 $b_inner_aes_key = base64_encode($inner_aes_key);
110 $inner_iv = random_string(16);
111 $b_inner_iv = base64_encode($inner_iv);
113 $outer_aes_key = random_string(32);
114 $b_outer_aes_key = base64_encode($outer_aes_key);
115 $outer_iv = random_string(16);
116 $b_outer_iv = base64_encode($outer_iv);
118 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
120 $padded_data = pkcs5_pad($msg,16);
121 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
123 $b64_data = base64_encode($inner_encrypted);
126 $b64url_data = base64url_encode($b64_data);
127 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
129 $type = 'application/xml';
130 $encoding = 'base64url';
133 $signable_data = $data . '.' . base64url_encode($type) . '.'
134 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
136 $signature = rsa_sign($signable_data,$prvkey);
137 $sig = base64url_encode($signature);
139 $decrypted_header = <<< EOT
142 <aes_key>$b_inner_aes_key</aes_key>
143 <author_id>$handle</author_id>
147 $decrypted_header = pkcs5_pad($decrypted_header,16);
149 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
151 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
153 $encrypted_outer_key_bundle = '';
154 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
156 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
158 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
160 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
161 'ciphertext' => base64_encode($ciphertext)));
162 $cipher_json = base64_encode($encrypted_header_json_object);
164 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
167 <?xml version='1.0' encoding='UTF-8'?>
168 <entry xmlns='http://www.w3.org/2005/Atom'>
170 <me:env xmlns:me="http://salmon-protocol.org/ns/magic-env">
171 <me:encoding>base64url</me:encoding>
172 <me:alg>RSA-SHA256</me:alg>
173 <me:data type="application/xml">$data</me:data>
174 <me:sig>$sig</me:sig>
179 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
186 * diaspora_decode($importer,$xml)
187 * array $importer -> from user table
188 * string $xml -> urldecoded Diaspora salmon
191 * 'message' -> decoded Diaspora XML message
192 * 'author' -> author diaspora handle
193 * 'key' -> author public key (converted to pkcs#8)
195 * Author and key are used elsewhere to save a lookup for verifying replies and likes
199 function diaspora_decode($importer,$xml) {
202 $basedom = parse_xml_string($xml);
204 $children = $basedom->children('https://joindiaspora.com/protocol');
206 if($children->header) {
208 $author_link = str_replace('acct:','',$children->author_id);
212 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
214 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
215 $ciphertext = base64_decode($encrypted_header->ciphertext);
217 $outer_key_bundle = '';
218 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
220 $j_outer_key_bundle = json_decode($outer_key_bundle);
222 $outer_iv = base64_decode($j_outer_key_bundle->iv);
223 $outer_key = base64_decode($j_outer_key_bundle->key);
225 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
228 $decrypted = pkcs5_unpad($decrypted);
231 * $decrypted now contains something like
234 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
235 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
240 * <name>Ryan Hughes</name>
241 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
246 * <author_id>acct:galaxor@diaspora.priateship.org</author_id>
250 * </decrypted_header>
253 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
254 $idom = parse_xml_string($decrypted,false);
256 $inner_iv = base64_decode($idom->iv);
257 $inner_aes_key = base64_decode($idom->aes_key);
259 $author_link = str_replace('acct:','',$idom->author_id);
263 $dom = $basedom->children(NAMESPACE_SALMON_ME);
265 // figure out where in the DOM tree our data is hiding
267 if($dom->provenance->data)
268 $base = $dom->provenance;
269 elseif($dom->env->data)
275 logger('mod-diaspora: unable to locate salmon data in xml ');
276 http_status_exit(400);
280 // Stash the signature away for now. We have to find their key or it won't be good for anything.
281 $signature = base64url_decode($base->sig);
285 // strip whitespace so our data element will return to one big base64 blob
286 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
289 // stash away some other stuff for later
291 $type = $base->data[0]->attributes()->type[0];
292 $keyhash = $base->sig[0]->attributes()->keyhash[0];
293 $encoding = $base->encoding;
297 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
301 $data = base64url_decode($data);
305 $inner_decrypted = $data;
309 // Decode the encrypted blob
311 $inner_encrypted = base64_decode($data);
312 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
313 $inner_decrypted = pkcs5_unpad($inner_decrypted);
317 logger('mod-diaspora: Could not retrieve author URI.');
318 http_status_exit(400);
321 // Once we have the author URI, go to the web and try to find their public key
322 // (first this will look it up locally if it is in the fcontact cache)
323 // This will also convert diaspora public key from pkcs#1 to pkcs#8
325 logger('mod-diaspora: Fetching key for ' . $author_link );
326 $key = get_diaspora_key($author_link);
329 logger('mod-diaspora: Could not retrieve author key.');
330 http_status_exit(400);
333 $verify = rsa_verify($signed_data,$signature,$key);
336 logger('mod-diaspora: Message did not verify. Discarding.');
337 // http_status_exit(400);
340 logger('mod-diaspora: Message verified.');
342 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
347 function diaspora_request($importer,$xml) {
349 $sender_handle = unxmlify($xml->sender_handle);
350 $recipient_handle = unxmlify($xml->recipient_handle);
352 if(! $sender_handle || ! $recipient_handle)
355 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
359 // perhaps we were already sharing with this person. Now they're sharing with us.
360 // That makes us friends.
362 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
363 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
364 intval(CONTACT_IS_FRIEND),
365 intval($contact['id']),
366 intval($importer['uid'])
369 // send notification?
373 $ret = find_diaspora_person_by_handle($sender_handle);
376 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
377 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
381 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
382 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
383 intval($importer['uid']),
384 dbesc($ret['network']),
390 dbesc($ret['photo']),
391 dbesc($ret['pubkey']),
392 dbesc($ret['notify']),
398 // find the contact record we just created
400 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
402 $hash = random_string() . (string) time(); // Generate a confirm_key
404 if($contact_record) {
405 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
406 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
407 intval($importer['uid']),
408 intval($contact_record['id']),
411 dbesc( t('Sharing notification from Diaspora network')),
413 dbesc(datetime_convert())
420 function diaspora_post($importer,$xml) {
423 $guid = notags(unxmlify($xml->guid));
424 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
426 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
430 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
431 logger('diaspora_post: Ignoring this author.');
435 $message_id = $diaspora_handle . ':' . $guid;
436 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
437 intval($importer['uid']),
442 logger('diaspora_post: message exists: ' . $guid);
446 // allocate a guid on our system - we aren't fixing any collisions.
447 // we're ignoring them
449 $g = q("select * from guid where guid = '%s' limit 1",
453 q("insert into guid ( guid ) values ( '%s' )",
458 $created = unxmlify($xml->created_at);
459 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
461 $body = diaspora2bb($xml->raw_message);
464 $datarray['uid'] = $importer['uid'];
465 $datarray['contact-id'] = $contact['id'];
466 $datarray['wall'] = 0;
467 $datarray['guid'] = $guid;
468 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
469 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
470 $datarray['private'] = $private;
471 $datarray['parent'] = 0;
472 $datarray['owner-name'] = $contact['name'];
473 $datarray['owner-link'] = $contact['url'];
474 $datarray['owner-avatar'] = $contact['thumb'];
475 $datarray['author-name'] = $contact['name'];
476 $datarray['author-link'] = $contact['url'];
477 $datarray['author-avatar'] = $contact['thumb'];
478 $datarray['body'] = $body;
479 $datarray['app'] = 'Diaspora';
481 $message_id = item_store($datarray);
484 q("update item set plink = '%s' where id = %d limit 1",
485 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
494 function diaspora_comment($importer,$xml,$msg) {
497 $guid = notags(unxmlify($xml->guid));
498 $parent_guid = notags(unxmlify($xml->parent_guid));
499 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
500 $target_type = notags(unxmlify($xml->target_type));
501 $text = unxmlify($xml->text);
502 $author_signature = notags(unxmlify($xml->author_signature));
504 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
508 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
510 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
514 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
515 logger('diaspora_comment: Ignoring this author.');
519 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
520 intval($importer['uid']),
524 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
528 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
529 intval($importer['uid']),
533 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
536 $parent_item = $r[0];
538 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
540 $author_signature = base64_decode($author_signature);
542 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
547 $person = find_diaspora_person_by_handle($diaspora_handle);
549 if(is_array($person) && x($person,'pubkey'))
550 $key = $person['pubkey'];
552 logger('diaspora_comment: unable to find author details');
557 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
558 logger('diaspora_comment: verification failed.');
563 if($parent_author_signature) {
564 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
566 $parent_author_signature = base64_decode($parent_author_signature);
570 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
571 logger('diaspora_comment: owner verification failed.');
576 // Phew! Everything checks out. Now create an item.
578 $body = diaspora2bb($text);
580 $message_id = $diaspora_handle . ':' . $guid;
583 $datarray['uid'] = $importer['uid'];
584 $datarray['contact-id'] = $contact['id'];
585 $datarray['wall'] = $parent_item['wall'];
586 $datarray['gravity'] = GRAVITY_COMMENT;
587 $datarray['guid'] = $guid;
588 $datarray['uri'] = $message_id;
589 $datarray['parent-uri'] = $parent_item['uri'];
591 // No timestamps for comments? OK, we'll the use current time.
592 $datarray['created'] = $datarray['edited'] = datetime_convert();
593 $datarray['private'] = $parent_item['private'];
595 $datarray['owner-name'] = $contact['name'];
596 $datarray['owner-link'] = $contact['url'];
597 $datarray['owner-avatar'] = $contact['thumb'];
599 $datarray['author-name'] = $person['name'];
600 $datarray['author-link'] = $person['url'];
601 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
602 $datarray['body'] = $body;
603 $datarray['app'] = 'Diaspora';
605 $message_id = item_store($datarray);
608 q("update item set plink = '%s' where id = %d limit 1",
609 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
614 if(! $parent_author_signature) {
615 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
617 dbesc($author_signed_data),
618 dbesc(base64_encode($author_signature)),
619 dbesc($diaspora_handle)
622 // if the message isn't already being relayed, notify others
623 // the existence of parent_author_signature means the parent_author or owner
624 // is already relaying.
626 proc_run('php','include/notifier.php','comment',$message_id);
631 function diaspora_photo($importer,$xml,$msg) {
634 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
636 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
638 $status_message_guid = notags(unxmlify($xml->status_message_guid));
640 $guid = notags(unxmlify($xml->guid));
642 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
644 $public = notags(unxmlify($xml->public));
646 $created_at = notags(unxmlify($xml_created_at));
649 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
653 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
654 logger('diaspora_photo: Ignoring this author.');
658 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
659 intval($importer['uid']),
660 dbesc($status_message_guid)
663 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
666 $parent_item = $r[0];
668 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
670 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
671 dbesc($link_text . $parent_item['body']),
672 intval($parent_item['id']),
673 intval($parent_item['uid'])
682 function diaspora_like($importer,$xml,$msg) {
685 $guid = notags(unxmlify($xml->guid));
686 $parent_guid = notags(unxmlify($xml->parent_guid));
687 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
688 $target_type = notags(unxmlify($xml->target_type));
689 $positive = notags(unxmlify($xml->positive));
690 $author_signature = notags(unxmlify($xml->author_signature));
692 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
694 // likes on comments not supported here and likes on photos not supported by Diaspora
696 if($target_type !== 'Post')
699 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
701 logger('diaspora_like: cannot find contact: ' . $msg['author']);
705 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
706 logger('diaspora_like: Ignoring this author.');
710 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
711 intval($importer['uid']),
715 logger('diaspora_like: parent item not found: ' . $guid);
719 $parent_item = $r[0];
721 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
722 intval($importer['uid']),
726 if($positive === 'true') {
727 logger('diaspora_like: duplicate like: ' . $guid);
730 if($positive === 'false') {
731 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
733 intval($importer['uid'])
736 // send notification via proc_run()
740 if($positive === 'false') {
741 logger('diaspora_like: unlike received with no corresponding like');
745 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
747 $author_signature = base64_decode($author_signature);
749 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
754 $person = find_diaspora_person_by_handle($diaspora_handle);
755 if(is_array($person) && x($person,'pubkey'))
756 $key = $person['pubkey'];
758 logger('diaspora_like: unable to find author details');
763 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
764 logger('diaspora_like: verification failed.');
768 if($parent_author_signature) {
770 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
772 $parent_author_signature = base64_decode($parent_author_signature);
776 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
777 logger('diaspora_like: owner verification failed.');
782 // Phew! Everything checks out. Now create an item.
784 $uri = $diaspora_handle . ':' . $guid;
786 $activity = ACTIVITY_LIKE;
787 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
788 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
789 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
790 $body = $parent_item['body'];
795 <type>$objtype</type>
797 <id>{$parent_item['uri']}</id>
800 <content>$body</content>
803 $bodyverb = t('%1$s likes %2$s\'s %3$s');
808 $arr['uid'] = $importer['uid'];
809 $arr['guid'] = $guid;
810 $arr['contact-id'] = $contact['id'];
811 $arr['type'] = 'activity';
812 $arr['wall'] = $parent_item['wall'];
813 $arr['gravity'] = GRAVITY_LIKE;
814 $arr['parent'] = $parent_item['id'];
815 $arr['parent-uri'] = $parent_item['uri'];
817 $arr['owner-name'] = $contact['name'];
818 $arr['owner-link'] = $contact['url'];
819 $arr['owner-avatar'] = $contact['thumb'];
821 $arr['author-name'] = $person['name'];
822 $arr['author-link'] = $person['url'];
823 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
825 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
826 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
827 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
828 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
830 $arr['app'] = 'Diaspora';
832 $arr['private'] = $parent_item['private'];
833 $arr['verb'] = $activity;
834 $arr['object-type'] = $objtype;
835 $arr['object'] = $obj;
838 $arr['last-child'] = 0;
840 $message_id = item_store($arr);
844 q("update item set plink = '%s' where id = %d limit 1",
845 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
850 if(! $parent_author_signature) {
851 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
853 dbesc($author_signed_data),
854 dbesc(base64_encode($author_signature)),
855 dbesc($diaspora_handle)
859 // if the message isn't already being relayed, notify others
860 // the existence of parent_author_signature means the parent_author or owner
861 // is already relaying.
863 if(! $parent_author_signature)
864 proc_run('php','include/notifier.php','comment',$message_id);
869 function diaspora_retraction($importer,$xml) {
871 $guid = notags(unxmlify($xml->guid));
872 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
873 $type = notags(unxmlify($xml->type));
875 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
879 if($type === 'Person') {
880 contact_remove($contact['id']);
882 elseif($type === 'Post') {
883 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
885 intval($importer['uid'])
888 if(link_compare($r[0]['author-link'],$contact['url'])) {
889 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
890 dbesc(datetime_convert()),
901 function diaspora_share($me,$contact) {
903 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
904 $theiraddr = $contact['addr'];
906 $tpl = get_markup_template('diaspora_share.tpl');
907 $msg = replace_macros($tpl, array(
908 '$sender' => $myaddr,
909 '$recipient' => $theiraddr
912 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
914 return(diaspora_transmit($owner,$contact,$slap));
917 function diaspora_unshare($me,$contact) {
920 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
922 $tpl = get_markup_template('diaspora_retract.tpl');
923 $msg = replace_macros($tpl, array(
924 '$guid' => $me['guid'],
929 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
931 return(diaspora_transmit($owner,$contact,$slap));
937 function diaspora_send_status($item,$owner,$contact) {
940 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
941 $theiraddr = $contact['addr'];
945 $body = $item['body'];
947 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
949 foreach($matches as $mtch) {
951 $detail['str'] = $mtch[0];
952 $detail['path'] = dirname($mtch[1]) . '/';
953 $detail['file'] = basename($mtch[1]);
954 $detail['guid'] = $item['guid'];
955 $detail['handle'] = $myaddr;
957 $body = str_replace($detail['str'],t('link'),$body);
961 $body = xmlify(html_entity_decode(bb2diaspora($body)));
963 $public = (($item['private']) ? 'false' : 'true');
965 require_once('include/datetime.php');
966 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
968 $tpl = get_markup_template('diaspora_post.tpl');
969 $msg = replace_macros($tpl, array(
971 '$guid' => $item['guid'],
972 '$handle' => xmlify($myaddr),
973 '$public' => $public,
974 '$created' => $created
977 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
979 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
981 $return_code = diaspora_transmit($owner,$contact,$slap);
984 diaspora_send_images($item,$owner,$contact,$images);
991 function diaspora_send_images($item,$owner,$contact,$images) {
995 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
997 $tpl = get_markup_template('diaspora_photo.tpl');
998 foreach($images as $image) {
999 if(! stristr($image['path'],$mysite))
1001 $resource = str_replace('.jpg','',$image['file']);
1002 $resource = substr($resource,0,strpos($resource,'-'));
1004 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1006 intval($owner['uid'])
1010 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1011 $msg = replace_macros($tpl,array(
1012 '$path' => xmlify($image['path']),
1013 '$filename' => xmlify($image['file']),
1014 '$msg_guid' => xmlify($image['guid']),
1015 '$guid' => xmlify($r[0]['guid']),
1016 '$handle' => xmlify($image['handle']),
1017 '$public' => xmlify($public),
1018 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1022 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1023 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1025 diaspora_transmit($owner,$contact,$slap);
1030 function diaspora_send_followup($item,$owner,$contact) {
1033 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1034 $theiraddr = $contact['addr'];
1036 $p = q("select guid from item where parent = %d limit 1",
1040 $parent_guid = $p[0]['guid'];
1044 if($item['verb'] === ACTIVITY_LIKE) {
1045 $tpl = get_markup_template('diaspora_like.tpl');
1047 $target_type = 'Post';
1048 $positive = (($item['deleted']) ? 'false' : 'true');
1051 $tpl = get_markup_template('diaspora_comment.tpl');
1055 $text = html_entity_decode(bb2diaspora($item['body']));
1060 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1062 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1064 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1066 $msg = replace_macros($tpl,array(
1067 '$guid' => xmlify($item['guid']),
1068 '$parent_guid' => xmlify($parent_guid),
1069 '$target_type' =>xmlify($target_type),
1070 '$authorsig' => xmlify($authorsig),
1071 '$body' => xmlify($text),
1072 '$positive' => xmlify($positive),
1073 '$handle' => xmlify($myaddr)
1076 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1078 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1080 return(diaspora_transmit($owner,$contact,$slap));
1084 function diaspora_send_relay($item,$owner,$contact) {
1088 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1089 $theiraddr = $contact['addr'];
1092 $p = q("select guid from item where parent = %d limit 1",
1096 $parent_guid = $p[0]['guid'];
1100 if($item['verb'] === ACTIVITY_LIKE) {
1101 $tpl = get_markup_template('diaspora_like_relay.tpl');
1103 $target_type = 'Post';
1104 $positive = (($item['deleted']) ? 'false' : 'true');
1107 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1111 $body = $item['body'];
1113 $text = html_entity_decode(bb2diaspora($body));
1115 // fetch the original signature if somebody sent the post to us to relay
1116 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1117 // action. It wasn't needed. In that case create the original signature and the
1118 // owner (parent author) signature
1119 // comments from other networks will be relayed under our name, with a brief
1120 // preamble to describe what's happening and noting the real author
1122 $r = q("select * from sign where iid = %d limit 1",
1127 $signed_text = $orig_sign['signed_text'];
1128 $authorsig = $orig_sign['signature'];
1129 $handle = $orig_sign['signer'];
1133 $itemcontact = q("select * from contact where `id` = %d limit 1",
1134 intval($item['contact-id'])
1136 if(count($itemcontact)) {
1137 if(! $itemcontact[0]['self']) {
1138 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1139 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1140 network_to_name($itemcontact['network'])) . "\n";
1141 $body = $prefix . $body;
1147 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1149 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1151 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1153 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1154 intval($item['id']),
1155 dbesc($signed_text),
1156 dbesc(base64_encode($authorsig)),
1165 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1167 $msg = replace_macros($tpl,array(
1168 '$guid' => xmlify($item['guid']),
1169 '$parent_guid' => xmlify($parent_guid),
1170 '$target_type' =>xmlify($target_type),
1171 '$authorsig' => xmlify($orig_sign['signature']),
1172 '$parentsig' => xmlify($parentauthorsig),
1173 '$body' => xmlify($text),
1174 '$positive' => xmlify($positive),
1175 '$handle' => xmlify($handle)
1178 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1180 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1182 return(diaspora_transmit($owner,$contact,$slap));
1188 function diaspora_send_retraction($item,$owner,$contact) {
1191 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1193 $tpl = get_markup_template('diaspora_retract.tpl');
1194 $msg = replace_macros($tpl, array(
1195 '$guid' => $item['guid'],
1197 '$handle' => $myaddr
1200 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1202 return(diaspora_transmit($owner,$contact,$slap));
1207 function diaspora_transmit($owner,$contact,$slap) {
1211 post_url($contact['notify'] . '/',$slap);
1212 $return_code = $a->get_curl_code();
1213 logger('diaspora_transmit: returns: ' . $return_code);
1215 if(! $return_code) {
1216 logger('diaspora_transmit: queue message');
1217 // queue message for redelivery
1218 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
1219 VALUES ( %d, '%s', '%s', '%s') ",
1220 intval($contact['id']),
1221 dbesc(datetime_convert()),
1222 dbesc(datetime_convert()),
1227 return(($return_code) ? $return_code : (-1));