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) {
425 $sender_handle = unxmlify($xml->sender_handle);
426 $recipient_handle = unxmlify($xml->recipient_handle);
428 if(! $sender_handle || ! $recipient_handle)
431 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
435 // perhaps we were already sharing with this person. Now they're sharing with us.
436 // That makes us friends.
438 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
439 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
440 intval(CONTACT_IS_FRIEND),
441 intval($contact['id']),
442 intval($importer['uid'])
447 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
448 intval($importer['uid'])
451 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
452 require_once('include/items.php');
454 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
455 intval($importer['uid'])
461 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
462 $arr['uid'] = $importer['uid'];
463 $arr['contact-id'] = $self[0]['id'];
465 $arr['type'] = 'wall';
468 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
469 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
470 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
471 $arr['verb'] = ACTIVITY_FRIEND;
472 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
474 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
475 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
476 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
477 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
479 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
480 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
481 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
482 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
483 $arr['object'] .= '</link></object>' . "\n";
484 $arr['last-child'] = 1;
486 $arr['allow_cid'] = $user[0]['allow_cid'];
487 $arr['allow_gid'] = $user[0]['allow_gid'];
488 $arr['deny_cid'] = $user[0]['deny_cid'];
489 $arr['deny_gid'] = $user[0]['deny_gid'];
491 $i = item_store($arr);
493 proc_run('php',"include/notifier.php","activity","$i");
502 $ret = find_diaspora_person_by_handle($sender_handle);
505 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
506 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
510 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
512 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
513 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
514 intval($importer['uid']),
515 dbesc($ret['network']),
519 dbesc(normalise_link($ret['url'])),
523 dbesc($ret['photo']),
524 dbesc($ret['pubkey']),
525 dbesc($ret['notify']),
531 // find the contact record we just created
533 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
535 $hash = random_string() . (string) time(); // Generate a confirm_key
537 if($contact_record) {
538 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
539 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
540 intval($importer['uid']),
541 intval($contact_record['id']),
544 dbesc( t('Sharing notification from Diaspora network')),
546 dbesc(datetime_convert())
553 function diaspora_post($importer,$xml) {
556 $guid = notags(unxmlify($xml->guid));
557 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
559 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
563 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
564 logger('diaspora_post: Ignoring this author.');
568 $message_id = $diaspora_handle . ':' . $guid;
569 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
570 intval($importer['uid']),
575 logger('diaspora_post: message exists: ' . $guid);
579 // allocate a guid on our system - we aren't fixing any collisions.
580 // we're ignoring them
582 $g = q("select * from guid where guid = '%s' limit 1",
586 q("insert into guid ( guid ) values ( '%s' )",
591 $created = unxmlify($xml->created_at);
592 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
594 $body = diaspora2bb($xml->raw_message);
600 $tags = get_tags($body);
603 foreach($tags as $tag) {
604 if(strpos($tag,'#') === 0) {
605 if(strpos($tag,'[url='))
607 $basetag = str_replace('_',' ',substr($tag,1));
608 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
609 if(strlen($str_tags))
611 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
617 $datarray['uid'] = $importer['uid'];
618 $datarray['contact-id'] = $contact['id'];
619 $datarray['wall'] = 0;
620 $datarray['guid'] = $guid;
621 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
622 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
623 $datarray['private'] = $private;
624 $datarray['parent'] = 0;
625 $datarray['owner-name'] = $contact['name'];
626 $datarray['owner-link'] = $contact['url'];
627 $datarray['owner-avatar'] = $contact['thumb'];
628 $datarray['author-name'] = $contact['name'];
629 $datarray['author-link'] = $contact['url'];
630 $datarray['author-avatar'] = $contact['thumb'];
631 $datarray['body'] = $body;
632 $datarray['tag'] = $str_tags;
633 $datarray['app'] = 'Diaspora';
635 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
637 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
639 $message_id = item_store($datarray);
642 q("update item set plink = '%s' where id = %d limit 1",
643 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
652 function diaspora_reshare($importer,$xml) {
654 logger('diaspora_reshare: init: ' . print_r($xml,true));
657 $guid = notags(unxmlify($xml->guid));
658 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
661 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
665 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
666 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
670 $message_id = $diaspora_handle . ':' . $guid;
671 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
672 intval($importer['uid']),
677 logger('diaspora_reshare: message exists: ' . $guid);
681 $orig_author = notags(unxmlify($xml->root_diaspora_id));
682 $orig_guid = notags(unxmlify($xml->root_guid));
684 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
685 $x = fetch_url($source_url);
687 $x = fetch_url(str_replace('https://','http://',$source_url));
689 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
692 logger('diaspora_reshare: source: ' . $x);
694 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
695 $source_xml = parse_xml_string($x,false);
697 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
698 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
699 $body = scale_diaspora_images($body,false);
701 elseif($source_xml->post->asphoto->image_url) {
702 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
703 $body = scale_diaspora_images($body);
705 elseif($source_xml->post->status_message) {
706 $body = diaspora2bb($source_xml->post->status_message->raw_message);
707 $body = scale_diaspora_images($body);
711 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
715 logger('diaspora_reshare: empty body: source= ' . $x);
719 $person = find_diaspora_person_by_handle($orig_author);
721 if(is_array($person) && x($person,'name') && x($person,'url'))
722 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
724 $details = $orig_author;
726 $prefix = '♲ ' . $details . "\n";
729 // allocate a guid on our system - we aren't fixing any collisions.
730 // we're ignoring them
732 $g = q("select * from guid where guid = '%s' limit 1",
736 q("insert into guid ( guid ) values ( '%s' )",
741 $created = unxmlify($xml->created_at);
742 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
748 $tags = get_tags($body);
751 foreach($tags as $tag) {
752 if(strpos($tag,'#') === 0) {
753 if(strpos($tag,'[url='))
755 $basetag = str_replace('_',' ',substr($tag,1));
756 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
757 if(strlen($str_tags))
759 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
765 $datarray['uid'] = $importer['uid'];
766 $datarray['contact-id'] = $contact['id'];
767 $datarray['wall'] = 0;
768 $datarray['guid'] = $guid;
769 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
770 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
771 $datarray['private'] = $private;
772 $datarray['parent'] = 0;
773 $datarray['owner-name'] = $contact['name'];
774 $datarray['owner-link'] = $contact['url'];
775 $datarray['owner-avatar'] = $contact['thumb'];
776 $datarray['author-name'] = $contact['name'];
777 $datarray['author-link'] = $contact['url'];
778 $datarray['author-avatar'] = $contact['thumb'];
779 $datarray['body'] = $prefix . $body;
780 $datarray['tag'] = $str_tags;
781 $datarray['app'] = 'Diaspora';
783 $message_id = item_store($datarray);
786 q("update item set plink = '%s' where id = %d limit 1",
787 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
797 function diaspora_asphoto($importer,$xml) {
798 logger('diaspora_asphoto called');
801 $guid = notags(unxmlify($xml->guid));
802 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
804 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
808 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
809 logger('diaspora_asphoto: Ignoring this author.');
813 $message_id = $diaspora_handle . ':' . $guid;
814 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
815 intval($importer['uid']),
820 logger('diaspora_asphoto: message exists: ' . $guid);
824 // allocate a guid on our system - we aren't fixing any collisions.
825 // we're ignoring them
827 $g = q("select * from guid where guid = '%s' limit 1",
831 q("insert into guid ( guid ) values ( '%s' )",
836 $created = unxmlify($xml->created_at);
837 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
839 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
840 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
841 $body = scale_diaspora_images($body,false);
843 elseif($xml->image_url) {
844 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
845 $body = scale_diaspora_images($body);
848 logger('diaspora_asphoto: no photo url found.');
855 $datarray['uid'] = $importer['uid'];
856 $datarray['contact-id'] = $contact['id'];
857 $datarray['wall'] = 0;
858 $datarray['guid'] = $guid;
859 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
860 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
861 $datarray['private'] = $private;
862 $datarray['parent'] = 0;
863 $datarray['owner-name'] = $contact['name'];
864 $datarray['owner-link'] = $contact['url'];
865 $datarray['owner-avatar'] = $contact['thumb'];
866 $datarray['author-name'] = $contact['name'];
867 $datarray['author-link'] = $contact['url'];
868 $datarray['author-avatar'] = $contact['thumb'];
869 $datarray['body'] = $body;
871 $datarray['app'] = 'Diaspora/Cubbi.es';
873 $message_id = item_store($datarray);
876 q("update item set plink = '%s' where id = %d limit 1",
877 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
891 function diaspora_comment($importer,$xml,$msg) {
894 $guid = notags(unxmlify($xml->guid));
895 $parent_guid = notags(unxmlify($xml->parent_guid));
896 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
897 $target_type = notags(unxmlify($xml->target_type));
898 $text = unxmlify($xml->text);
899 $author_signature = notags(unxmlify($xml->author_signature));
901 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
905 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
907 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
911 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
912 logger('diaspora_comment: Ignoring this author.');
916 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
917 intval($importer['uid']),
921 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
925 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
926 intval($importer['uid']),
930 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
933 $parent_item = $r[0];
935 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
937 $author_signature = base64_decode($author_signature);
939 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
944 $person = find_diaspora_person_by_handle($diaspora_handle);
946 if(is_array($person) && x($person,'pubkey'))
947 $key = $person['pubkey'];
949 logger('diaspora_comment: unable to find author details');
954 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
955 logger('diaspora_comment: verification failed.');
959 if($parent_author_signature) {
960 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
962 $parent_author_signature = base64_decode($parent_author_signature);
966 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
967 logger('diaspora_comment: owner verification failed.');
972 // Phew! Everything checks out. Now create an item.
974 $body = diaspora2bb($text);
976 $message_id = $diaspora_handle . ':' . $guid;
982 $tags = get_tags($body);
985 foreach($tags as $tag) {
986 if(strpos($tag,'#') === 0) {
987 if(strpos($tag,'[url='))
989 $basetag = str_replace('_',' ',substr($tag,1));
990 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
991 if(strlen($str_tags))
993 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
999 $datarray['uid'] = $importer['uid'];
1000 $datarray['contact-id'] = $contact['id'];
1001 $datarray['wall'] = $parent_item['wall'];
1002 $datarray['gravity'] = GRAVITY_COMMENT;
1003 $datarray['guid'] = $guid;
1004 $datarray['uri'] = $message_id;
1005 $datarray['parent-uri'] = $parent_item['uri'];
1007 // No timestamps for comments? OK, we'll the use current time.
1008 $datarray['created'] = $datarray['edited'] = datetime_convert();
1009 $datarray['private'] = $parent_item['private'];
1011 $datarray['owner-name'] = $parent_item['owner-name'];
1012 $datarray['owner-link'] = $parent_item['owner-link'];
1013 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1015 $datarray['author-name'] = $person['name'];
1016 $datarray['author-link'] = $person['url'];
1017 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1018 $datarray['body'] = $body;
1019 $datarray['tag'] = $str_tags;
1021 // We can't be certain what the original app is if the message is relayed.
1022 if(($parent_item['origin']) && (! $parent_author_signature))
1023 $datarray['app'] = 'Diaspora';
1025 $message_id = item_store($datarray);
1028 q("update item set plink = '%s' where id = %d limit 1",
1029 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1034 if(($parent_item['origin']) && (! $parent_author_signature)) {
1035 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1036 intval($message_id),
1037 dbesc($author_signed_data),
1038 dbesc(base64_encode($author_signature)),
1039 dbesc($diaspora_handle)
1042 // if the message isn't already being relayed, notify others
1043 // the existence of parent_author_signature means the parent_author or owner
1044 // is already relaying.
1046 proc_run('php','include/notifier.php','comment',$message_id);
1051 function diaspora_photo($importer,$xml,$msg) {
1054 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1056 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1058 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1060 $guid = notags(unxmlify($xml->guid));
1062 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1064 $public = notags(unxmlify($xml->public));
1066 $created_at = notags(unxmlify($xml_created_at));
1069 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1073 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1074 logger('diaspora_photo: Ignoring this author.');
1078 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1079 intval($importer['uid']),
1080 dbesc($status_message_guid)
1083 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1086 $parent_item = $r[0];
1088 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1090 $link_text = scale_diaspora_images($link_text);
1092 if(strpos($parent_item['body'],$link_text) === false) {
1093 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1094 dbesc($link_text . $parent_item['body']),
1095 intval($parent_item['id']),
1096 intval($parent_item['uid'])
1106 function diaspora_like($importer,$xml,$msg) {
1109 $guid = notags(unxmlify($xml->guid));
1110 $parent_guid = notags(unxmlify($xml->parent_guid));
1111 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1112 $target_type = notags(unxmlify($xml->target_type));
1113 $positive = notags(unxmlify($xml->positive));
1114 $author_signature = notags(unxmlify($xml->author_signature));
1116 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1118 // likes on comments not supported here and likes on photos not supported by Diaspora
1120 if($target_type !== 'Post')
1123 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1125 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1129 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1130 logger('diaspora_like: Ignoring this author.');
1134 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1135 intval($importer['uid']),
1139 logger('diaspora_like: parent item not found: ' . $guid);
1143 $parent_item = $r[0];
1145 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1146 intval($importer['uid']),
1150 if($positive === 'true') {
1151 logger('diaspora_like: duplicate like: ' . $guid);
1154 if($positive === 'false') {
1155 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1156 intval($r[0]['id']),
1157 intval($importer['uid'])
1160 // send notification via proc_run()
1164 if($positive === 'false') {
1165 logger('diaspora_like: unlike received with no corresponding like');
1169 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1171 $author_signature = base64_decode($author_signature);
1173 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1178 $person = find_diaspora_person_by_handle($diaspora_handle);
1179 if(is_array($person) && x($person,'pubkey'))
1180 $key = $person['pubkey'];
1182 logger('diaspora_like: unable to find author details');
1187 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1188 logger('diaspora_like: verification failed.');
1192 if($parent_author_signature) {
1194 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1196 $parent_author_signature = base64_decode($parent_author_signature);
1200 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1201 logger('diaspora_like: owner verification failed.');
1206 // Phew! Everything checks out. Now create an item.
1208 $uri = $diaspora_handle . ':' . $guid;
1210 $activity = ACTIVITY_LIKE;
1211 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1212 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1213 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1214 $body = $parent_item['body'];
1219 <type>$objtype</type>
1221 <id>{$parent_item['uri']}</id>
1224 <content>$body</content>
1227 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1232 $arr['uid'] = $importer['uid'];
1233 $arr['guid'] = $guid;
1234 $arr['contact-id'] = $contact['id'];
1235 $arr['type'] = 'activity';
1236 $arr['wall'] = $parent_item['wall'];
1237 $arr['gravity'] = GRAVITY_LIKE;
1238 $arr['parent'] = $parent_item['id'];
1239 $arr['parent-uri'] = $parent_item['uri'];
1241 $arr['owner-name'] = $parent_item['name'];
1242 $arr['owner-link'] = $parent_item['url'];
1243 $arr['owner-avatar'] = $parent_item['thumb'];
1245 $arr['author-name'] = $person['name'];
1246 $arr['author-link'] = $person['url'];
1247 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1249 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1250 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1251 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1252 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1254 $arr['app'] = 'Diaspora';
1256 $arr['private'] = $parent_item['private'];
1257 $arr['verb'] = $activity;
1258 $arr['object-type'] = $objtype;
1259 $arr['object'] = $obj;
1260 $arr['visible'] = 1;
1262 $arr['last-child'] = 0;
1264 $message_id = item_store($arr);
1268 q("update item set plink = '%s' where id = %d limit 1",
1269 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1274 if(! $parent_author_signature) {
1275 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1276 intval($message_id),
1277 dbesc($author_signed_data),
1278 dbesc(base64_encode($author_signature)),
1279 dbesc($diaspora_handle)
1283 // if the message isn't already being relayed, notify others
1284 // the existence of parent_author_signature means the parent_author or owner
1285 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1287 if(($parent_item['origin']) && (! $parent_author_signature))
1288 proc_run('php','include/notifier.php','comment',$message_id);
1293 function diaspora_retraction($importer,$xml) {
1295 $guid = notags(unxmlify($xml->guid));
1296 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1297 $type = notags(unxmlify($xml->type));
1299 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1303 if($type === 'Person') {
1304 contact_remove($contact['id']);
1306 elseif($type === 'Post') {
1307 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1309 intval($importer['uid'])
1312 if(link_compare($r[0]['author-link'],$contact['url'])) {
1313 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1314 dbesc(datetime_convert()),
1325 function diaspora_signed_retraction($importer,$xml) {
1327 $guid = notags(unxmlify($xml->target_guid));
1328 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1329 $type = notags(unxmlify($xml->target_type));
1330 $sig = notags(unxmlify($xml->target_author_signature));
1332 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1336 // this may not yet work for comments. Need to see how the relaying works
1337 // and figure out who signs it.
1340 $signed_data = $guid . ';' . $type ;
1342 $sig = base64_decode($sig);
1346 if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1347 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1351 if($type === 'StatusMessage') {
1352 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1354 intval($importer['uid'])
1357 if(link_compare($r[0]['author-link'],$contact['url'])) {
1358 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1359 dbesc(datetime_convert()),
1370 function diaspora_profile($importer,$xml) {
1373 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1375 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1379 if($contact['blocked']) {
1380 logger('diaspora_post: Ignoring this author.');
1384 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1385 $image_url = unxmlify($xml->image_url);
1386 $birthday = unxmlify($xml->birthday);
1388 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1389 intval($importer['uid']),
1390 intval($contact['id'])
1392 $oldphotos = ((count($r)) ? $r : null);
1394 require_once('include/Photo.php');
1396 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1398 // Generic birthday. We don't know the timezone. The year is irrelevant.
1400 $birthday = str_replace('1000','1901',$birthday);
1402 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1404 $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",
1406 dbesc(datetime_convert()),
1410 dbesc(datetime_convert()),
1412 intval($contact['id']),
1413 intval($importer['uid'])
1418 foreach($oldphotos as $ph) {
1419 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1420 intval($importer['uid']),
1421 intval($contact['id']),
1422 dbesc($ph['resource-id'])
1453 function diaspora_share($me,$contact) {
1455 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1456 $theiraddr = $contact['addr'];
1458 $tpl = get_markup_template('diaspora_share.tpl');
1459 $msg = replace_macros($tpl, array(
1460 '$sender' => $myaddr,
1461 '$recipient' => $theiraddr
1464 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1466 return(diaspora_transmit($owner,$contact,$slap, false));
1469 function diaspora_unshare($me,$contact) {
1472 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1474 $tpl = get_markup_template('diaspora_retract.tpl');
1475 $msg = replace_macros($tpl, array(
1476 '$guid' => $me['guid'],
1477 '$type' => 'Person',
1478 '$handle' => $myaddr
1481 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1483 return(diaspora_transmit($owner,$contact,$slap, false));
1489 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1492 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1493 $theiraddr = $contact['addr'];
1497 $body = $item['body'];
1500 // We're trying to match Diaspora's split message/photo protocol but
1501 // all the photos are displayed on D* as links and not img's - even
1502 // though we're sending pretty much precisely what they send us when
1503 // doing the same operation.
1504 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1505 // which seems to get through intact.
1507 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1509 foreach($matches as $mtch) {
1511 $detail['str'] = $mtch[0];
1512 $detail['path'] = dirname($mtch[1]) . '/';
1513 $detail['file'] = basename($mtch[1]);
1514 $detail['guid'] = $item['guid'];
1515 $detail['handle'] = $myaddr;
1516 $images[] = $detail;
1517 $body = str_replace($detail['str'],$mtch[1],$body);
1522 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1524 if($item['attach']) {
1525 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1527 $body .= "\n" . t('Attachments:') . "\n";
1528 foreach($matches as $mtch) {
1529 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1535 $public = (($item['private']) ? 'false' : 'true');
1537 require_once('include/datetime.php');
1538 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1540 $tpl = get_markup_template('diaspora_post.tpl');
1541 $msg = replace_macros($tpl, array(
1543 '$guid' => $item['guid'],
1544 '$handle' => xmlify($myaddr),
1545 '$public' => $public,
1546 '$created' => $created
1549 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1551 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1553 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1555 if(count($images)) {
1556 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1559 return $return_code;
1563 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1565 if(! count($images))
1567 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1569 $tpl = get_markup_template('diaspora_photo.tpl');
1570 foreach($images as $image) {
1571 if(! stristr($image['path'],$mysite))
1573 $resource = str_replace('.jpg','',$image['file']);
1574 $resource = substr($resource,0,strpos($resource,'-'));
1576 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1578 intval($owner['uid'])
1582 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1583 $msg = replace_macros($tpl,array(
1584 '$path' => xmlify($image['path']),
1585 '$filename' => xmlify($image['file']),
1586 '$msg_guid' => xmlify($image['guid']),
1587 '$guid' => xmlify($r[0]['guid']),
1588 '$handle' => xmlify($image['handle']),
1589 '$public' => xmlify($public),
1590 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1594 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1595 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1597 diaspora_transmit($owner,$contact,$slap,$public_batch);
1602 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1605 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1606 $theiraddr = $contact['addr'];
1608 $p = q("select guid from item where parent = %d limit 1",
1612 $parent_guid = $p[0]['guid'];
1616 if($item['verb'] === ACTIVITY_LIKE) {
1617 $tpl = get_markup_template('diaspora_like.tpl');
1619 $target_type = 'Post';
1620 $positive = (($item['deleted']) ? 'false' : 'true');
1623 $tpl = get_markup_template('diaspora_comment.tpl');
1627 $text = html_entity_decode(bb2diaspora($item['body']));
1632 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1634 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1636 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1638 $msg = replace_macros($tpl,array(
1639 '$guid' => xmlify($item['guid']),
1640 '$parent_guid' => xmlify($parent_guid),
1641 '$target_type' =>xmlify($target_type),
1642 '$authorsig' => xmlify($authorsig),
1643 '$body' => xmlify($text),
1644 '$positive' => xmlify($positive),
1645 '$handle' => xmlify($myaddr)
1648 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1650 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1652 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1656 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1660 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1661 $theiraddr = $contact['addr'];
1664 $p = q("select guid from item where parent = %d limit 1",
1668 $parent_guid = $p[0]['guid'];
1672 if($item['verb'] === ACTIVITY_LIKE) {
1673 $tpl = get_markup_template('diaspora_like_relay.tpl');
1675 $target_type = 'Post';
1676 $positive = (($item['deleted']) ? 'false' : 'true');
1679 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1683 $body = $item['body'];
1685 $text = html_entity_decode(bb2diaspora($body));
1687 // fetch the original signature if somebody sent the post to us to relay
1688 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1689 // action. It wasn't needed. In that case create the original signature and the
1690 // owner (parent author) signature
1691 // comments from other networks will be relayed under our name, with a brief
1692 // preamble to describe what's happening and noting the real author
1694 $r = q("select * from sign where iid = %d limit 1",
1699 $signed_text = $orig_sign['signed_text'];
1700 $authorsig = $orig_sign['signature'];
1701 $handle = $orig_sign['signer'];
1705 $itemcontact = q("select * from contact where `id` = %d limit 1",
1706 intval($item['contact-id'])
1708 if(count($itemcontact)) {
1709 if(! $itemcontact[0]['self']) {
1710 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1711 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1712 network_to_name($itemcontact['network'])) . "\n";
1713 $body = $prefix . $body;
1719 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1721 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1723 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1725 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1726 intval($item['id']),
1727 dbesc($signed_text),
1728 dbesc(base64_encode($authorsig)),
1737 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1739 $msg = replace_macros($tpl,array(
1740 '$guid' => xmlify($item['guid']),
1741 '$parent_guid' => xmlify($parent_guid),
1742 '$target_type' =>xmlify($target_type),
1743 '$authorsig' => xmlify($orig_sign['signature']),
1744 '$parentsig' => xmlify($parentauthorsig),
1745 '$body' => xmlify($text),
1746 '$positive' => xmlify($positive),
1747 '$handle' => xmlify($handle)
1750 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1752 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1754 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1760 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1763 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1765 $signed_text = $item['guid'] . ';' . 'StatusMessage';
1767 $tpl = get_markup_template('diaspora_signed_retract.tpl');
1768 $msg = replace_macros($tpl, array(
1769 '$guid' => $item['guid'],
1770 '$type' => 'StatusMessage',
1771 '$handle' => $myaddr,
1772 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1775 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1777 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1782 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1785 $logid = random_string(4);
1786 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
1788 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
1792 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
1794 post_url($dest_url . '/', $slap);
1796 $return_code = $a->get_curl_code();
1797 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1799 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1800 logger('diaspora_transmit: queue message');
1802 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
1803 intval($contact['id']),
1804 dbesc(NETWORK_DIASPORA),
1806 intval($public_batch)
1809 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
1812 // queue message for redelivery
1813 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
1818 return(($return_code) ? $return_code : (-1));