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) {
584 logger('diaspora_asphoto called');
587 $guid = notags(unxmlify($xml->guid));
588 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
590 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
594 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
595 logger('diaspora_asphoto: Ignoring this author.');
599 $message_id = $diaspora_handle . ':' . $guid;
600 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
601 intval($importer['uid']),
606 logger('diaspora_asphoto: message exists: ' . $guid);
610 // allocate a guid on our system - we aren't fixing any collisions.
611 // we're ignoring them
613 $g = q("select * from guid where guid = '%s' limit 1",
617 q("insert into guid ( guid ) values ( '%s' )",
622 $created = unxmlify($xml->created_at);
623 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
625 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url))
626 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img=' . notags(unxmlify($xml->objectId)) . '][/img][/url]' . "\n";
627 elseif($xml->image_url)
628 $body = '[img=' . notags(unxmlify($xml->image_url)) . '][/img]' . "\n";
630 logger('diaspora_asphoto: no photo url found.');
638 $datarray['uid'] = $importer['uid'];
639 $datarray['contact-id'] = $contact['id'];
640 $datarray['wall'] = 0;
641 $datarray['guid'] = $guid;
642 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
643 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
644 $datarray['private'] = $private;
645 $datarray['parent'] = 0;
646 $datarray['owner-name'] = $contact['name'];
647 $datarray['owner-link'] = $contact['url'];
648 $datarray['owner-avatar'] = $contact['thumb'];
649 $datarray['author-name'] = $contact['name'];
650 $datarray['author-link'] = $contact['url'];
651 $datarray['author-avatar'] = $contact['thumb'];
652 $datarray['body'] = $body;
654 $datarray['app'] = 'Diaspora/Cubbi.es';
656 $message_id = item_store($datarray);
659 q("update item set plink = '%s' where id = %d limit 1",
660 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
674 function diaspora_comment($importer,$xml,$msg) {
677 $guid = notags(unxmlify($xml->guid));
678 $parent_guid = notags(unxmlify($xml->parent_guid));
679 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
680 $target_type = notags(unxmlify($xml->target_type));
681 $text = unxmlify($xml->text);
682 $author_signature = notags(unxmlify($xml->author_signature));
684 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
688 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
690 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
694 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
695 logger('diaspora_comment: Ignoring this author.');
699 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
700 intval($importer['uid']),
704 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
708 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
709 intval($importer['uid']),
713 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
716 $parent_item = $r[0];
718 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
720 $author_signature = base64_decode($author_signature);
722 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
727 $person = find_diaspora_person_by_handle($diaspora_handle);
729 if(is_array($person) && x($person,'pubkey'))
730 $key = $person['pubkey'];
732 logger('diaspora_comment: unable to find author details');
737 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
738 logger('diaspora_comment: verification failed.');
742 if($parent_author_signature) {
743 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
745 $parent_author_signature = base64_decode($parent_author_signature);
749 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
750 logger('diaspora_comment: owner verification failed.');
755 // Phew! Everything checks out. Now create an item.
757 $body = diaspora2bb($text);
759 $message_id = $diaspora_handle . ':' . $guid;
765 $tags = get_tags($body);
768 foreach($tags as $tag) {
769 if(strpos($tag,'#') === 0) {
770 if(strpos($tag,'[url='))
772 $basetag = str_replace('_',' ',substr($tag,1));
773 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
774 if(strlen($str_tags))
776 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
782 $datarray['uid'] = $importer['uid'];
783 $datarray['contact-id'] = $contact['id'];
784 $datarray['wall'] = $parent_item['wall'];
785 $datarray['gravity'] = GRAVITY_COMMENT;
786 $datarray['guid'] = $guid;
787 $datarray['uri'] = $message_id;
788 $datarray['parent-uri'] = $parent_item['uri'];
790 // No timestamps for comments? OK, we'll the use current time.
791 $datarray['created'] = $datarray['edited'] = datetime_convert();
792 $datarray['private'] = $parent_item['private'];
794 $datarray['owner-name'] = $parent_item['owner-name'];
795 $datarray['owner-link'] = $parent_item['owner-link'];
796 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
798 $datarray['author-name'] = $person['name'];
799 $datarray['author-link'] = $person['url'];
800 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
801 $datarray['body'] = $body;
802 $datarray['tag'] = $str_tags;
803 $datarray['app'] = 'Diaspora';
805 $message_id = item_store($datarray);
808 q("update item set plink = '%s' where id = %d limit 1",
809 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
814 if(! $parent_author_signature) {
815 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
817 dbesc($author_signed_data),
818 dbesc(base64_encode($author_signature)),
819 dbesc($diaspora_handle)
822 // if the message isn't already being relayed, notify others
823 // the existence of parent_author_signature means the parent_author or owner
824 // is already relaying.
826 proc_run('php','include/notifier.php','comment',$message_id);
831 function diaspora_photo($importer,$xml,$msg) {
834 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
836 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
838 $status_message_guid = notags(unxmlify($xml->status_message_guid));
840 $guid = notags(unxmlify($xml->guid));
842 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
844 $public = notags(unxmlify($xml->public));
846 $created_at = notags(unxmlify($xml_created_at));
849 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
853 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
854 logger('diaspora_photo: Ignoring this author.');
858 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
859 intval($importer['uid']),
860 dbesc($status_message_guid)
863 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
866 $parent_item = $r[0];
868 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
870 if(strpos($parent_item['body'],$link_text) === false) {
871 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
872 dbesc($link_text . $parent_item['body']),
873 intval($parent_item['id']),
874 intval($parent_item['uid'])
884 function diaspora_like($importer,$xml,$msg) {
887 $guid = notags(unxmlify($xml->guid));
888 $parent_guid = notags(unxmlify($xml->parent_guid));
889 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
890 $target_type = notags(unxmlify($xml->target_type));
891 $positive = notags(unxmlify($xml->positive));
892 $author_signature = notags(unxmlify($xml->author_signature));
894 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
896 // likes on comments not supported here and likes on photos not supported by Diaspora
898 if($target_type !== 'Post')
901 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
903 logger('diaspora_like: cannot find contact: ' . $msg['author']);
907 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
908 logger('diaspora_like: Ignoring this author.');
912 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
913 intval($importer['uid']),
917 logger('diaspora_like: parent item not found: ' . $guid);
921 $parent_item = $r[0];
923 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
924 intval($importer['uid']),
928 if($positive === 'true') {
929 logger('diaspora_like: duplicate like: ' . $guid);
932 if($positive === 'false') {
933 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
935 intval($importer['uid'])
938 // send notification via proc_run()
942 if($positive === 'false') {
943 logger('diaspora_like: unlike received with no corresponding like');
947 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
949 $author_signature = base64_decode($author_signature);
951 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
956 $person = find_diaspora_person_by_handle($diaspora_handle);
957 if(is_array($person) && x($person,'pubkey'))
958 $key = $person['pubkey'];
960 logger('diaspora_like: unable to find author details');
965 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
966 logger('diaspora_like: verification failed.');
970 if($parent_author_signature) {
972 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
974 $parent_author_signature = base64_decode($parent_author_signature);
978 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
979 logger('diaspora_like: owner verification failed.');
984 // Phew! Everything checks out. Now create an item.
986 $uri = $diaspora_handle . ':' . $guid;
988 $activity = ACTIVITY_LIKE;
989 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
990 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
991 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
992 $body = $parent_item['body'];
997 <type>$objtype</type>
999 <id>{$parent_item['uri']}</id>
1002 <content>$body</content>
1005 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1010 $arr['uid'] = $importer['uid'];
1011 $arr['guid'] = $guid;
1012 $arr['contact-id'] = $contact['id'];
1013 $arr['type'] = 'activity';
1014 $arr['wall'] = $parent_item['wall'];
1015 $arr['gravity'] = GRAVITY_LIKE;
1016 $arr['parent'] = $parent_item['id'];
1017 $arr['parent-uri'] = $parent_item['uri'];
1019 $arr['owner-name'] = $contact['name'];
1020 $arr['owner-link'] = $contact['url'];
1021 $arr['owner-avatar'] = $contact['thumb'];
1023 $arr['author-name'] = $person['name'];
1024 $arr['author-link'] = $person['url'];
1025 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1027 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1028 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1029 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1030 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1032 $arr['app'] = 'Diaspora';
1034 $arr['private'] = $parent_item['private'];
1035 $arr['verb'] = $activity;
1036 $arr['object-type'] = $objtype;
1037 $arr['object'] = $obj;
1038 $arr['visible'] = 1;
1040 $arr['last-child'] = 0;
1042 $message_id = item_store($arr);
1046 q("update item set plink = '%s' where id = %d limit 1",
1047 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1052 if(! $parent_author_signature) {
1053 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1054 intval($message_id),
1055 dbesc($author_signed_data),
1056 dbesc(base64_encode($author_signature)),
1057 dbesc($diaspora_handle)
1061 // if the message isn't already being relayed, notify others
1062 // the existence of parent_author_signature means the parent_author or owner
1063 // is already relaying.
1065 if(! $parent_author_signature)
1066 proc_run('php','include/notifier.php','comment',$message_id);
1071 function diaspora_retraction($importer,$xml) {
1073 $guid = notags(unxmlify($xml->guid));
1074 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1075 $type = notags(unxmlify($xml->type));
1077 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1081 if($type === 'Person') {
1082 contact_remove($contact['id']);
1084 elseif($type === 'Post') {
1085 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1087 intval($importer['uid'])
1090 if(link_compare($r[0]['author-link'],$contact['url'])) {
1091 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1092 dbesc(datetime_convert()),
1103 function diaspora_profile($importer,$xml) {
1106 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1108 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1112 if($contact['blocked']) {
1113 logger('diaspora_post: Ignoring this author.');
1117 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1118 $image_url = unxmlify($xml->image_url);
1119 $birthday = unxmlify($xml->birthday);
1121 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1122 intval($importer['uid']),
1123 intval($contact['id'])
1125 $oldphotos = ((count($r)) ? $r : null);
1127 require_once('include/Photo.php');
1129 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1131 // Generic birthday. We don't know the timezone. The year is irrelevant.
1133 $birthday = str_replace('1000','1901',$birthday);
1135 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1137 $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",
1139 dbesc(datetime_convert()),
1143 dbesc(datetime_convert()),
1145 intval($contact['id']),
1146 intval($importer['uid'])
1151 foreach($oldphotos as $ph) {
1152 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1153 intval($importer['uid']),
1154 intval($contact['id']),
1155 dbesc($ph['resource-id'])
1186 function diaspora_share($me,$contact) {
1188 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1189 $theiraddr = $contact['addr'];
1191 $tpl = get_markup_template('diaspora_share.tpl');
1192 $msg = replace_macros($tpl, array(
1193 '$sender' => $myaddr,
1194 '$recipient' => $theiraddr
1197 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1199 return(diaspora_transmit($owner,$contact,$slap, false));
1202 function diaspora_unshare($me,$contact) {
1205 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1207 $tpl = get_markup_template('diaspora_retract.tpl');
1208 $msg = replace_macros($tpl, array(
1209 '$guid' => $me['guid'],
1210 '$type' => 'Person',
1211 '$handle' => $myaddr
1214 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1216 return(diaspora_transmit($owner,$contact,$slap, false));
1222 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1225 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1226 $theiraddr = $contact['addr'];
1230 $body = $item['body'];
1232 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1234 foreach($matches as $mtch) {
1236 $detail['str'] = $mtch[0];
1237 $detail['path'] = dirname($mtch[1]) . '/';
1238 $detail['file'] = basename($mtch[1]);
1239 $detail['guid'] = $item['guid'];
1240 $detail['handle'] = $myaddr;
1241 $images[] = $detail;
1242 $body = str_replace($detail['str'],t('link'),$body);
1246 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1248 $public = (($item['private']) ? 'false' : 'true');
1250 require_once('include/datetime.php');
1251 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1253 $tpl = get_markup_template('diaspora_post.tpl');
1254 $msg = replace_macros($tpl, array(
1256 '$guid' => $item['guid'],
1257 '$handle' => xmlify($myaddr),
1258 '$public' => $public,
1259 '$created' => $created
1262 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1264 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1266 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1268 if(count($images)) {
1269 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1272 return $return_code;
1276 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1278 if(! count($images))
1280 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1282 $tpl = get_markup_template('diaspora_photo.tpl');
1283 foreach($images as $image) {
1284 if(! stristr($image['path'],$mysite))
1286 $resource = str_replace('.jpg','',$image['file']);
1287 $resource = substr($resource,0,strpos($resource,'-'));
1289 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1291 intval($owner['uid'])
1295 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1296 $msg = replace_macros($tpl,array(
1297 '$path' => xmlify($image['path']),
1298 '$filename' => xmlify($image['file']),
1299 '$msg_guid' => xmlify($image['guid']),
1300 '$guid' => xmlify($r[0]['guid']),
1301 '$handle' => xmlify($image['handle']),
1302 '$public' => xmlify($public),
1303 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1307 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1308 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1310 diaspora_transmit($owner,$contact,$slap,$public_batch);
1315 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1318 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1319 $theiraddr = $contact['addr'];
1321 $p = q("select guid from item where parent = %d limit 1",
1325 $parent_guid = $p[0]['guid'];
1329 if($item['verb'] === ACTIVITY_LIKE) {
1330 $tpl = get_markup_template('diaspora_like.tpl');
1332 $target_type = 'Post';
1333 $positive = (($item['deleted']) ? 'false' : 'true');
1336 $tpl = get_markup_template('diaspora_comment.tpl');
1340 $text = html_entity_decode(bb2diaspora($item['body']));
1345 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1347 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1349 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1351 $msg = replace_macros($tpl,array(
1352 '$guid' => xmlify($item['guid']),
1353 '$parent_guid' => xmlify($parent_guid),
1354 '$target_type' =>xmlify($target_type),
1355 '$authorsig' => xmlify($authorsig),
1356 '$body' => xmlify($text),
1357 '$positive' => xmlify($positive),
1358 '$handle' => xmlify($myaddr)
1361 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1363 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1365 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1369 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1373 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1374 $theiraddr = $contact['addr'];
1377 $p = q("select guid from item where parent = %d limit 1",
1381 $parent_guid = $p[0]['guid'];
1385 if($item['verb'] === ACTIVITY_LIKE) {
1386 $tpl = get_markup_template('diaspora_like_relay.tpl');
1388 $target_type = 'Post';
1389 $positive = (($item['deleted']) ? 'false' : 'true');
1392 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1396 $body = $item['body'];
1398 $text = html_entity_decode(bb2diaspora($body));
1400 // fetch the original signature if somebody sent the post to us to relay
1401 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1402 // action. It wasn't needed. In that case create the original signature and the
1403 // owner (parent author) signature
1404 // comments from other networks will be relayed under our name, with a brief
1405 // preamble to describe what's happening and noting the real author
1407 $r = q("select * from sign where iid = %d limit 1",
1412 $signed_text = $orig_sign['signed_text'];
1413 $authorsig = $orig_sign['signature'];
1414 $handle = $orig_sign['signer'];
1418 $itemcontact = q("select * from contact where `id` = %d limit 1",
1419 intval($item['contact-id'])
1421 if(count($itemcontact)) {
1422 if(! $itemcontact[0]['self']) {
1423 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1424 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1425 network_to_name($itemcontact['network'])) . "\n";
1426 $body = $prefix . $body;
1432 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1434 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1436 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1438 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1439 intval($item['id']),
1440 dbesc($signed_text),
1441 dbesc(base64_encode($authorsig)),
1450 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1452 $msg = replace_macros($tpl,array(
1453 '$guid' => xmlify($item['guid']),
1454 '$parent_guid' => xmlify($parent_guid),
1455 '$target_type' =>xmlify($target_type),
1456 '$authorsig' => xmlify($orig_sign['signature']),
1457 '$parentsig' => xmlify($parentauthorsig),
1458 '$body' => xmlify($text),
1459 '$positive' => xmlify($positive),
1460 '$handle' => xmlify($handle)
1463 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1465 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1467 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1473 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1476 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1478 $tpl = get_markup_template('diaspora_retract.tpl');
1479 $msg = replace_macros($tpl, array(
1480 '$guid' => $item['guid'],
1482 '$handle' => $myaddr
1485 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1487 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1492 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1495 $logid = random_string(4);
1496 logger('diaspora_transmit: ' . $logid . ' ' . (($public_batch) ? $contact['batch'] : $contact['notify']));
1497 post_url((($public_batch) ? $contact['batch'] : $contact['notify']) . '/',$slap);
1498 $return_code = $a->get_curl_code();
1499 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1501 if((! $return_code) || (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1502 logger('diaspora_transmit: queue message');
1503 // queue message for redelivery
1504 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`,`batch`)
1505 VALUES ( %d, '%s', '%s', '%s', %d) ",
1506 intval($contact['id']),
1507 dbesc(datetime_convert()),
1508 dbesc(datetime_convert()),
1510 intval($public_batch)
1515 return(($return_code) ? $return_code : (-1));