3 require_once('include/crypto.php');
4 require_once('include/items.php');
5 require_once('include/bb2diaspora.php');
6 require_once('include/contact_selectors.php');
9 function diaspora_dispatch_public($msg) {
11 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' ) AND `account_expired` = 0 ",
12 dbesc(NETWORK_DIASPORA),
17 logger('diaspora_public: delivering to: ' . $rr['username']);
18 diaspora_dispatch($rr,$msg);
22 logger('diaspora_public: no subscribers');
27 function diaspora_dispatch($importer,$msg) {
31 $parsed_xml = parse_xml_string($msg['message'],false);
33 $xmlbase = $parsed_xml->post;
35 if($xmlbase->request) {
36 $ret = diaspora_request($importer,$xmlbase->request);
38 elseif($xmlbase->status_message) {
39 $ret = diaspora_post($importer,$xmlbase->status_message);
41 elseif($xmlbase->profile) {
42 $ret = diaspora_profile($importer,$xmlbase->profile);
44 elseif($xmlbase->comment) {
45 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
47 elseif($xmlbase->like) {
48 $ret = diaspora_like($importer,$xmlbase->like,$msg);
50 elseif($xmlbase->retraction) {
51 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
53 elseif($xmlbase->photo) {
54 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
57 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
62 function diaspora_get_contact_by_handle($uid,$handle) {
63 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
64 dbesc(NETWORK_DIASPORA),
73 function find_diaspora_person_by_handle($handle) {
75 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
76 dbesc(NETWORK_DIASPORA),
80 // update record occasionally so it doesn't get stale
81 $d = strtotime($r[0]['updated'] . ' +00:00');
82 if($d > strtotime('now - 14 days'))
86 require_once('include/Scrape.php');
87 $r = probe_url($handle, PROBE_DIASPORA);
88 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
89 add_fcontact($r,$update);
96 function get_diaspora_key($uri) {
97 logger('Fetching diaspora key for: ' . $uri);
99 $r = find_diaspora_person_by_handle($uri);
106 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
109 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
112 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
114 // $b64_data = base64_encode($msg);
115 // $b64url_data = base64url_encode($b64_data);
117 $b64url_data = base64url_encode($msg);
119 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
121 $type = 'application/xml';
122 $encoding = 'base64url';
125 $signable_data = $data . '.' . base64url_encode($type) . '.'
126 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
128 $signature = rsa_sign($signable_data,$prvkey);
129 $sig = base64url_encode($signature);
132 <?xml version='1.0' encoding='UTF-8'?>
133 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
135 <author_id>$handle</author_id>
138 <me:encoding>base64url</me:encoding>
139 <me:alg>RSA-SHA256</me:alg>
140 <me:data type="application/xml">$data</me:data>
141 <me:sig>$sig</me:sig>
146 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
154 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
158 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
160 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
162 $inner_aes_key = random_string(32);
163 $b_inner_aes_key = base64_encode($inner_aes_key);
164 $inner_iv = random_string(16);
165 $b_inner_iv = base64_encode($inner_iv);
167 $outer_aes_key = random_string(32);
168 $b_outer_aes_key = base64_encode($outer_aes_key);
169 $outer_iv = random_string(16);
170 $b_outer_iv = base64_encode($outer_iv);
172 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
174 $padded_data = pkcs5_pad($msg,16);
175 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
177 $b64_data = base64_encode($inner_encrypted);
180 $b64url_data = base64url_encode($b64_data);
181 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
183 $type = 'application/xml';
184 $encoding = 'base64url';
187 $signable_data = $data . '.' . base64url_encode($type) . '.'
188 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
190 $signature = rsa_sign($signable_data,$prvkey);
191 $sig = base64url_encode($signature);
193 $decrypted_header = <<< EOT
196 <aes_key>$b_inner_aes_key</aes_key>
197 <author_id>$handle</author_id>
201 $decrypted_header = pkcs5_pad($decrypted_header,16);
203 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
205 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
207 $encrypted_outer_key_bundle = '';
208 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
210 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
212 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
214 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
215 'ciphertext' => base64_encode($ciphertext)));
216 $cipher_json = base64_encode($encrypted_header_json_object);
218 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
221 <?xml version='1.0' encoding='UTF-8'?>
222 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
225 <me:encoding>base64url</me:encoding>
226 <me:alg>RSA-SHA256</me:alg>
227 <me:data type="application/xml">$data</me:data>
228 <me:sig>$sig</me:sig>
233 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
240 * diaspora_decode($importer,$xml)
241 * array $importer -> from user table
242 * string $xml -> urldecoded Diaspora salmon
245 * 'message' -> decoded Diaspora XML message
246 * 'author' -> author diaspora handle
247 * 'key' -> author public key (converted to pkcs#8)
249 * Author and key are used elsewhere to save a lookup for verifying replies and likes
253 function diaspora_decode($importer,$xml) {
256 $basedom = parse_xml_string($xml);
258 $children = $basedom->children('https://joindiaspora.com/protocol');
260 if($children->header) {
262 $author_link = str_replace('acct:','',$children->header->author_id);
266 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
268 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
269 $ciphertext = base64_decode($encrypted_header->ciphertext);
271 $outer_key_bundle = '';
272 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
274 $j_outer_key_bundle = json_decode($outer_key_bundle);
276 $outer_iv = base64_decode($j_outer_key_bundle->iv);
277 $outer_key = base64_decode($j_outer_key_bundle->key);
279 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
282 $decrypted = pkcs5_unpad($decrypted);
285 * $decrypted now contains something like
288 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
289 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
294 * <name>Ryan Hughes</name>
295 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
300 * <author_id>galaxor@diaspora.priateship.org</author_id>
304 * </decrypted_header>
307 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
308 $idom = parse_xml_string($decrypted,false);
310 $inner_iv = base64_decode($idom->iv);
311 $inner_aes_key = base64_decode($idom->aes_key);
313 $author_link = str_replace('acct:','',$idom->author_id);
317 $dom = $basedom->children(NAMESPACE_SALMON_ME);
319 // figure out where in the DOM tree our data is hiding
321 if($dom->provenance->data)
322 $base = $dom->provenance;
323 elseif($dom->env->data)
329 logger('mod-diaspora: unable to locate salmon data in xml ');
330 http_status_exit(400);
334 // Stash the signature away for now. We have to find their key or it won't be good for anything.
335 $signature = base64url_decode($base->sig);
339 // strip whitespace so our data element will return to one big base64 blob
340 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
343 // stash away some other stuff for later
345 $type = $base->data[0]->attributes()->type[0];
346 $keyhash = $base->sig[0]->attributes()->keyhash[0];
347 $encoding = $base->encoding;
351 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
355 $data = base64url_decode($data);
359 $inner_decrypted = $data;
363 // Decode the encrypted blob
365 $inner_encrypted = base64_decode($data);
366 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
367 $inner_decrypted = pkcs5_unpad($inner_decrypted);
371 logger('mod-diaspora: Could not retrieve author URI.');
372 http_status_exit(400);
375 // Once we have the author URI, go to the web and try to find their public key
376 // (first this will look it up locally if it is in the fcontact cache)
377 // This will also convert diaspora public key from pkcs#1 to pkcs#8
379 logger('mod-diaspora: Fetching key for ' . $author_link );
380 $key = get_diaspora_key($author_link);
383 logger('mod-diaspora: Could not retrieve author key.');
384 http_status_exit(400);
387 $verify = rsa_verify($signed_data,$signature,$key);
390 logger('mod-diaspora: Message did not verify. Discarding.');
391 http_status_exit(400);
394 logger('mod-diaspora: Message verified.');
396 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
401 function diaspora_request($importer,$xml) {
403 $sender_handle = unxmlify($xml->sender_handle);
404 $recipient_handle = unxmlify($xml->recipient_handle);
406 if(! $sender_handle || ! $recipient_handle)
409 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
413 // perhaps we were already sharing with this person. Now they're sharing with us.
414 // That makes us friends.
416 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
417 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
418 intval(CONTACT_IS_FRIEND),
419 intval($contact['id']),
420 intval($importer['uid'])
423 // send notification?
427 $ret = find_diaspora_person_by_handle($sender_handle);
430 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
431 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
435 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
437 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
438 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
439 intval($importer['uid']),
440 dbesc($ret['network']),
447 dbesc($ret['photo']),
448 dbesc($ret['pubkey']),
449 dbesc($ret['notify']),
455 // find the contact record we just created
457 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
459 $hash = random_string() . (string) time(); // Generate a confirm_key
461 if($contact_record) {
462 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
463 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
464 intval($importer['uid']),
465 intval($contact_record['id']),
468 dbesc( t('Sharing notification from Diaspora network')),
470 dbesc(datetime_convert())
477 function diaspora_post($importer,$xml) {
480 $guid = notags(unxmlify($xml->guid));
481 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
483 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
487 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
488 logger('diaspora_post: Ignoring this author.');
492 $message_id = $diaspora_handle . ':' . $guid;
493 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
494 intval($importer['uid']),
499 logger('diaspora_post: message exists: ' . $guid);
503 // allocate a guid on our system - we aren't fixing any collisions.
504 // we're ignoring them
506 $g = q("select * from guid where guid = '%s' limit 1",
510 q("insert into guid ( guid ) values ( '%s' )",
515 $created = unxmlify($xml->created_at);
516 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
518 $body = diaspora2bb($xml->raw_message);
524 $tags = get_tags($body);
527 foreach($tags as $tag) {
528 if(strpos($tag,'#') === 0) {
529 if(strpos($tag,'[url='))
531 $basetag = str_replace('_',' ',substr($tag,1));
532 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
533 if(strlen($str_tags))
535 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
541 $datarray['uid'] = $importer['uid'];
542 $datarray['contact-id'] = $contact['id'];
543 $datarray['wall'] = 0;
544 $datarray['guid'] = $guid;
545 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
546 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
547 $datarray['private'] = $private;
548 $datarray['parent'] = 0;
549 $datarray['owner-name'] = $contact['name'];
550 $datarray['owner-link'] = $contact['url'];
551 $datarray['owner-avatar'] = $contact['thumb'];
552 $datarray['author-name'] = $contact['name'];
553 $datarray['author-link'] = $contact['url'];
554 $datarray['author-avatar'] = $contact['thumb'];
555 $datarray['body'] = $body;
556 $datarray['tag'] = $str_tags;
557 $datarray['app'] = 'Diaspora';
559 $message_id = item_store($datarray);
562 q("update item set plink = '%s' where id = %d limit 1",
563 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
572 function diaspora_comment($importer,$xml,$msg) {
575 $guid = notags(unxmlify($xml->guid));
576 $parent_guid = notags(unxmlify($xml->parent_guid));
577 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
578 $target_type = notags(unxmlify($xml->target_type));
579 $text = unxmlify($xml->text);
580 $author_signature = notags(unxmlify($xml->author_signature));
582 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
586 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
588 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
592 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
593 logger('diaspora_comment: Ignoring this author.');
597 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
598 intval($importer['uid']),
602 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
606 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
607 intval($importer['uid']),
611 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
614 $parent_item = $r[0];
616 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
618 $author_signature = base64_decode($author_signature);
620 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
625 $person = find_diaspora_person_by_handle($diaspora_handle);
627 if(is_array($person) && x($person,'pubkey'))
628 $key = $person['pubkey'];
630 logger('diaspora_comment: unable to find author details');
635 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
636 logger('diaspora_comment: verification failed.');
640 if($parent_author_signature) {
641 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
643 $parent_author_signature = base64_decode($parent_author_signature);
647 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
648 logger('diaspora_comment: owner verification failed.');
653 // Phew! Everything checks out. Now create an item.
655 $body = diaspora2bb($text);
657 $message_id = $diaspora_handle . ':' . $guid;
663 $tags = get_tags($body);
666 foreach($tags as $tag) {
667 if(strpos($tag,'#') === 0) {
668 if(strpos($tag,'[url='))
670 $basetag = str_replace('_',' ',substr($tag,1));
671 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
672 if(strlen($str_tags))
674 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
680 $datarray['uid'] = $importer['uid'];
681 $datarray['contact-id'] = $contact['id'];
682 $datarray['wall'] = $parent_item['wall'];
683 $datarray['gravity'] = GRAVITY_COMMENT;
684 $datarray['guid'] = $guid;
685 $datarray['uri'] = $message_id;
686 $datarray['parent-uri'] = $parent_item['uri'];
688 // No timestamps for comments? OK, we'll the use current time.
689 $datarray['created'] = $datarray['edited'] = datetime_convert();
690 $datarray['private'] = $parent_item['private'];
692 $datarray['owner-name'] = $parent_item['owner-name'];
693 $datarray['owner-link'] = $parent_item['owner-link'];
694 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
696 $datarray['author-name'] = $person['name'];
697 $datarray['author-link'] = $person['url'];
698 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
699 $datarray['body'] = $body;
700 $datarray['tag'] = $str_tags;
701 $datarray['app'] = 'Diaspora';
703 $message_id = item_store($datarray);
706 q("update item set plink = '%s' where id = %d limit 1",
707 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
712 if(! $parent_author_signature) {
713 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
715 dbesc($author_signed_data),
716 dbesc(base64_encode($author_signature)),
717 dbesc($diaspora_handle)
720 // if the message isn't already being relayed, notify others
721 // the existence of parent_author_signature means the parent_author or owner
722 // is already relaying.
724 proc_run('php','include/notifier.php','comment',$message_id);
729 function diaspora_photo($importer,$xml,$msg) {
732 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
734 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
736 $status_message_guid = notags(unxmlify($xml->status_message_guid));
738 $guid = notags(unxmlify($xml->guid));
740 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
742 $public = notags(unxmlify($xml->public));
744 $created_at = notags(unxmlify($xml_created_at));
747 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
751 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
752 logger('diaspora_photo: Ignoring this author.');
756 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
757 intval($importer['uid']),
758 dbesc($status_message_guid)
761 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
764 $parent_item = $r[0];
766 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
768 if(strpos($parent_item['body'],$link_text) === false) {
769 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
770 dbesc($link_text . $parent_item['body']),
771 intval($parent_item['id']),
772 intval($parent_item['uid'])
782 function diaspora_like($importer,$xml,$msg) {
785 $guid = notags(unxmlify($xml->guid));
786 $parent_guid = notags(unxmlify($xml->parent_guid));
787 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
788 $target_type = notags(unxmlify($xml->target_type));
789 $positive = notags(unxmlify($xml->positive));
790 $author_signature = notags(unxmlify($xml->author_signature));
792 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
794 // likes on comments not supported here and likes on photos not supported by Diaspora
796 if($target_type !== 'Post')
799 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
801 logger('diaspora_like: cannot find contact: ' . $msg['author']);
805 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
806 logger('diaspora_like: Ignoring this author.');
810 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
811 intval($importer['uid']),
815 logger('diaspora_like: parent item not found: ' . $guid);
819 $parent_item = $r[0];
821 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
822 intval($importer['uid']),
826 if($positive === 'true') {
827 logger('diaspora_like: duplicate like: ' . $guid);
830 if($positive === 'false') {
831 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
833 intval($importer['uid'])
836 // send notification via proc_run()
840 if($positive === 'false') {
841 logger('diaspora_like: unlike received with no corresponding like');
845 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
847 $author_signature = base64_decode($author_signature);
849 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
854 $person = find_diaspora_person_by_handle($diaspora_handle);
855 if(is_array($person) && x($person,'pubkey'))
856 $key = $person['pubkey'];
858 logger('diaspora_like: unable to find author details');
863 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
864 logger('diaspora_like: verification failed.');
868 if($parent_author_signature) {
870 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
872 $parent_author_signature = base64_decode($parent_author_signature);
876 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
877 logger('diaspora_like: owner verification failed.');
882 // Phew! Everything checks out. Now create an item.
884 $uri = $diaspora_handle . ':' . $guid;
886 $activity = ACTIVITY_LIKE;
887 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
888 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
889 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
890 $body = $parent_item['body'];
895 <type>$objtype</type>
897 <id>{$parent_item['uri']}</id>
900 <content>$body</content>
903 $bodyverb = t('%1$s likes %2$s\'s %3$s');
908 $arr['uid'] = $importer['uid'];
909 $arr['guid'] = $guid;
910 $arr['contact-id'] = $contact['id'];
911 $arr['type'] = 'activity';
912 $arr['wall'] = $parent_item['wall'];
913 $arr['gravity'] = GRAVITY_LIKE;
914 $arr['parent'] = $parent_item['id'];
915 $arr['parent-uri'] = $parent_item['uri'];
917 $arr['owner-name'] = $contact['name'];
918 $arr['owner-link'] = $contact['url'];
919 $arr['owner-avatar'] = $contact['thumb'];
921 $arr['author-name'] = $person['name'];
922 $arr['author-link'] = $person['url'];
923 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
925 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
926 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
927 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
928 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
930 $arr['app'] = 'Diaspora';
932 $arr['private'] = $parent_item['private'];
933 $arr['verb'] = $activity;
934 $arr['object-type'] = $objtype;
935 $arr['object'] = $obj;
938 $arr['last-child'] = 0;
940 $message_id = item_store($arr);
944 q("update item set plink = '%s' where id = %d limit 1",
945 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
950 if(! $parent_author_signature) {
951 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
953 dbesc($author_signed_data),
954 dbesc(base64_encode($author_signature)),
955 dbesc($diaspora_handle)
959 // if the message isn't already being relayed, notify others
960 // the existence of parent_author_signature means the parent_author or owner
961 // is already relaying.
963 if(! $parent_author_signature)
964 proc_run('php','include/notifier.php','comment',$message_id);
969 function diaspora_retraction($importer,$xml) {
971 $guid = notags(unxmlify($xml->guid));
972 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
973 $type = notags(unxmlify($xml->type));
975 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
979 if($type === 'Person') {
980 contact_remove($contact['id']);
982 elseif($type === 'Post') {
983 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
985 intval($importer['uid'])
988 if(link_compare($r[0]['author-link'],$contact['url'])) {
989 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
990 dbesc(datetime_convert()),
1001 function diaspora_profile($importer,$xml) {
1004 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1006 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1010 if($contact['blocked']) {
1011 logger('diaspora_post: Ignoring this author.');
1015 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1016 $image_url = unxmlify($xml->image_url);
1017 $birthday = unxmlify($xml->birthday);
1019 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1020 intval($importer['uid']),
1021 intval($contact['id'])
1023 $oldphotos = ((count($r)) ? $r : null);
1025 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1027 // Generic birthday. We don't know the timezone. The year is irrelevant.
1029 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1031 $r = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
1033 dbesc(datetime_convert()),
1037 dbesc(datetime_convert()),
1038 intval($contact['id']),
1039 intval($importer['uid']),
1044 foreach($oldphotos as $ph) {
1045 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1046 intval($importer['uid']),
1047 intval($contact['id']),
1048 dbesc($ph['resource-id'])
1079 function diaspora_share($me,$contact) {
1081 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1082 $theiraddr = $contact['addr'];
1084 $tpl = get_markup_template('diaspora_share.tpl');
1085 $msg = replace_macros($tpl, array(
1086 '$sender' => $myaddr,
1087 '$recipient' => $theiraddr
1090 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1092 return(diaspora_transmit($owner,$contact,$slap, false));
1095 function diaspora_unshare($me,$contact) {
1098 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1100 $tpl = get_markup_template('diaspora_retract.tpl');
1101 $msg = replace_macros($tpl, array(
1102 '$guid' => $me['guid'],
1103 '$type' => 'Person',
1104 '$handle' => $myaddr
1107 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1109 return(diaspora_transmit($owner,$contact,$slap, false));
1115 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1118 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1119 $theiraddr = $contact['addr'];
1123 $body = $item['body'];
1125 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1127 foreach($matches as $mtch) {
1129 $detail['str'] = $mtch[0];
1130 $detail['path'] = dirname($mtch[1]) . '/';
1131 $detail['file'] = basename($mtch[1]);
1132 $detail['guid'] = $item['guid'];
1133 $detail['handle'] = $myaddr;
1134 $images[] = $detail;
1135 $body = str_replace($detail['str'],t('link'),$body);
1139 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1141 $public = (($item['private']) ? 'false' : 'true');
1143 require_once('include/datetime.php');
1144 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1146 $tpl = get_markup_template('diaspora_post.tpl');
1147 $msg = replace_macros($tpl, array(
1149 '$guid' => $item['guid'],
1150 '$handle' => xmlify($myaddr),
1151 '$public' => $public,
1152 '$created' => $created
1155 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1157 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1159 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1161 if(count($images)) {
1162 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1165 return $return_code;
1169 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1171 if(! count($images))
1173 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1175 $tpl = get_markup_template('diaspora_photo.tpl');
1176 foreach($images as $image) {
1177 if(! stristr($image['path'],$mysite))
1179 $resource = str_replace('.jpg','',$image['file']);
1180 $resource = substr($resource,0,strpos($resource,'-'));
1182 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1184 intval($owner['uid'])
1188 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1189 $msg = replace_macros($tpl,array(
1190 '$path' => xmlify($image['path']),
1191 '$filename' => xmlify($image['file']),
1192 '$msg_guid' => xmlify($image['guid']),
1193 '$guid' => xmlify($r[0]['guid']),
1194 '$handle' => xmlify($image['handle']),
1195 '$public' => xmlify($public),
1196 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1200 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1201 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1203 diaspora_transmit($owner,$contact,$slap,$public_batch);
1208 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1211 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1212 $theiraddr = $contact['addr'];
1214 $p = q("select guid from item where parent = %d limit 1",
1218 $parent_guid = $p[0]['guid'];
1222 if($item['verb'] === ACTIVITY_LIKE) {
1223 $tpl = get_markup_template('diaspora_like.tpl');
1225 $target_type = 'Post';
1226 $positive = (($item['deleted']) ? 'false' : 'true');
1229 $tpl = get_markup_template('diaspora_comment.tpl');
1233 $text = html_entity_decode(bb2diaspora($item['body']));
1238 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1240 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1242 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1244 $msg = replace_macros($tpl,array(
1245 '$guid' => xmlify($item['guid']),
1246 '$parent_guid' => xmlify($parent_guid),
1247 '$target_type' =>xmlify($target_type),
1248 '$authorsig' => xmlify($authorsig),
1249 '$body' => xmlify($text),
1250 '$positive' => xmlify($positive),
1251 '$handle' => xmlify($myaddr)
1254 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1256 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1258 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1262 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1266 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1267 $theiraddr = $contact['addr'];
1270 $p = q("select guid from item where parent = %d limit 1",
1274 $parent_guid = $p[0]['guid'];
1278 if($item['verb'] === ACTIVITY_LIKE) {
1279 $tpl = get_markup_template('diaspora_like_relay.tpl');
1281 $target_type = 'Post';
1282 $positive = (($item['deleted']) ? 'false' : 'true');
1285 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1289 $body = $item['body'];
1291 $text = html_entity_decode(bb2diaspora($body));
1293 // fetch the original signature if somebody sent the post to us to relay
1294 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1295 // action. It wasn't needed. In that case create the original signature and the
1296 // owner (parent author) signature
1297 // comments from other networks will be relayed under our name, with a brief
1298 // preamble to describe what's happening and noting the real author
1300 $r = q("select * from sign where iid = %d limit 1",
1305 $signed_text = $orig_sign['signed_text'];
1306 $authorsig = $orig_sign['signature'];
1307 $handle = $orig_sign['signer'];
1311 $itemcontact = q("select * from contact where `id` = %d limit 1",
1312 intval($item['contact-id'])
1314 if(count($itemcontact)) {
1315 if(! $itemcontact[0]['self']) {
1316 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1317 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1318 network_to_name($itemcontact['network'])) . "\n";
1319 $body = $prefix . $body;
1325 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1327 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1329 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1331 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1332 intval($item['id']),
1333 dbesc($signed_text),
1334 dbesc(base64_encode($authorsig)),
1343 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1345 $msg = replace_macros($tpl,array(
1346 '$guid' => xmlify($item['guid']),
1347 '$parent_guid' => xmlify($parent_guid),
1348 '$target_type' =>xmlify($target_type),
1349 '$authorsig' => xmlify($orig_sign['signature']),
1350 '$parentsig' => xmlify($parentauthorsig),
1351 '$body' => xmlify($text),
1352 '$positive' => xmlify($positive),
1353 '$handle' => xmlify($handle)
1356 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1358 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1360 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1366 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1369 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1371 $tpl = get_markup_template('diaspora_retract.tpl');
1372 $msg = replace_macros($tpl, array(
1373 '$guid' => $item['guid'],
1375 '$handle' => $myaddr
1378 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1380 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1385 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1388 $logid = random_string(4);
1389 logger('diaspora_transmit: ' . $logid . ' ' . (($public_batch) ? $contact['batch'] : $contact['notify']));
1390 post_url((($public_batch) ? $contact['batch'] : $contact['notify']) . '/',$slap);
1391 $return_code = $a->get_curl_code();
1392 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1394 if((! $return_code) || (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1395 logger('diaspora_transmit: queue message');
1396 // queue message for redelivery
1397 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`,`batch`)
1398 VALUES ( %d, '%s', '%s', '%s', %d) ",
1399 intval($contact['id']),
1400 dbesc(datetime_convert()),
1401 dbesc(datetime_convert()),
1403 intval($public_batch)
1408 return(($return_code) ? $return_code : (-1));