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->comment) {
42 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
44 elseif($xmlbase->like) {
45 $ret = diaspora_like($importer,$xmlbase->like,$msg);
47 elseif($xmlbase->retraction) {
48 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
50 elseif($xmlbase->photo) {
51 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
54 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
59 function diaspora_get_contact_by_handle($uid,$handle) {
60 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
61 dbesc(NETWORK_DIASPORA),
70 function find_diaspora_person_by_handle($handle) {
72 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
73 dbesc(NETWORK_DIASPORA),
77 // update record occasionally so it doesn't get stale
78 $d = strtotime($r[0]['updated'] . ' +00:00');
79 if($d > strtotime('now - 14 days'))
83 require_once('include/Scrape.php');
84 $r = probe_url($handle, PROBE_DIASPORA);
85 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
86 add_fcontact($r,$update);
93 function get_diaspora_key($uri) {
94 logger('Fetching diaspora key for: ' . $uri);
96 $r = find_diaspora_person_by_handle($uri);
103 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
106 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
109 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
111 // $b64_data = base64_encode($msg);
112 // $b64url_data = base64url_encode($b64_data);
114 $b64url_data = base64url_encode($msg);
116 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
118 $type = 'application/xml';
119 $encoding = 'base64url';
122 $signable_data = $data . '.' . base64url_encode($type) . '.'
123 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
125 $signature = rsa_sign($signable_data,$prvkey);
126 $sig = base64url_encode($signature);
129 <?xml version='1.0' encoding='UTF-8'?>
130 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
132 <author_id>$handle</author_id>
135 <me:encoding>base64url</me:encoding>
136 <me:alg>RSA-SHA256</me:alg>
137 <me:data type="application/xml">$data</me:data>
138 <me:sig>$sig</me:sig>
143 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
151 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
155 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
157 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
159 $inner_aes_key = random_string(32);
160 $b_inner_aes_key = base64_encode($inner_aes_key);
161 $inner_iv = random_string(16);
162 $b_inner_iv = base64_encode($inner_iv);
164 $outer_aes_key = random_string(32);
165 $b_outer_aes_key = base64_encode($outer_aes_key);
166 $outer_iv = random_string(16);
167 $b_outer_iv = base64_encode($outer_iv);
169 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
171 $padded_data = pkcs5_pad($msg,16);
172 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
174 $b64_data = base64_encode($inner_encrypted);
177 $b64url_data = base64url_encode($b64_data);
178 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
180 $type = 'application/xml';
181 $encoding = 'base64url';
184 $signable_data = $data . '.' . base64url_encode($type) . '.'
185 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
187 $signature = rsa_sign($signable_data,$prvkey);
188 $sig = base64url_encode($signature);
190 $decrypted_header = <<< EOT
193 <aes_key>$b_inner_aes_key</aes_key>
194 <author_id>$handle</author_id>
198 $decrypted_header = pkcs5_pad($decrypted_header,16);
200 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
202 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
204 $encrypted_outer_key_bundle = '';
205 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
207 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
209 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
211 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
212 'ciphertext' => base64_encode($ciphertext)));
213 $cipher_json = base64_encode($encrypted_header_json_object);
215 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
218 <?xml version='1.0' encoding='UTF-8'?>
219 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
222 <me:encoding>base64url</me:encoding>
223 <me:alg>RSA-SHA256</me:alg>
224 <me:data type="application/xml">$data</me:data>
225 <me:sig>$sig</me:sig>
230 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
237 * diaspora_decode($importer,$xml)
238 * array $importer -> from user table
239 * string $xml -> urldecoded Diaspora salmon
242 * 'message' -> decoded Diaspora XML message
243 * 'author' -> author diaspora handle
244 * 'key' -> author public key (converted to pkcs#8)
246 * Author and key are used elsewhere to save a lookup for verifying replies and likes
250 function diaspora_decode($importer,$xml) {
253 $basedom = parse_xml_string($xml);
255 $children = $basedom->children('https://joindiaspora.com/protocol');
257 if($children->header) {
259 $author_link = str_replace('acct:','',$children->header->author_id);
263 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
265 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
266 $ciphertext = base64_decode($encrypted_header->ciphertext);
268 $outer_key_bundle = '';
269 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
271 $j_outer_key_bundle = json_decode($outer_key_bundle);
273 $outer_iv = base64_decode($j_outer_key_bundle->iv);
274 $outer_key = base64_decode($j_outer_key_bundle->key);
276 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
279 $decrypted = pkcs5_unpad($decrypted);
282 * $decrypted now contains something like
285 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
286 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
291 * <name>Ryan Hughes</name>
292 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
297 * <author_id>galaxor@diaspora.priateship.org</author_id>
301 * </decrypted_header>
304 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
305 $idom = parse_xml_string($decrypted,false);
307 $inner_iv = base64_decode($idom->iv);
308 $inner_aes_key = base64_decode($idom->aes_key);
310 $author_link = str_replace('acct:','',$idom->author_id);
314 $dom = $basedom->children(NAMESPACE_SALMON_ME);
316 // figure out where in the DOM tree our data is hiding
318 if($dom->provenance->data)
319 $base = $dom->provenance;
320 elseif($dom->env->data)
326 logger('mod-diaspora: unable to locate salmon data in xml ');
327 http_status_exit(400);
331 // Stash the signature away for now. We have to find their key or it won't be good for anything.
332 $signature = base64url_decode($base->sig);
336 // strip whitespace so our data element will return to one big base64 blob
337 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
340 // stash away some other stuff for later
342 $type = $base->data[0]->attributes()->type[0];
343 $keyhash = $base->sig[0]->attributes()->keyhash[0];
344 $encoding = $base->encoding;
348 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
352 $data = base64url_decode($data);
356 $inner_decrypted = $data;
360 // Decode the encrypted blob
362 $inner_encrypted = base64_decode($data);
363 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
364 $inner_decrypted = pkcs5_unpad($inner_decrypted);
368 logger('mod-diaspora: Could not retrieve author URI.');
369 http_status_exit(400);
372 // Once we have the author URI, go to the web and try to find their public key
373 // (first this will look it up locally if it is in the fcontact cache)
374 // This will also convert diaspora public key from pkcs#1 to pkcs#8
376 logger('mod-diaspora: Fetching key for ' . $author_link );
377 $key = get_diaspora_key($author_link);
380 logger('mod-diaspora: Could not retrieve author key.');
381 http_status_exit(400);
384 $verify = rsa_verify($signed_data,$signature,$key);
387 logger('mod-diaspora: Message did not verify. Discarding.');
388 http_status_exit(400);
391 logger('mod-diaspora: Message verified.');
393 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
398 function diaspora_request($importer,$xml) {
400 $sender_handle = unxmlify($xml->sender_handle);
401 $recipient_handle = unxmlify($xml->recipient_handle);
403 if(! $sender_handle || ! $recipient_handle)
406 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
410 // perhaps we were already sharing with this person. Now they're sharing with us.
411 // That makes us friends.
413 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
414 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
415 intval(CONTACT_IS_FRIEND),
416 intval($contact['id']),
417 intval($importer['uid'])
420 // send notification?
424 $ret = find_diaspora_person_by_handle($sender_handle);
427 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
428 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
432 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
434 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
435 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
436 intval($importer['uid']),
437 dbesc($ret['network']),
444 dbesc($ret['photo']),
445 dbesc($ret['pubkey']),
446 dbesc($ret['notify']),
452 // find the contact record we just created
454 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
456 $hash = random_string() . (string) time(); // Generate a confirm_key
458 if($contact_record) {
459 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
460 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
461 intval($importer['uid']),
462 intval($contact_record['id']),
465 dbesc( t('Sharing notification from Diaspora network')),
467 dbesc(datetime_convert())
474 function diaspora_post($importer,$xml) {
477 $guid = notags(unxmlify($xml->guid));
478 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
480 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
484 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
485 logger('diaspora_post: Ignoring this author.');
489 $message_id = $diaspora_handle . ':' . $guid;
490 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
491 intval($importer['uid']),
496 logger('diaspora_post: message exists: ' . $guid);
500 // allocate a guid on our system - we aren't fixing any collisions.
501 // we're ignoring them
503 $g = q("select * from guid where guid = '%s' limit 1",
507 q("insert into guid ( guid ) values ( '%s' )",
512 $created = unxmlify($xml->created_at);
513 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
515 $body = diaspora2bb($xml->raw_message);
518 $datarray['uid'] = $importer['uid'];
519 $datarray['contact-id'] = $contact['id'];
520 $datarray['wall'] = 0;
521 $datarray['guid'] = $guid;
522 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
523 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
524 $datarray['private'] = $private;
525 $datarray['parent'] = 0;
526 $datarray['owner-name'] = $contact['name'];
527 $datarray['owner-link'] = $contact['url'];
528 $datarray['owner-avatar'] = $contact['thumb'];
529 $datarray['author-name'] = $contact['name'];
530 $datarray['author-link'] = $contact['url'];
531 $datarray['author-avatar'] = $contact['thumb'];
532 $datarray['body'] = $body;
533 $datarray['app'] = 'Diaspora';
535 $message_id = item_store($datarray);
538 q("update item set plink = '%s' where id = %d limit 1",
539 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
548 function diaspora_comment($importer,$xml,$msg) {
551 $guid = notags(unxmlify($xml->guid));
552 $parent_guid = notags(unxmlify($xml->parent_guid));
553 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
554 $target_type = notags(unxmlify($xml->target_type));
555 $text = unxmlify($xml->text);
556 $author_signature = notags(unxmlify($xml->author_signature));
558 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
562 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
564 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
568 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
569 logger('diaspora_comment: Ignoring this author.');
573 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
574 intval($importer['uid']),
578 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
582 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
583 intval($importer['uid']),
587 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
590 $parent_item = $r[0];
592 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
594 $author_signature = base64_decode($author_signature);
596 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
601 $person = find_diaspora_person_by_handle($diaspora_handle);
603 if(is_array($person) && x($person,'pubkey'))
604 $key = $person['pubkey'];
606 logger('diaspora_comment: unable to find author details');
611 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
612 logger('diaspora_comment: verification failed.');
617 if($parent_author_signature) {
618 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
620 $parent_author_signature = base64_decode($parent_author_signature);
624 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
625 logger('diaspora_comment: owner verification failed.');
630 // Phew! Everything checks out. Now create an item.
632 $body = diaspora2bb($text);
634 $message_id = $diaspora_handle . ':' . $guid;
637 $datarray['uid'] = $importer['uid'];
638 $datarray['contact-id'] = $contact['id'];
639 $datarray['wall'] = $parent_item['wall'];
640 $datarray['gravity'] = GRAVITY_COMMENT;
641 $datarray['guid'] = $guid;
642 $datarray['uri'] = $message_id;
643 $datarray['parent-uri'] = $parent_item['uri'];
645 // No timestamps for comments? OK, we'll the use current time.
646 $datarray['created'] = $datarray['edited'] = datetime_convert();
647 $datarray['private'] = $parent_item['private'];
649 $datarray['owner-name'] = $contact['name'];
650 $datarray['owner-link'] = $contact['url'];
651 $datarray['owner-avatar'] = $contact['thumb'];
653 $datarray['author-name'] = $person['name'];
654 $datarray['author-link'] = $person['url'];
655 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
656 $datarray['body'] = $body;
657 $datarray['app'] = 'Diaspora';
659 $message_id = item_store($datarray);
662 q("update item set plink = '%s' where id = %d limit 1",
663 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
668 if(! $parent_author_signature) {
669 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
671 dbesc($author_signed_data),
672 dbesc(base64_encode($author_signature)),
673 dbesc($diaspora_handle)
676 // if the message isn't already being relayed, notify others
677 // the existence of parent_author_signature means the parent_author or owner
678 // is already relaying.
680 proc_run('php','include/notifier.php','comment',$message_id);
685 function diaspora_photo($importer,$xml,$msg) {
688 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
690 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
692 $status_message_guid = notags(unxmlify($xml->status_message_guid));
694 $guid = notags(unxmlify($xml->guid));
696 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
698 $public = notags(unxmlify($xml->public));
700 $created_at = notags(unxmlify($xml_created_at));
703 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
707 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
708 logger('diaspora_photo: Ignoring this author.');
712 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
713 intval($importer['uid']),
714 dbesc($status_message_guid)
717 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
720 $parent_item = $r[0];
722 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
724 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
725 dbesc($link_text . $parent_item['body']),
726 intval($parent_item['id']),
727 intval($parent_item['uid'])
736 function diaspora_like($importer,$xml,$msg) {
739 $guid = notags(unxmlify($xml->guid));
740 $parent_guid = notags(unxmlify($xml->parent_guid));
741 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
742 $target_type = notags(unxmlify($xml->target_type));
743 $positive = notags(unxmlify($xml->positive));
744 $author_signature = notags(unxmlify($xml->author_signature));
746 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
748 // likes on comments not supported here and likes on photos not supported by Diaspora
750 if($target_type !== 'Post')
753 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
755 logger('diaspora_like: cannot find contact: ' . $msg['author']);
759 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
760 logger('diaspora_like: Ignoring this author.');
764 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
765 intval($importer['uid']),
769 logger('diaspora_like: parent item not found: ' . $guid);
773 $parent_item = $r[0];
775 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
776 intval($importer['uid']),
780 if($positive === 'true') {
781 logger('diaspora_like: duplicate like: ' . $guid);
784 if($positive === 'false') {
785 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
787 intval($importer['uid'])
790 // send notification via proc_run()
794 if($positive === 'false') {
795 logger('diaspora_like: unlike received with no corresponding like');
799 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
801 $author_signature = base64_decode($author_signature);
803 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
808 $person = find_diaspora_person_by_handle($diaspora_handle);
809 if(is_array($person) && x($person,'pubkey'))
810 $key = $person['pubkey'];
812 logger('diaspora_like: unable to find author details');
817 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
818 logger('diaspora_like: verification failed.');
822 if($parent_author_signature) {
824 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
826 $parent_author_signature = base64_decode($parent_author_signature);
830 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
831 logger('diaspora_like: owner verification failed.');
836 // Phew! Everything checks out. Now create an item.
838 $uri = $diaspora_handle . ':' . $guid;
840 $activity = ACTIVITY_LIKE;
841 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
842 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
843 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
844 $body = $parent_item['body'];
849 <type>$objtype</type>
851 <id>{$parent_item['uri']}</id>
854 <content>$body</content>
857 $bodyverb = t('%1$s likes %2$s\'s %3$s');
862 $arr['uid'] = $importer['uid'];
863 $arr['guid'] = $guid;
864 $arr['contact-id'] = $contact['id'];
865 $arr['type'] = 'activity';
866 $arr['wall'] = $parent_item['wall'];
867 $arr['gravity'] = GRAVITY_LIKE;
868 $arr['parent'] = $parent_item['id'];
869 $arr['parent-uri'] = $parent_item['uri'];
871 $arr['owner-name'] = $contact['name'];
872 $arr['owner-link'] = $contact['url'];
873 $arr['owner-avatar'] = $contact['thumb'];
875 $arr['author-name'] = $person['name'];
876 $arr['author-link'] = $person['url'];
877 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
879 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
880 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
881 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
882 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
884 $arr['app'] = 'Diaspora';
886 $arr['private'] = $parent_item['private'];
887 $arr['verb'] = $activity;
888 $arr['object-type'] = $objtype;
889 $arr['object'] = $obj;
892 $arr['last-child'] = 0;
894 $message_id = item_store($arr);
898 q("update item set plink = '%s' where id = %d limit 1",
899 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
904 if(! $parent_author_signature) {
905 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
907 dbesc($author_signed_data),
908 dbesc(base64_encode($author_signature)),
909 dbesc($diaspora_handle)
913 // if the message isn't already being relayed, notify others
914 // the existence of parent_author_signature means the parent_author or owner
915 // is already relaying.
917 if(! $parent_author_signature)
918 proc_run('php','include/notifier.php','comment',$message_id);
923 function diaspora_retraction($importer,$xml) {
925 $guid = notags(unxmlify($xml->guid));
926 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
927 $type = notags(unxmlify($xml->type));
929 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
933 if($type === 'Person') {
934 contact_remove($contact['id']);
936 elseif($type === 'Post') {
937 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
939 intval($importer['uid'])
942 if(link_compare($r[0]['author-link'],$contact['url'])) {
943 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
944 dbesc(datetime_convert()),
955 function diaspora_share($me,$contact) {
957 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
958 $theiraddr = $contact['addr'];
960 $tpl = get_markup_template('diaspora_share.tpl');
961 $msg = replace_macros($tpl, array(
962 '$sender' => $myaddr,
963 '$recipient' => $theiraddr
966 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
968 return(diaspora_transmit($owner,$contact,$slap));
971 function diaspora_unshare($me,$contact) {
974 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
976 $tpl = get_markup_template('diaspora_retract.tpl');
977 $msg = replace_macros($tpl, array(
978 '$guid' => $me['guid'],
983 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
985 return(diaspora_transmit($owner,$contact,$slap));
991 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
994 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
995 $theiraddr = $contact['addr'];
999 $body = $item['body'];
1001 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1003 foreach($matches as $mtch) {
1005 $detail['str'] = $mtch[0];
1006 $detail['path'] = dirname($mtch[1]) . '/';
1007 $detail['file'] = basename($mtch[1]);
1008 $detail['guid'] = $item['guid'];
1009 $detail['handle'] = $myaddr;
1010 $images[] = $detail;
1011 $body = str_replace($detail['str'],t('link'),$body);
1015 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1017 $public = (($item['private']) ? 'false' : 'true');
1019 require_once('include/datetime.php');
1020 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1022 $tpl = get_markup_template('diaspora_post.tpl');
1023 $msg = replace_macros($tpl, array(
1025 '$guid' => $item['guid'],
1026 '$handle' => xmlify($myaddr),
1027 '$public' => $public,
1028 '$created' => $created
1031 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1033 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1035 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1037 if(count($images)) {
1038 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1041 return $return_code;
1045 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1047 if(! count($images))
1049 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1051 $tpl = get_markup_template('diaspora_photo.tpl');
1052 foreach($images as $image) {
1053 if(! stristr($image['path'],$mysite))
1055 $resource = str_replace('.jpg','',$image['file']);
1056 $resource = substr($resource,0,strpos($resource,'-'));
1058 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1060 intval($owner['uid'])
1064 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1065 $msg = replace_macros($tpl,array(
1066 '$path' => xmlify($image['path']),
1067 '$filename' => xmlify($image['file']),
1068 '$msg_guid' => xmlify($image['guid']),
1069 '$guid' => xmlify($r[0]['guid']),
1070 '$handle' => xmlify($image['handle']),
1071 '$public' => xmlify($public),
1072 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1076 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1077 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1079 diaspora_transmit($owner,$contact,$slap,$public_batch);
1084 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1087 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1088 $theiraddr = $contact['addr'];
1090 $p = q("select guid from item where parent = %d limit 1",
1094 $parent_guid = $p[0]['guid'];
1098 if($item['verb'] === ACTIVITY_LIKE) {
1099 $tpl = get_markup_template('diaspora_like.tpl');
1101 $target_type = 'Post';
1102 $positive = (($item['deleted']) ? 'false' : 'true');
1105 $tpl = get_markup_template('diaspora_comment.tpl');
1109 $text = html_entity_decode(bb2diaspora($item['body']));
1114 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1116 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1118 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1120 $msg = replace_macros($tpl,array(
1121 '$guid' => xmlify($item['guid']),
1122 '$parent_guid' => xmlify($parent_guid),
1123 '$target_type' =>xmlify($target_type),
1124 '$authorsig' => xmlify($authorsig),
1125 '$body' => xmlify($text),
1126 '$positive' => xmlify($positive),
1127 '$handle' => xmlify($myaddr)
1130 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1132 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1134 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1138 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1142 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1143 $theiraddr = $contact['addr'];
1146 $p = q("select guid from item where parent = %d limit 1",
1150 $parent_guid = $p[0]['guid'];
1154 if($item['verb'] === ACTIVITY_LIKE) {
1155 $tpl = get_markup_template('diaspora_like_relay.tpl');
1157 $target_type = 'Post';
1158 $positive = (($item['deleted']) ? 'false' : 'true');
1161 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1165 $body = $item['body'];
1167 $text = html_entity_decode(bb2diaspora($body));
1169 // fetch the original signature if somebody sent the post to us to relay
1170 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1171 // action. It wasn't needed. In that case create the original signature and the
1172 // owner (parent author) signature
1173 // comments from other networks will be relayed under our name, with a brief
1174 // preamble to describe what's happening and noting the real author
1176 $r = q("select * from sign where iid = %d limit 1",
1181 $signed_text = $orig_sign['signed_text'];
1182 $authorsig = $orig_sign['signature'];
1183 $handle = $orig_sign['signer'];
1187 $itemcontact = q("select * from contact where `id` = %d limit 1",
1188 intval($item['contact-id'])
1190 if(count($itemcontact)) {
1191 if(! $itemcontact[0]['self']) {
1192 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1193 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1194 network_to_name($itemcontact['network'])) . "\n";
1195 $body = $prefix . $body;
1201 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1203 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1205 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1207 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1208 intval($item['id']),
1209 dbesc($signed_text),
1210 dbesc(base64_encode($authorsig)),
1219 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1221 $msg = replace_macros($tpl,array(
1222 '$guid' => xmlify($item['guid']),
1223 '$parent_guid' => xmlify($parent_guid),
1224 '$target_type' =>xmlify($target_type),
1225 '$authorsig' => xmlify($orig_sign['signature']),
1226 '$parentsig' => xmlify($parentauthorsig),
1227 '$body' => xmlify($text),
1228 '$positive' => xmlify($positive),
1229 '$handle' => xmlify($handle)
1232 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1234 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1236 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1242 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1245 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1247 $tpl = get_markup_template('diaspora_retract.tpl');
1248 $msg = replace_macros($tpl, array(
1249 '$guid' => $item['guid'],
1251 '$handle' => $myaddr
1254 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1256 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1261 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1264 $logid = random_string(4);
1265 logger('diaspora_transmit: ' . $logid . ' ' . (($public_batch) ? $contact['batch'] : $contact['notify']));
1266 post_url((($public_batch) ? $contact['batch'] : $contact['notify']) . '/',$slap);
1267 $return_code = $a->get_curl_code();
1268 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1270 if((! $return_code) || (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1271 logger('diaspora_transmit: queue message');
1272 // queue message for redelivery
1273 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`,`batch`)
1274 VALUES ( %d, '%s', '%s', '%s', %d) ",
1275 intval($contact['id']),
1276 dbesc(datetime_convert()),
1277 dbesc(datetime_convert()),
1279 intval($public_batch)
1284 return(($return_code) ? $return_code : (-1));