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 // php doesn't like dashes in variable names
33 $msg['message'] = str_replace(
34 array('<activity_streams-photo>','</activity_streams-photo>'),
35 array('<asphoto>','</asphoto>'),
39 $parsed_xml = parse_xml_string($msg['message'],false);
41 $xmlbase = $parsed_xml->post;
43 if($xmlbase->request) {
44 $ret = diaspora_request($importer,$xmlbase->request);
46 elseif($xmlbase->status_message) {
47 $ret = diaspora_post($importer,$xmlbase->status_message);
49 elseif($xmlbase->profile) {
50 $ret = diaspora_profile($importer,$xmlbase->profile);
52 elseif($xmlbase->comment) {
53 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
55 elseif($xmlbase->like) {
56 $ret = diaspora_like($importer,$xmlbase->like,$msg);
58 elseif($xmlbase->asphoto) {
59 $ret = diaspora_asphoto($importer,$xmlbase->asphoto);
61 elseif($xmlbase->retraction) {
62 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
64 elseif($xmlbase->photo) {
65 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
68 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
73 function diaspora_get_contact_by_handle($uid,$handle) {
74 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
75 dbesc(NETWORK_DIASPORA),
84 function find_diaspora_person_by_handle($handle) {
86 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
87 dbesc(NETWORK_DIASPORA),
91 // update record occasionally so it doesn't get stale
92 $d = strtotime($r[0]['updated'] . ' +00:00');
93 if($d > strtotime('now - 14 days'))
97 require_once('include/Scrape.php');
98 $r = probe_url($handle, PROBE_DIASPORA);
99 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
100 add_fcontact($r,$update);
107 function get_diaspora_key($uri) {
108 logger('Fetching diaspora key for: ' . $uri);
110 $r = find_diaspora_person_by_handle($uri);
117 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
120 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
123 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
125 // $b64_data = base64_encode($msg);
126 // $b64url_data = base64url_encode($b64_data);
128 $b64url_data = base64url_encode($msg);
130 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
132 $type = 'application/xml';
133 $encoding = 'base64url';
136 $signable_data = $data . '.' . base64url_encode($type) . '.'
137 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
139 $signature = rsa_sign($signable_data,$prvkey);
140 $sig = base64url_encode($signature);
143 <?xml version='1.0' encoding='UTF-8'?>
144 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
146 <author_id>$handle</author_id>
149 <me:encoding>base64url</me:encoding>
150 <me:alg>RSA-SHA256</me:alg>
151 <me:data type="application/xml">$data</me:data>
152 <me:sig>$sig</me:sig>
157 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
165 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
169 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
171 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
173 $inner_aes_key = random_string(32);
174 $b_inner_aes_key = base64_encode($inner_aes_key);
175 $inner_iv = random_string(16);
176 $b_inner_iv = base64_encode($inner_iv);
178 $outer_aes_key = random_string(32);
179 $b_outer_aes_key = base64_encode($outer_aes_key);
180 $outer_iv = random_string(16);
181 $b_outer_iv = base64_encode($outer_iv);
183 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
185 $padded_data = pkcs5_pad($msg,16);
186 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
188 $b64_data = base64_encode($inner_encrypted);
191 $b64url_data = base64url_encode($b64_data);
192 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
194 $type = 'application/xml';
195 $encoding = 'base64url';
198 $signable_data = $data . '.' . base64url_encode($type) . '.'
199 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
201 $signature = rsa_sign($signable_data,$prvkey);
202 $sig = base64url_encode($signature);
204 $decrypted_header = <<< EOT
207 <aes_key>$b_inner_aes_key</aes_key>
208 <author_id>$handle</author_id>
212 $decrypted_header = pkcs5_pad($decrypted_header,16);
214 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
216 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
218 $encrypted_outer_key_bundle = '';
219 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
221 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
223 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
225 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
226 'ciphertext' => base64_encode($ciphertext)));
227 $cipher_json = base64_encode($encrypted_header_json_object);
229 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
232 <?xml version='1.0' encoding='UTF-8'?>
233 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
236 <me:encoding>base64url</me:encoding>
237 <me:alg>RSA-SHA256</me:alg>
238 <me:data type="application/xml">$data</me:data>
239 <me:sig>$sig</me:sig>
244 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
251 * diaspora_decode($importer,$xml)
252 * array $importer -> from user table
253 * string $xml -> urldecoded Diaspora salmon
256 * 'message' -> decoded Diaspora XML message
257 * 'author' -> author diaspora handle
258 * 'key' -> author public key (converted to pkcs#8)
260 * Author and key are used elsewhere to save a lookup for verifying replies and likes
264 function diaspora_decode($importer,$xml) {
267 $basedom = parse_xml_string($xml);
269 $children = $basedom->children('https://joindiaspora.com/protocol');
271 if($children->header) {
273 $author_link = str_replace('acct:','',$children->header->author_id);
277 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
279 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
280 $ciphertext = base64_decode($encrypted_header->ciphertext);
282 $outer_key_bundle = '';
283 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
285 $j_outer_key_bundle = json_decode($outer_key_bundle);
287 $outer_iv = base64_decode($j_outer_key_bundle->iv);
288 $outer_key = base64_decode($j_outer_key_bundle->key);
290 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
293 $decrypted = pkcs5_unpad($decrypted);
296 * $decrypted now contains something like
299 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
300 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
305 * <name>Ryan Hughes</name>
306 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
311 * <author_id>galaxor@diaspora.priateship.org</author_id>
315 * </decrypted_header>
318 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
319 $idom = parse_xml_string($decrypted,false);
321 $inner_iv = base64_decode($idom->iv);
322 $inner_aes_key = base64_decode($idom->aes_key);
324 $author_link = str_replace('acct:','',$idom->author_id);
328 $dom = $basedom->children(NAMESPACE_SALMON_ME);
330 // figure out where in the DOM tree our data is hiding
332 if($dom->provenance->data)
333 $base = $dom->provenance;
334 elseif($dom->env->data)
340 logger('mod-diaspora: unable to locate salmon data in xml ');
341 http_status_exit(400);
345 // Stash the signature away for now. We have to find their key or it won't be good for anything.
346 $signature = base64url_decode($base->sig);
350 // strip whitespace so our data element will return to one big base64 blob
351 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
354 // stash away some other stuff for later
356 $type = $base->data[0]->attributes()->type[0];
357 $keyhash = $base->sig[0]->attributes()->keyhash[0];
358 $encoding = $base->encoding;
362 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
366 $data = base64url_decode($data);
370 $inner_decrypted = $data;
374 // Decode the encrypted blob
376 $inner_encrypted = base64_decode($data);
377 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
378 $inner_decrypted = pkcs5_unpad($inner_decrypted);
382 logger('mod-diaspora: Could not retrieve author URI.');
383 http_status_exit(400);
386 // Once we have the author URI, go to the web and try to find their public key
387 // (first this will look it up locally if it is in the fcontact cache)
388 // This will also convert diaspora public key from pkcs#1 to pkcs#8
390 logger('mod-diaspora: Fetching key for ' . $author_link );
391 $key = get_diaspora_key($author_link);
394 logger('mod-diaspora: Could not retrieve author key.');
395 http_status_exit(400);
398 $verify = rsa_verify($signed_data,$signature,$key);
401 logger('mod-diaspora: Message did not verify. Discarding.');
402 http_status_exit(400);
405 logger('mod-diaspora: Message verified.');
407 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
412 function diaspora_request($importer,$xml) {
414 $sender_handle = unxmlify($xml->sender_handle);
415 $recipient_handle = unxmlify($xml->recipient_handle);
417 if(! $sender_handle || ! $recipient_handle)
420 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
424 // perhaps we were already sharing with this person. Now they're sharing with us.
425 // That makes us friends.
427 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
428 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
429 intval(CONTACT_IS_FRIEND),
430 intval($contact['id']),
431 intval($importer['uid'])
434 // send notification?
438 $ret = find_diaspora_person_by_handle($sender_handle);
441 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
442 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
446 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
448 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
449 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
450 intval($importer['uid']),
451 dbesc($ret['network']),
458 dbesc($ret['photo']),
459 dbesc($ret['pubkey']),
460 dbesc($ret['notify']),
466 // find the contact record we just created
468 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
470 $hash = random_string() . (string) time(); // Generate a confirm_key
472 if($contact_record) {
473 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
474 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
475 intval($importer['uid']),
476 intval($contact_record['id']),
479 dbesc( t('Sharing notification from Diaspora network')),
481 dbesc(datetime_convert())
488 function diaspora_post($importer,$xml) {
491 $guid = notags(unxmlify($xml->guid));
492 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
494 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
498 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
499 logger('diaspora_post: Ignoring this author.');
503 $message_id = $diaspora_handle . ':' . $guid;
504 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
505 intval($importer['uid']),
510 logger('diaspora_post: message exists: ' . $guid);
514 // allocate a guid on our system - we aren't fixing any collisions.
515 // we're ignoring them
517 $g = q("select * from guid where guid = '%s' limit 1",
521 q("insert into guid ( guid ) values ( '%s' )",
526 $created = unxmlify($xml->created_at);
527 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
529 $body = diaspora2bb($xml->raw_message);
535 $tags = get_tags($body);
538 foreach($tags as $tag) {
539 if(strpos($tag,'#') === 0) {
540 if(strpos($tag,'[url='))
542 $basetag = str_replace('_',' ',substr($tag,1));
543 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
544 if(strlen($str_tags))
546 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
552 $datarray['uid'] = $importer['uid'];
553 $datarray['contact-id'] = $contact['id'];
554 $datarray['wall'] = 0;
555 $datarray['guid'] = $guid;
556 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
557 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
558 $datarray['private'] = $private;
559 $datarray['parent'] = 0;
560 $datarray['owner-name'] = $contact['name'];
561 $datarray['owner-link'] = $contact['url'];
562 $datarray['owner-avatar'] = $contact['thumb'];
563 $datarray['author-name'] = $contact['name'];
564 $datarray['author-link'] = $contact['url'];
565 $datarray['author-avatar'] = $contact['thumb'];
566 $datarray['body'] = $body;
567 $datarray['tag'] = $str_tags;
568 $datarray['app'] = 'Diaspora';
570 $message_id = item_store($datarray);
573 q("update item set plink = '%s' where id = %d limit 1",
574 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
583 function diaspora_asphoto($importer,$xml) {
586 $guid = notags(unxmlify($xml->guid));
587 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
589 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
593 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
594 logger('diaspora_asphoto: Ignoring this author.');
598 $message_id = $diaspora_handle . ':' . $guid;
599 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
600 intval($importer['uid']),
605 logger('diaspora_asphoto: message exists: ' . $guid);
609 // allocate a guid on our system - we aren't fixing any collisions.
610 // we're ignoring them
612 $g = q("select * from guid where guid = '%s' limit 1",
616 q("insert into guid ( guid ) values ( '%s' )",
621 $created = unxmlify($xml->created_at);
622 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
624 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url))
625 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img=' . notags(unxmlify($xml->objectId)) . '][/img][/url]' . "\n";
626 elseif($xml->image_url)
627 $body = '[img=' . notags(unxmlify($xml->image_url)) . '][/img]' . "\n";
629 logger('diaspora_asphoto: no photo url found.');
637 $datarray['uid'] = $importer['uid'];
638 $datarray['contact-id'] = $contact['id'];
639 $datarray['wall'] = 0;
640 $datarray['guid'] = $guid;
641 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
642 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
643 $datarray['private'] = $private;
644 $datarray['parent'] = 0;
645 $datarray['owner-name'] = $contact['name'];
646 $datarray['owner-link'] = $contact['url'];
647 $datarray['owner-avatar'] = $contact['thumb'];
648 $datarray['author-name'] = $contact['name'];
649 $datarray['author-link'] = $contact['url'];
650 $datarray['author-avatar'] = $contact['thumb'];
651 $datarray['body'] = $body;
653 $datarray['app'] = 'Diaspora/Cubbi.es';
655 $message_id = item_store($datarray);
658 q("update item set plink = '%s' where id = %d limit 1",
659 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
673 function diaspora_comment($importer,$xml,$msg) {
676 $guid = notags(unxmlify($xml->guid));
677 $parent_guid = notags(unxmlify($xml->parent_guid));
678 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
679 $target_type = notags(unxmlify($xml->target_type));
680 $text = unxmlify($xml->text);
681 $author_signature = notags(unxmlify($xml->author_signature));
683 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
687 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
689 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
693 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
694 logger('diaspora_comment: Ignoring this author.');
698 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
699 intval($importer['uid']),
703 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
707 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
708 intval($importer['uid']),
712 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
715 $parent_item = $r[0];
717 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
719 $author_signature = base64_decode($author_signature);
721 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
726 $person = find_diaspora_person_by_handle($diaspora_handle);
728 if(is_array($person) && x($person,'pubkey'))
729 $key = $person['pubkey'];
731 logger('diaspora_comment: unable to find author details');
736 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
737 logger('diaspora_comment: verification failed.');
741 if($parent_author_signature) {
742 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
744 $parent_author_signature = base64_decode($parent_author_signature);
748 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
749 logger('diaspora_comment: owner verification failed.');
754 // Phew! Everything checks out. Now create an item.
756 $body = diaspora2bb($text);
758 $message_id = $diaspora_handle . ':' . $guid;
764 $tags = get_tags($body);
767 foreach($tags as $tag) {
768 if(strpos($tag,'#') === 0) {
769 if(strpos($tag,'[url='))
771 $basetag = str_replace('_',' ',substr($tag,1));
772 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
773 if(strlen($str_tags))
775 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
781 $datarray['uid'] = $importer['uid'];
782 $datarray['contact-id'] = $contact['id'];
783 $datarray['wall'] = $parent_item['wall'];
784 $datarray['gravity'] = GRAVITY_COMMENT;
785 $datarray['guid'] = $guid;
786 $datarray['uri'] = $message_id;
787 $datarray['parent-uri'] = $parent_item['uri'];
789 // No timestamps for comments? OK, we'll the use current time.
790 $datarray['created'] = $datarray['edited'] = datetime_convert();
791 $datarray['private'] = $parent_item['private'];
793 $datarray['owner-name'] = $parent_item['owner-name'];
794 $datarray['owner-link'] = $parent_item['owner-link'];
795 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
797 $datarray['author-name'] = $person['name'];
798 $datarray['author-link'] = $person['url'];
799 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
800 $datarray['body'] = $body;
801 $datarray['tag'] = $str_tags;
802 $datarray['app'] = 'Diaspora';
804 $message_id = item_store($datarray);
807 q("update item set plink = '%s' where id = %d limit 1",
808 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
813 if(! $parent_author_signature) {
814 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
816 dbesc($author_signed_data),
817 dbesc(base64_encode($author_signature)),
818 dbesc($diaspora_handle)
821 // if the message isn't already being relayed, notify others
822 // the existence of parent_author_signature means the parent_author or owner
823 // is already relaying.
825 proc_run('php','include/notifier.php','comment',$message_id);
830 function diaspora_photo($importer,$xml,$msg) {
833 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
835 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
837 $status_message_guid = notags(unxmlify($xml->status_message_guid));
839 $guid = notags(unxmlify($xml->guid));
841 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
843 $public = notags(unxmlify($xml->public));
845 $created_at = notags(unxmlify($xml_created_at));
848 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
852 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
853 logger('diaspora_photo: Ignoring this author.');
857 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
858 intval($importer['uid']),
859 dbesc($status_message_guid)
862 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
865 $parent_item = $r[0];
867 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
869 if(strpos($parent_item['body'],$link_text) === false) {
870 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
871 dbesc($link_text . $parent_item['body']),
872 intval($parent_item['id']),
873 intval($parent_item['uid'])
883 function diaspora_like($importer,$xml,$msg) {
886 $guid = notags(unxmlify($xml->guid));
887 $parent_guid = notags(unxmlify($xml->parent_guid));
888 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
889 $target_type = notags(unxmlify($xml->target_type));
890 $positive = notags(unxmlify($xml->positive));
891 $author_signature = notags(unxmlify($xml->author_signature));
893 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
895 // likes on comments not supported here and likes on photos not supported by Diaspora
897 if($target_type !== 'Post')
900 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
902 logger('diaspora_like: cannot find contact: ' . $msg['author']);
906 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
907 logger('diaspora_like: Ignoring this author.');
911 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
912 intval($importer['uid']),
916 logger('diaspora_like: parent item not found: ' . $guid);
920 $parent_item = $r[0];
922 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
923 intval($importer['uid']),
927 if($positive === 'true') {
928 logger('diaspora_like: duplicate like: ' . $guid);
931 if($positive === 'false') {
932 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
934 intval($importer['uid'])
937 // send notification via proc_run()
941 if($positive === 'false') {
942 logger('diaspora_like: unlike received with no corresponding like');
946 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
948 $author_signature = base64_decode($author_signature);
950 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
955 $person = find_diaspora_person_by_handle($diaspora_handle);
956 if(is_array($person) && x($person,'pubkey'))
957 $key = $person['pubkey'];
959 logger('diaspora_like: unable to find author details');
964 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
965 logger('diaspora_like: verification failed.');
969 if($parent_author_signature) {
971 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
973 $parent_author_signature = base64_decode($parent_author_signature);
977 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
978 logger('diaspora_like: owner verification failed.');
983 // Phew! Everything checks out. Now create an item.
985 $uri = $diaspora_handle . ':' . $guid;
987 $activity = ACTIVITY_LIKE;
988 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
989 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
990 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
991 $body = $parent_item['body'];
996 <type>$objtype</type>
998 <id>{$parent_item['uri']}</id>
1001 <content>$body</content>
1004 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1009 $arr['uid'] = $importer['uid'];
1010 $arr['guid'] = $guid;
1011 $arr['contact-id'] = $contact['id'];
1012 $arr['type'] = 'activity';
1013 $arr['wall'] = $parent_item['wall'];
1014 $arr['gravity'] = GRAVITY_LIKE;
1015 $arr['parent'] = $parent_item['id'];
1016 $arr['parent-uri'] = $parent_item['uri'];
1018 $arr['owner-name'] = $contact['name'];
1019 $arr['owner-link'] = $contact['url'];
1020 $arr['owner-avatar'] = $contact['thumb'];
1022 $arr['author-name'] = $person['name'];
1023 $arr['author-link'] = $person['url'];
1024 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1026 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1027 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1028 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1029 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1031 $arr['app'] = 'Diaspora';
1033 $arr['private'] = $parent_item['private'];
1034 $arr['verb'] = $activity;
1035 $arr['object-type'] = $objtype;
1036 $arr['object'] = $obj;
1037 $arr['visible'] = 1;
1039 $arr['last-child'] = 0;
1041 $message_id = item_store($arr);
1045 q("update item set plink = '%s' where id = %d limit 1",
1046 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1051 if(! $parent_author_signature) {
1052 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1053 intval($message_id),
1054 dbesc($author_signed_data),
1055 dbesc(base64_encode($author_signature)),
1056 dbesc($diaspora_handle)
1060 // if the message isn't already being relayed, notify others
1061 // the existence of parent_author_signature means the parent_author or owner
1062 // is already relaying.
1064 if(! $parent_author_signature)
1065 proc_run('php','include/notifier.php','comment',$message_id);
1070 function diaspora_retraction($importer,$xml) {
1072 $guid = notags(unxmlify($xml->guid));
1073 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1074 $type = notags(unxmlify($xml->type));
1076 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1080 if($type === 'Person') {
1081 contact_remove($contact['id']);
1083 elseif($type === 'Post') {
1084 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1086 intval($importer['uid'])
1089 if(link_compare($r[0]['author-link'],$contact['url'])) {
1090 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1091 dbesc(datetime_convert()),
1102 function diaspora_profile($importer,$xml) {
1105 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1107 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1111 if($contact['blocked']) {
1112 logger('diaspora_post: Ignoring this author.');
1116 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1117 $image_url = unxmlify($xml->image_url);
1118 $birthday = unxmlify($xml->birthday);
1120 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1121 intval($importer['uid']),
1122 intval($contact['id'])
1124 $oldphotos = ((count($r)) ? $r : null);
1126 require_once('include/Photo.php');
1128 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1130 // Generic birthday. We don't know the timezone. The year is irrelevant.
1132 $birthday = str_replace('1000','1901',$birthday);
1134 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1136 $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",
1138 dbesc(datetime_convert()),
1142 dbesc(datetime_convert()),
1144 intval($contact['id']),
1145 intval($importer['uid'])
1150 foreach($oldphotos as $ph) {
1151 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1152 intval($importer['uid']),
1153 intval($contact['id']),
1154 dbesc($ph['resource-id'])
1185 function diaspora_share($me,$contact) {
1187 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1188 $theiraddr = $contact['addr'];
1190 $tpl = get_markup_template('diaspora_share.tpl');
1191 $msg = replace_macros($tpl, array(
1192 '$sender' => $myaddr,
1193 '$recipient' => $theiraddr
1196 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1198 return(diaspora_transmit($owner,$contact,$slap, false));
1201 function diaspora_unshare($me,$contact) {
1204 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1206 $tpl = get_markup_template('diaspora_retract.tpl');
1207 $msg = replace_macros($tpl, array(
1208 '$guid' => $me['guid'],
1209 '$type' => 'Person',
1210 '$handle' => $myaddr
1213 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1215 return(diaspora_transmit($owner,$contact,$slap, false));
1221 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1224 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1225 $theiraddr = $contact['addr'];
1229 $body = $item['body'];
1231 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1233 foreach($matches as $mtch) {
1235 $detail['str'] = $mtch[0];
1236 $detail['path'] = dirname($mtch[1]) . '/';
1237 $detail['file'] = basename($mtch[1]);
1238 $detail['guid'] = $item['guid'];
1239 $detail['handle'] = $myaddr;
1240 $images[] = $detail;
1241 $body = str_replace($detail['str'],t('link'),$body);
1245 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1247 $public = (($item['private']) ? 'false' : 'true');
1249 require_once('include/datetime.php');
1250 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1252 $tpl = get_markup_template('diaspora_post.tpl');
1253 $msg = replace_macros($tpl, array(
1255 '$guid' => $item['guid'],
1256 '$handle' => xmlify($myaddr),
1257 '$public' => $public,
1258 '$created' => $created
1261 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1263 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1265 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1267 if(count($images)) {
1268 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1271 return $return_code;
1275 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1277 if(! count($images))
1279 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1281 $tpl = get_markup_template('diaspora_photo.tpl');
1282 foreach($images as $image) {
1283 if(! stristr($image['path'],$mysite))
1285 $resource = str_replace('.jpg','',$image['file']);
1286 $resource = substr($resource,0,strpos($resource,'-'));
1288 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1290 intval($owner['uid'])
1294 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1295 $msg = replace_macros($tpl,array(
1296 '$path' => xmlify($image['path']),
1297 '$filename' => xmlify($image['file']),
1298 '$msg_guid' => xmlify($image['guid']),
1299 '$guid' => xmlify($r[0]['guid']),
1300 '$handle' => xmlify($image['handle']),
1301 '$public' => xmlify($public),
1302 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1306 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1307 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1309 diaspora_transmit($owner,$contact,$slap,$public_batch);
1314 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1317 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1318 $theiraddr = $contact['addr'];
1320 $p = q("select guid from item where parent = %d limit 1",
1324 $parent_guid = $p[0]['guid'];
1328 if($item['verb'] === ACTIVITY_LIKE) {
1329 $tpl = get_markup_template('diaspora_like.tpl');
1331 $target_type = 'Post';
1332 $positive = (($item['deleted']) ? 'false' : 'true');
1335 $tpl = get_markup_template('diaspora_comment.tpl');
1339 $text = html_entity_decode(bb2diaspora($item['body']));
1344 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1346 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1348 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1350 $msg = replace_macros($tpl,array(
1351 '$guid' => xmlify($item['guid']),
1352 '$parent_guid' => xmlify($parent_guid),
1353 '$target_type' =>xmlify($target_type),
1354 '$authorsig' => xmlify($authorsig),
1355 '$body' => xmlify($text),
1356 '$positive' => xmlify($positive),
1357 '$handle' => xmlify($myaddr)
1360 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1362 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1364 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1368 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1372 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1373 $theiraddr = $contact['addr'];
1376 $p = q("select guid from item where parent = %d limit 1",
1380 $parent_guid = $p[0]['guid'];
1384 if($item['verb'] === ACTIVITY_LIKE) {
1385 $tpl = get_markup_template('diaspora_like_relay.tpl');
1387 $target_type = 'Post';
1388 $positive = (($item['deleted']) ? 'false' : 'true');
1391 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1395 $body = $item['body'];
1397 $text = html_entity_decode(bb2diaspora($body));
1399 // fetch the original signature if somebody sent the post to us to relay
1400 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1401 // action. It wasn't needed. In that case create the original signature and the
1402 // owner (parent author) signature
1403 // comments from other networks will be relayed under our name, with a brief
1404 // preamble to describe what's happening and noting the real author
1406 $r = q("select * from sign where iid = %d limit 1",
1411 $signed_text = $orig_sign['signed_text'];
1412 $authorsig = $orig_sign['signature'];
1413 $handle = $orig_sign['signer'];
1417 $itemcontact = q("select * from contact where `id` = %d limit 1",
1418 intval($item['contact-id'])
1420 if(count($itemcontact)) {
1421 if(! $itemcontact[0]['self']) {
1422 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1423 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1424 network_to_name($itemcontact['network'])) . "\n";
1425 $body = $prefix . $body;
1431 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1433 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1435 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1437 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1438 intval($item['id']),
1439 dbesc($signed_text),
1440 dbesc(base64_encode($authorsig)),
1449 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1451 $msg = replace_macros($tpl,array(
1452 '$guid' => xmlify($item['guid']),
1453 '$parent_guid' => xmlify($parent_guid),
1454 '$target_type' =>xmlify($target_type),
1455 '$authorsig' => xmlify($orig_sign['signature']),
1456 '$parentsig' => xmlify($parentauthorsig),
1457 '$body' => xmlify($text),
1458 '$positive' => xmlify($positive),
1459 '$handle' => xmlify($handle)
1462 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1464 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1466 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1472 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1475 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1477 $tpl = get_markup_template('diaspora_retract.tpl');
1478 $msg = replace_macros($tpl, array(
1479 '$guid' => $item['guid'],
1481 '$handle' => $myaddr
1484 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1486 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1491 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1494 $logid = random_string(4);
1495 logger('diaspora_transmit: ' . $logid . ' ' . (($public_batch) ? $contact['batch'] : $contact['notify']));
1496 post_url((($public_batch) ? $contact['batch'] : $contact['notify']) . '/',$slap);
1497 $return_code = $a->get_curl_code();
1498 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1500 if((! $return_code) || (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1501 logger('diaspora_transmit: queue message');
1502 // queue message for redelivery
1503 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`,`batch`)
1504 VALUES ( %d, '%s', '%s', '%s', %d) ",
1505 intval($contact['id']),
1506 dbesc(datetime_convert()),
1507 dbesc(datetime_convert()),
1509 intval($public_batch)
1514 return(($return_code) ? $return_code : (-1));