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');
7 require_once('include/queue_fn.php');
10 function diaspora_dispatch_public($msg) {
12 $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 ",
13 dbesc(NETWORK_DIASPORA),
18 logger('diaspora_public: delivering to: ' . $rr['username']);
19 diaspora_dispatch($rr,$msg);
23 logger('diaspora_public: no subscribers');
28 function diaspora_dispatch($importer,$msg) {
32 // php doesn't like dashes in variable names
34 $msg['message'] = str_replace(
35 array('<activity_streams-photo>','</activity_streams-photo>'),
36 array('<asphoto>','</asphoto>'),
40 $parsed_xml = parse_xml_string($msg['message'],false);
42 $xmlbase = $parsed_xml->post;
44 if($xmlbase->request) {
45 $ret = diaspora_request($importer,$xmlbase->request);
47 elseif($xmlbase->status_message) {
48 $ret = diaspora_post($importer,$xmlbase->status_message);
50 elseif($xmlbase->profile) {
51 $ret = diaspora_profile($importer,$xmlbase->profile);
53 elseif($xmlbase->comment) {
54 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
56 elseif($xmlbase->like) {
57 $ret = diaspora_like($importer,$xmlbase->like,$msg);
59 elseif($xmlbase->asphoto) {
60 $ret = diaspora_asphoto($importer,$xmlbase->asphoto);
62 elseif($xmlbase->reshare) {
63 $ret = diaspora_reshare($importer,$xmlbase->reshare);
65 elseif($xmlbase->retraction) {
66 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
68 elseif($xmlbase->signed_retraction) {
69 $ret = diaspora_signed_retraction($importer,$xmlbase->retraction,$msg);
71 elseif($xmlbase->photo) {
72 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
75 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
80 function diaspora_get_contact_by_handle($uid,$handle) {
81 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
82 dbesc(NETWORK_DIASPORA),
91 function find_diaspora_person_by_handle($handle) {
93 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
94 dbesc(NETWORK_DIASPORA),
98 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
99 // update record occasionally so it doesn't get stale
100 $d = strtotime($r[0]['updated'] . ' +00:00');
101 if($d > strtotime('now - 14 days'))
105 logger('find_diaspora_person_by_handle: refresh',LOGGER_DEBUG);
106 require_once('include/Scrape.php');
107 $r = probe_url($handle, PROBE_DIASPORA);
108 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
109 add_fcontact($r,$update);
116 function get_diaspora_key($uri) {
117 logger('Fetching diaspora key for: ' . $uri);
119 $r = find_diaspora_person_by_handle($uri);
126 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
129 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
132 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
134 // $b64_data = base64_encode($msg);
135 // $b64url_data = base64url_encode($b64_data);
137 $b64url_data = base64url_encode($msg);
139 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
141 $type = 'application/xml';
142 $encoding = 'base64url';
145 $signable_data = $data . '.' . base64url_encode($type) . '.'
146 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
148 $signature = rsa_sign($signable_data,$prvkey);
149 $sig = base64url_encode($signature);
152 <?xml version='1.0' encoding='UTF-8'?>
153 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
155 <author_id>$handle</author_id>
158 <me:encoding>base64url</me:encoding>
159 <me:alg>RSA-SHA256</me:alg>
160 <me:data type="application/xml">$data</me:data>
161 <me:sig>$sig</me:sig>
166 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
174 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
178 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
180 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
182 $inner_aes_key = random_string(32);
183 $b_inner_aes_key = base64_encode($inner_aes_key);
184 $inner_iv = random_string(16);
185 $b_inner_iv = base64_encode($inner_iv);
187 $outer_aes_key = random_string(32);
188 $b_outer_aes_key = base64_encode($outer_aes_key);
189 $outer_iv = random_string(16);
190 $b_outer_iv = base64_encode($outer_iv);
192 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
194 $padded_data = pkcs5_pad($msg,16);
195 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
197 $b64_data = base64_encode($inner_encrypted);
200 $b64url_data = base64url_encode($b64_data);
201 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
203 $type = 'application/xml';
204 $encoding = 'base64url';
207 $signable_data = $data . '.' . base64url_encode($type) . '.'
208 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
210 $signature = rsa_sign($signable_data,$prvkey);
211 $sig = base64url_encode($signature);
213 $decrypted_header = <<< EOT
216 <aes_key>$b_inner_aes_key</aes_key>
217 <author_id>$handle</author_id>
221 $decrypted_header = pkcs5_pad($decrypted_header,16);
223 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
225 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
227 $encrypted_outer_key_bundle = '';
228 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
230 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
232 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
234 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
235 'ciphertext' => base64_encode($ciphertext)));
236 $cipher_json = base64_encode($encrypted_header_json_object);
238 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
241 <?xml version='1.0' encoding='UTF-8'?>
242 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
245 <me:encoding>base64url</me:encoding>
246 <me:alg>RSA-SHA256</me:alg>
247 <me:data type="application/xml">$data</me:data>
248 <me:sig>$sig</me:sig>
253 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
260 * diaspora_decode($importer,$xml)
261 * array $importer -> from user table
262 * string $xml -> urldecoded Diaspora salmon
265 * 'message' -> decoded Diaspora XML message
266 * 'author' -> author diaspora handle
267 * 'key' -> author public key (converted to pkcs#8)
269 * Author and key are used elsewhere to save a lookup for verifying replies and likes
273 function diaspora_decode($importer,$xml) {
276 $basedom = parse_xml_string($xml);
278 $children = $basedom->children('https://joindiaspora.com/protocol');
280 if($children->header) {
282 $author_link = str_replace('acct:','',$children->header->author_id);
286 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
288 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
289 $ciphertext = base64_decode($encrypted_header->ciphertext);
291 $outer_key_bundle = '';
292 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
294 $j_outer_key_bundle = json_decode($outer_key_bundle);
296 $outer_iv = base64_decode($j_outer_key_bundle->iv);
297 $outer_key = base64_decode($j_outer_key_bundle->key);
299 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
302 $decrypted = pkcs5_unpad($decrypted);
305 * $decrypted now contains something like
308 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
309 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
314 * <name>Ryan Hughes</name>
315 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
320 * <author_id>galaxor@diaspora.priateship.org</author_id>
324 * </decrypted_header>
327 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
328 $idom = parse_xml_string($decrypted,false);
330 $inner_iv = base64_decode($idom->iv);
331 $inner_aes_key = base64_decode($idom->aes_key);
333 $author_link = str_replace('acct:','',$idom->author_id);
337 $dom = $basedom->children(NAMESPACE_SALMON_ME);
339 // figure out where in the DOM tree our data is hiding
341 if($dom->provenance->data)
342 $base = $dom->provenance;
343 elseif($dom->env->data)
349 logger('mod-diaspora: unable to locate salmon data in xml ');
350 http_status_exit(400);
354 // Stash the signature away for now. We have to find their key or it won't be good for anything.
355 $signature = base64url_decode($base->sig);
359 // strip whitespace so our data element will return to one big base64 blob
360 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
363 // stash away some other stuff for later
365 $type = $base->data[0]->attributes()->type[0];
366 $keyhash = $base->sig[0]->attributes()->keyhash[0];
367 $encoding = $base->encoding;
371 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
375 $data = base64url_decode($data);
379 $inner_decrypted = $data;
383 // Decode the encrypted blob
385 $inner_encrypted = base64_decode($data);
386 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
387 $inner_decrypted = pkcs5_unpad($inner_decrypted);
391 logger('mod-diaspora: Could not retrieve author URI.');
392 http_status_exit(400);
395 // Once we have the author URI, go to the web and try to find their public key
396 // (first this will look it up locally if it is in the fcontact cache)
397 // This will also convert diaspora public key from pkcs#1 to pkcs#8
399 logger('mod-diaspora: Fetching key for ' . $author_link );
400 $key = get_diaspora_key($author_link);
403 logger('mod-diaspora: Could not retrieve author key.');
404 http_status_exit(400);
407 $verify = rsa_verify($signed_data,$signature,$key);
410 logger('mod-diaspora: Message did not verify. Discarding.');
411 http_status_exit(400);
414 logger('mod-diaspora: Message verified.');
416 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
421 function diaspora_request($importer,$xml) {
423 $sender_handle = unxmlify($xml->sender_handle);
424 $recipient_handle = unxmlify($xml->recipient_handle);
426 if(! $sender_handle || ! $recipient_handle)
429 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
433 // perhaps we were already sharing with this person. Now they're sharing with us.
434 // That makes us friends.
436 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
437 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
438 intval(CONTACT_IS_FRIEND),
439 intval($contact['id']),
440 intval($importer['uid'])
443 // send notification?
447 $ret = find_diaspora_person_by_handle($sender_handle);
450 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
451 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
455 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
457 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
458 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
459 intval($importer['uid']),
460 dbesc($ret['network']),
464 dbesc(normalise_link($ret['url'])),
468 dbesc($ret['photo']),
469 dbesc($ret['pubkey']),
470 dbesc($ret['notify']),
476 // find the contact record we just created
478 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
480 $hash = random_string() . (string) time(); // Generate a confirm_key
482 if($contact_record) {
483 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
484 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
485 intval($importer['uid']),
486 intval($contact_record['id']),
489 dbesc( t('Sharing notification from Diaspora network')),
491 dbesc(datetime_convert())
498 function diaspora_post($importer,$xml) {
501 $guid = notags(unxmlify($xml->guid));
502 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
504 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
508 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
509 logger('diaspora_post: Ignoring this author.');
513 $message_id = $diaspora_handle . ':' . $guid;
514 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
515 intval($importer['uid']),
520 logger('diaspora_post: message exists: ' . $guid);
524 // allocate a guid on our system - we aren't fixing any collisions.
525 // we're ignoring them
527 $g = q("select * from guid where guid = '%s' limit 1",
531 q("insert into guid ( guid ) values ( '%s' )",
536 $created = unxmlify($xml->created_at);
537 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
539 $body = diaspora2bb($xml->raw_message);
545 $tags = get_tags($body);
548 foreach($tags as $tag) {
549 if(strpos($tag,'#') === 0) {
550 if(strpos($tag,'[url='))
552 $basetag = str_replace('_',' ',substr($tag,1));
553 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
554 if(strlen($str_tags))
556 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
562 $datarray['uid'] = $importer['uid'];
563 $datarray['contact-id'] = $contact['id'];
564 $datarray['wall'] = 0;
565 $datarray['guid'] = $guid;
566 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
567 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
568 $datarray['private'] = $private;
569 $datarray['parent'] = 0;
570 $datarray['owner-name'] = $contact['name'];
571 $datarray['owner-link'] = $contact['url'];
572 $datarray['owner-avatar'] = $contact['thumb'];
573 $datarray['author-name'] = $contact['name'];
574 $datarray['author-link'] = $contact['url'];
575 $datarray['author-avatar'] = $contact['thumb'];
576 $datarray['body'] = $body;
577 $datarray['tag'] = $str_tags;
578 $datarray['app'] = 'Diaspora';
580 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
582 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
584 $message_id = item_store($datarray);
587 q("update item set plink = '%s' where id = %d limit 1",
588 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
597 function diaspora_reshare($importer,$xml) {
599 logger('diaspora_reshare: init: ' . print_r($xml,true));
602 $guid = notags(unxmlify($xml->guid));
603 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
606 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
610 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
611 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
615 $message_id = $diaspora_handle . ':' . $guid;
616 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
617 intval($importer['uid']),
622 logger('diaspora_reshare: message exists: ' . $guid);
626 $orig_author = notags(unxmlify($xml->root_diaspora_id));
627 $orig_guid = notags(unxmlify($xml->root_guid));
629 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
630 $x = fetch_url($source_url);
632 $x = fetch_url(str_replace('https://','http://',$source_url));
634 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
637 logger('diaspora_reshare: source: ' . $x);
639 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
640 $source_xml = parse_xml_string($x,false);
642 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
643 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
644 $body = scale_diaspora_images($body,false);
646 elseif($source_xml->post->asphoto->image_url) {
647 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
648 $body = scale_diaspora_images($body);
650 elseif($source_xml->post->status_message) {
651 $body = diaspora2bb($source_xml->post->status_message->raw_message);
652 $body = scale_diaspora_images($body);
656 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
660 logger('diaspora_reshare: empty body: source= ' . $x);
664 $person = find_diaspora_person_by_handle($orig_author);
666 if(is_array($person) && x($person,'name') && x($person,'url'))
667 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
669 $details = $orig_author;
671 $prefix = '♲ ' . $details . "\n";
674 // allocate a guid on our system - we aren't fixing any collisions.
675 // we're ignoring them
677 $g = q("select * from guid where guid = '%s' limit 1",
681 q("insert into guid ( guid ) values ( '%s' )",
686 $created = unxmlify($xml->created_at);
687 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
693 $tags = get_tags($body);
696 foreach($tags as $tag) {
697 if(strpos($tag,'#') === 0) {
698 if(strpos($tag,'[url='))
700 $basetag = str_replace('_',' ',substr($tag,1));
701 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
702 if(strlen($str_tags))
704 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
710 $datarray['uid'] = $importer['uid'];
711 $datarray['contact-id'] = $contact['id'];
712 $datarray['wall'] = 0;
713 $datarray['guid'] = $guid;
714 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
715 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
716 $datarray['private'] = $private;
717 $datarray['parent'] = 0;
718 $datarray['owner-name'] = $contact['name'];
719 $datarray['owner-link'] = $contact['url'];
720 $datarray['owner-avatar'] = $contact['thumb'];
721 $datarray['author-name'] = $contact['name'];
722 $datarray['author-link'] = $contact['url'];
723 $datarray['author-avatar'] = $contact['thumb'];
724 $datarray['body'] = $prefix . $body;
725 $datarray['tag'] = $str_tags;
726 $datarray['app'] = 'Diaspora';
728 $message_id = item_store($datarray);
731 q("update item set plink = '%s' where id = %d limit 1",
732 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
742 function diaspora_asphoto($importer,$xml) {
743 logger('diaspora_asphoto called');
746 $guid = notags(unxmlify($xml->guid));
747 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
749 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
753 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
754 logger('diaspora_asphoto: Ignoring this author.');
758 $message_id = $diaspora_handle . ':' . $guid;
759 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
760 intval($importer['uid']),
765 logger('diaspora_asphoto: message exists: ' . $guid);
769 // allocate a guid on our system - we aren't fixing any collisions.
770 // we're ignoring them
772 $g = q("select * from guid where guid = '%s' limit 1",
776 q("insert into guid ( guid ) values ( '%s' )",
781 $created = unxmlify($xml->created_at);
782 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
784 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
785 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
786 $body = scale_diaspora_images($body,false);
788 elseif($xml->image_url) {
789 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
790 $body = scale_diaspora_images($body);
793 logger('diaspora_asphoto: no photo url found.');
800 $datarray['uid'] = $importer['uid'];
801 $datarray['contact-id'] = $contact['id'];
802 $datarray['wall'] = 0;
803 $datarray['guid'] = $guid;
804 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
805 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
806 $datarray['private'] = $private;
807 $datarray['parent'] = 0;
808 $datarray['owner-name'] = $contact['name'];
809 $datarray['owner-link'] = $contact['url'];
810 $datarray['owner-avatar'] = $contact['thumb'];
811 $datarray['author-name'] = $contact['name'];
812 $datarray['author-link'] = $contact['url'];
813 $datarray['author-avatar'] = $contact['thumb'];
814 $datarray['body'] = $body;
816 $datarray['app'] = 'Diaspora/Cubbi.es';
818 $message_id = item_store($datarray);
821 q("update item set plink = '%s' where id = %d limit 1",
822 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
836 function diaspora_comment($importer,$xml,$msg) {
839 $guid = notags(unxmlify($xml->guid));
840 $parent_guid = notags(unxmlify($xml->parent_guid));
841 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
842 $target_type = notags(unxmlify($xml->target_type));
843 $text = unxmlify($xml->text);
844 $author_signature = notags(unxmlify($xml->author_signature));
846 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
850 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
852 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
856 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
857 logger('diaspora_comment: Ignoring this author.');
861 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
862 intval($importer['uid']),
866 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
870 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
871 intval($importer['uid']),
875 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
878 $parent_item = $r[0];
880 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
882 $author_signature = base64_decode($author_signature);
884 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
889 $person = find_diaspora_person_by_handle($diaspora_handle);
891 if(is_array($person) && x($person,'pubkey'))
892 $key = $person['pubkey'];
894 logger('diaspora_comment: unable to find author details');
899 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
900 logger('diaspora_comment: verification failed.');
904 if($parent_author_signature) {
905 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
907 $parent_author_signature = base64_decode($parent_author_signature);
911 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
912 logger('diaspora_comment: owner verification failed.');
917 // Phew! Everything checks out. Now create an item.
919 $body = diaspora2bb($text);
921 $message_id = $diaspora_handle . ':' . $guid;
927 $tags = get_tags($body);
930 foreach($tags as $tag) {
931 if(strpos($tag,'#') === 0) {
932 if(strpos($tag,'[url='))
934 $basetag = str_replace('_',' ',substr($tag,1));
935 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
936 if(strlen($str_tags))
938 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
944 $datarray['uid'] = $importer['uid'];
945 $datarray['contact-id'] = $contact['id'];
946 $datarray['wall'] = $parent_item['wall'];
947 $datarray['gravity'] = GRAVITY_COMMENT;
948 $datarray['guid'] = $guid;
949 $datarray['uri'] = $message_id;
950 $datarray['parent-uri'] = $parent_item['uri'];
952 // No timestamps for comments? OK, we'll the use current time.
953 $datarray['created'] = $datarray['edited'] = datetime_convert();
954 $datarray['private'] = $parent_item['private'];
956 $datarray['owner-name'] = $parent_item['owner-name'];
957 $datarray['owner-link'] = $parent_item['owner-link'];
958 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
960 $datarray['author-name'] = $person['name'];
961 $datarray['author-link'] = $person['url'];
962 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
963 $datarray['body'] = $body;
964 $datarray['tag'] = $str_tags;
966 // We can't be certain what the original app is if the message is relayed.
967 if(($parent_item['origin']) && (! $parent_author_signature))
968 $datarray['app'] = 'Diaspora';
970 $message_id = item_store($datarray);
973 q("update item set plink = '%s' where id = %d limit 1",
974 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
979 if(($parent_item['origin']) && (! $parent_author_signature)) {
980 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
982 dbesc($author_signed_data),
983 dbesc(base64_encode($author_signature)),
984 dbesc($diaspora_handle)
987 // if the message isn't already being relayed, notify others
988 // the existence of parent_author_signature means the parent_author or owner
989 // is already relaying.
991 proc_run('php','include/notifier.php','comment',$message_id);
996 function diaspora_photo($importer,$xml,$msg) {
999 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1001 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1003 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1005 $guid = notags(unxmlify($xml->guid));
1007 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1009 $public = notags(unxmlify($xml->public));
1011 $created_at = notags(unxmlify($xml_created_at));
1014 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1018 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1019 logger('diaspora_photo: Ignoring this author.');
1023 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1024 intval($importer['uid']),
1025 dbesc($status_message_guid)
1028 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1031 $parent_item = $r[0];
1033 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1035 $link_text = scale_diaspora_images($link_text);
1037 if(strpos($parent_item['body'],$link_text) === false) {
1038 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1039 dbesc($link_text . $parent_item['body']),
1040 intval($parent_item['id']),
1041 intval($parent_item['uid'])
1051 function diaspora_like($importer,$xml,$msg) {
1054 $guid = notags(unxmlify($xml->guid));
1055 $parent_guid = notags(unxmlify($xml->parent_guid));
1056 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1057 $target_type = notags(unxmlify($xml->target_type));
1058 $positive = notags(unxmlify($xml->positive));
1059 $author_signature = notags(unxmlify($xml->author_signature));
1061 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1063 // likes on comments not supported here and likes on photos not supported by Diaspora
1065 if($target_type !== 'Post')
1068 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1070 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1074 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1075 logger('diaspora_like: Ignoring this author.');
1079 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1080 intval($importer['uid']),
1084 logger('diaspora_like: parent item not found: ' . $guid);
1088 $parent_item = $r[0];
1090 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1091 intval($importer['uid']),
1095 if($positive === 'true') {
1096 logger('diaspora_like: duplicate like: ' . $guid);
1099 if($positive === 'false') {
1100 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1101 intval($r[0]['id']),
1102 intval($importer['uid'])
1105 // send notification via proc_run()
1109 if($positive === 'false') {
1110 logger('diaspora_like: unlike received with no corresponding like');
1114 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1116 $author_signature = base64_decode($author_signature);
1118 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1123 $person = find_diaspora_person_by_handle($diaspora_handle);
1124 if(is_array($person) && x($person,'pubkey'))
1125 $key = $person['pubkey'];
1127 logger('diaspora_like: unable to find author details');
1132 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1133 logger('diaspora_like: verification failed.');
1137 if($parent_author_signature) {
1139 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1141 $parent_author_signature = base64_decode($parent_author_signature);
1145 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1146 logger('diaspora_like: owner verification failed.');
1151 // Phew! Everything checks out. Now create an item.
1153 $uri = $diaspora_handle . ':' . $guid;
1155 $activity = ACTIVITY_LIKE;
1156 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1157 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1158 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1159 $body = $parent_item['body'];
1164 <type>$objtype</type>
1166 <id>{$parent_item['uri']}</id>
1169 <content>$body</content>
1172 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1177 $arr['uid'] = $importer['uid'];
1178 $arr['guid'] = $guid;
1179 $arr['contact-id'] = $contact['id'];
1180 $arr['type'] = 'activity';
1181 $arr['wall'] = $parent_item['wall'];
1182 $arr['gravity'] = GRAVITY_LIKE;
1183 $arr['parent'] = $parent_item['id'];
1184 $arr['parent-uri'] = $parent_item['uri'];
1186 $arr['owner-name'] = $parent_item['name'];
1187 $arr['owner-link'] = $parent_item['url'];
1188 $arr['owner-avatar'] = $parent_item['thumb'];
1190 $arr['author-name'] = $person['name'];
1191 $arr['author-link'] = $person['url'];
1192 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1194 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1195 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1196 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1197 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1199 $arr['app'] = 'Diaspora';
1201 $arr['private'] = $parent_item['private'];
1202 $arr['verb'] = $activity;
1203 $arr['object-type'] = $objtype;
1204 $arr['object'] = $obj;
1205 $arr['visible'] = 1;
1207 $arr['last-child'] = 0;
1209 $message_id = item_store($arr);
1213 q("update item set plink = '%s' where id = %d limit 1",
1214 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1219 if(! $parent_author_signature) {
1220 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1221 intval($message_id),
1222 dbesc($author_signed_data),
1223 dbesc(base64_encode($author_signature)),
1224 dbesc($diaspora_handle)
1228 // if the message isn't already being relayed, notify others
1229 // the existence of parent_author_signature means the parent_author or owner
1230 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1232 if(($parent_item['origin']) && (! $parent_author_signature))
1233 proc_run('php','include/notifier.php','comment',$message_id);
1238 function diaspora_retraction($importer,$xml) {
1240 $guid = notags(unxmlify($xml->guid));
1241 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1242 $type = notags(unxmlify($xml->type));
1244 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1248 if($type === 'Person') {
1249 contact_remove($contact['id']);
1251 elseif($type === 'Post') {
1252 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1254 intval($importer['uid'])
1257 if(link_compare($r[0]['author-link'],$contact['url'])) {
1258 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1259 dbesc(datetime_convert()),
1270 function diaspora_signed_retraction($importer,$xml) {
1272 $guid = notags(unxmlify($xml->target_guid));
1273 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1274 $type = notags(unxmlify($xml->target_type));
1275 $sig = notags(unxmlify($xml->target_author_signature));
1277 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1281 // this may not yet work for comments. Need to see how the relaying works
1282 // and figure out who signs it.
1285 $signed_data = $guid . ';' . $type ;
1287 $sig = base64_decode($sig);
1291 if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1292 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1296 if($type === 'StatusMessage') {
1297 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1299 intval($importer['uid'])
1302 if(link_compare($r[0]['author-link'],$contact['url'])) {
1303 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1304 dbesc(datetime_convert()),
1315 function diaspora_profile($importer,$xml) {
1318 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1320 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1324 if($contact['blocked']) {
1325 logger('diaspora_post: Ignoring this author.');
1329 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1330 $image_url = unxmlify($xml->image_url);
1331 $birthday = unxmlify($xml->birthday);
1333 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1334 intval($importer['uid']),
1335 intval($contact['id'])
1337 $oldphotos = ((count($r)) ? $r : null);
1339 require_once('include/Photo.php');
1341 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1343 // Generic birthday. We don't know the timezone. The year is irrelevant.
1345 $birthday = str_replace('1000','1901',$birthday);
1347 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1349 $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",
1351 dbesc(datetime_convert()),
1355 dbesc(datetime_convert()),
1357 intval($contact['id']),
1358 intval($importer['uid'])
1363 foreach($oldphotos as $ph) {
1364 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1365 intval($importer['uid']),
1366 intval($contact['id']),
1367 dbesc($ph['resource-id'])
1398 function diaspora_share($me,$contact) {
1400 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1401 $theiraddr = $contact['addr'];
1403 $tpl = get_markup_template('diaspora_share.tpl');
1404 $msg = replace_macros($tpl, array(
1405 '$sender' => $myaddr,
1406 '$recipient' => $theiraddr
1409 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1411 return(diaspora_transmit($owner,$contact,$slap, false));
1414 function diaspora_unshare($me,$contact) {
1417 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1419 $tpl = get_markup_template('diaspora_retract.tpl');
1420 $msg = replace_macros($tpl, array(
1421 '$guid' => $me['guid'],
1422 '$type' => 'Person',
1423 '$handle' => $myaddr
1426 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1428 return(diaspora_transmit($owner,$contact,$slap, false));
1434 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1437 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1438 $theiraddr = $contact['addr'];
1442 $body = $item['body'];
1445 // We're trying to match Diaspora's split message/photo protocol but
1446 // all the photos are displayed on D* as links and not img's - even
1447 // though we're sending pretty much precisely what they send us when
1448 // doing the same operation.
1449 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1450 // which seems to get through intact.
1452 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1454 foreach($matches as $mtch) {
1456 $detail['str'] = $mtch[0];
1457 $detail['path'] = dirname($mtch[1]) . '/';
1458 $detail['file'] = basename($mtch[1]);
1459 $detail['guid'] = $item['guid'];
1460 $detail['handle'] = $myaddr;
1461 $images[] = $detail;
1462 $body = str_replace($detail['str'],$mtch[1],$body);
1467 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1469 if($item['attach']) {
1470 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1472 $body .= "\n" . t('Attachments:') . "\n";
1473 foreach($matches as $mtch) {
1474 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1480 $public = (($item['private']) ? 'false' : 'true');
1482 require_once('include/datetime.php');
1483 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1485 $tpl = get_markup_template('diaspora_post.tpl');
1486 $msg = replace_macros($tpl, array(
1488 '$guid' => $item['guid'],
1489 '$handle' => xmlify($myaddr),
1490 '$public' => $public,
1491 '$created' => $created
1494 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1496 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1498 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1500 if(count($images)) {
1501 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1504 return $return_code;
1508 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1510 if(! count($images))
1512 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1514 $tpl = get_markup_template('diaspora_photo.tpl');
1515 foreach($images as $image) {
1516 if(! stristr($image['path'],$mysite))
1518 $resource = str_replace('.jpg','',$image['file']);
1519 $resource = substr($resource,0,strpos($resource,'-'));
1521 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1523 intval($owner['uid'])
1527 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1528 $msg = replace_macros($tpl,array(
1529 '$path' => xmlify($image['path']),
1530 '$filename' => xmlify($image['file']),
1531 '$msg_guid' => xmlify($image['guid']),
1532 '$guid' => xmlify($r[0]['guid']),
1533 '$handle' => xmlify($image['handle']),
1534 '$public' => xmlify($public),
1535 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1539 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1540 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1542 diaspora_transmit($owner,$contact,$slap,$public_batch);
1547 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1550 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1551 $theiraddr = $contact['addr'];
1553 $p = q("select guid from item where parent = %d limit 1",
1557 $parent_guid = $p[0]['guid'];
1561 if($item['verb'] === ACTIVITY_LIKE) {
1562 $tpl = get_markup_template('diaspora_like.tpl');
1564 $target_type = 'Post';
1565 $positive = (($item['deleted']) ? 'false' : 'true');
1568 $tpl = get_markup_template('diaspora_comment.tpl');
1572 $text = html_entity_decode(bb2diaspora($item['body']));
1577 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1579 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1581 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1583 $msg = replace_macros($tpl,array(
1584 '$guid' => xmlify($item['guid']),
1585 '$parent_guid' => xmlify($parent_guid),
1586 '$target_type' =>xmlify($target_type),
1587 '$authorsig' => xmlify($authorsig),
1588 '$body' => xmlify($text),
1589 '$positive' => xmlify($positive),
1590 '$handle' => xmlify($myaddr)
1593 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1595 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1597 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1601 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1605 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1606 $theiraddr = $contact['addr'];
1609 $p = q("select guid from item where parent = %d limit 1",
1613 $parent_guid = $p[0]['guid'];
1617 if($item['verb'] === ACTIVITY_LIKE) {
1618 $tpl = get_markup_template('diaspora_like_relay.tpl');
1620 $target_type = 'Post';
1621 $positive = (($item['deleted']) ? 'false' : 'true');
1624 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1628 $body = $item['body'];
1630 $text = html_entity_decode(bb2diaspora($body));
1632 // fetch the original signature if somebody sent the post to us to relay
1633 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1634 // action. It wasn't needed. In that case create the original signature and the
1635 // owner (parent author) signature
1636 // comments from other networks will be relayed under our name, with a brief
1637 // preamble to describe what's happening and noting the real author
1639 $r = q("select * from sign where iid = %d limit 1",
1644 $signed_text = $orig_sign['signed_text'];
1645 $authorsig = $orig_sign['signature'];
1646 $handle = $orig_sign['signer'];
1650 $itemcontact = q("select * from contact where `id` = %d limit 1",
1651 intval($item['contact-id'])
1653 if(count($itemcontact)) {
1654 if(! $itemcontact[0]['self']) {
1655 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1656 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1657 network_to_name($itemcontact['network'])) . "\n";
1658 $body = $prefix . $body;
1664 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1666 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1668 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1670 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1671 intval($item['id']),
1672 dbesc($signed_text),
1673 dbesc(base64_encode($authorsig)),
1682 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1684 $msg = replace_macros($tpl,array(
1685 '$guid' => xmlify($item['guid']),
1686 '$parent_guid' => xmlify($parent_guid),
1687 '$target_type' =>xmlify($target_type),
1688 '$authorsig' => xmlify($orig_sign['signature']),
1689 '$parentsig' => xmlify($parentauthorsig),
1690 '$body' => xmlify($text),
1691 '$positive' => xmlify($positive),
1692 '$handle' => xmlify($handle)
1695 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1697 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1699 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1705 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1708 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1710 $signed_text = $item['guid'] . ';' . 'StatusMessage';
1712 $tpl = get_markup_template('diaspora_signed_retract.tpl');
1713 $msg = replace_macros($tpl, array(
1714 '$guid' => $item['guid'],
1715 '$type' => 'StatusMessage',
1716 '$handle' => $myaddr,
1717 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1720 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1722 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1727 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1730 $logid = random_string(4);
1731 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
1733 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
1737 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
1739 post_url($dest_url . '/', $slap);
1741 $return_code = $a->get_curl_code();
1742 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1744 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1745 logger('diaspora_transmit: queue message');
1747 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
1748 intval($contact['id']),
1749 dbesc(NETWORK_DIASPORA),
1751 intval($public_batch)
1754 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
1757 // queue message for redelivery
1758 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
1763 return(($return_code) ? $return_code : (-1));