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'])
458 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
460 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
463 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
464 $arr['uid'] = $importer['uid'];
465 $arr['contact-id'] = $self[0]['id'];
467 $arr['type'] = 'wall';
470 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
471 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
472 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
473 $arr['verb'] = ACTIVITY_FRIEND;
474 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
476 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
477 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
478 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
479 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
481 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
482 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
483 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
484 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
485 $arr['object'] .= '</link></object>' . "\n";
486 $arr['last-child'] = 1;
488 $arr['allow_cid'] = $user[0]['allow_cid'];
489 $arr['allow_gid'] = $user[0]['allow_gid'];
490 $arr['deny_cid'] = $user[0]['deny_cid'];
491 $arr['deny_gid'] = $user[0]['deny_gid'];
493 $i = item_store($arr);
495 proc_run('php',"include/notifier.php","activity","$i");
504 $ret = find_diaspora_person_by_handle($sender_handle);
507 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
508 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
512 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
514 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
515 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
516 intval($importer['uid']),
517 dbesc($ret['network']),
521 dbesc(normalise_link($ret['url'])),
525 dbesc($ret['photo']),
526 dbesc($ret['pubkey']),
527 dbesc($ret['notify']),
533 // find the contact record we just created
535 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
537 $hash = random_string() . (string) time(); // Generate a confirm_key
539 if($contact_record) {
540 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
541 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
542 intval($importer['uid']),
543 intval($contact_record['id']),
546 dbesc( t('Sharing notification from Diaspora network')),
548 dbesc(datetime_convert())
555 function diaspora_post($importer,$xml) {
558 $guid = notags(unxmlify($xml->guid));
559 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
561 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
565 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
566 logger('diaspora_post: Ignoring this author.');
570 $message_id = $diaspora_handle . ':' . $guid;
571 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
572 intval($importer['uid']),
577 logger('diaspora_post: message exists: ' . $guid);
581 // allocate a guid on our system - we aren't fixing any collisions.
582 // we're ignoring them
584 $g = q("select * from guid where guid = '%s' limit 1",
588 q("insert into guid ( guid ) values ( '%s' )",
593 $created = unxmlify($xml->created_at);
594 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
596 $body = diaspora2bb($xml->raw_message);
602 $tags = get_tags($body);
605 foreach($tags as $tag) {
606 if(strpos($tag,'#') === 0) {
607 if(strpos($tag,'[url='))
609 $basetag = str_replace('_',' ',substr($tag,1));
610 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
611 if(strlen($str_tags))
613 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
619 $datarray['uid'] = $importer['uid'];
620 $datarray['contact-id'] = $contact['id'];
621 $datarray['wall'] = 0;
622 $datarray['guid'] = $guid;
623 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
624 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
625 $datarray['private'] = $private;
626 $datarray['parent'] = 0;
627 $datarray['owner-name'] = $contact['name'];
628 $datarray['owner-link'] = $contact['url'];
629 $datarray['owner-avatar'] = $contact['thumb'];
630 $datarray['author-name'] = $contact['name'];
631 $datarray['author-link'] = $contact['url'];
632 $datarray['author-avatar'] = $contact['thumb'];
633 $datarray['body'] = $body;
634 $datarray['tag'] = $str_tags;
635 $datarray['app'] = 'Diaspora';
637 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
639 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
641 $message_id = item_store($datarray);
644 q("update item set plink = '%s' where id = %d limit 1",
645 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
654 function diaspora_reshare($importer,$xml) {
656 logger('diaspora_reshare: init: ' . print_r($xml,true));
659 $guid = notags(unxmlify($xml->guid));
660 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
663 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
667 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
668 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
672 $message_id = $diaspora_handle . ':' . $guid;
673 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
674 intval($importer['uid']),
679 logger('diaspora_reshare: message exists: ' . $guid);
683 $orig_author = notags(unxmlify($xml->root_diaspora_id));
684 $orig_guid = notags(unxmlify($xml->root_guid));
686 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
687 $x = fetch_url($source_url);
689 $x = fetch_url(str_replace('https://','http://',$source_url));
691 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
694 logger('diaspora_reshare: source: ' . $x);
696 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
697 $source_xml = parse_xml_string($x,false);
699 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
700 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
701 $body = scale_diaspora_images($body,false);
703 elseif($source_xml->post->asphoto->image_url) {
704 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
705 $body = scale_diaspora_images($body);
707 elseif($source_xml->post->status_message) {
708 $body = diaspora2bb($source_xml->post->status_message->raw_message);
709 $body = scale_diaspora_images($body);
713 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
717 logger('diaspora_reshare: empty body: source= ' . $x);
721 $person = find_diaspora_person_by_handle($orig_author);
723 if(is_array($person) && x($person,'name') && x($person,'url'))
724 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
726 $details = $orig_author;
728 $prefix = '♲ ' . $details . "\n";
731 // allocate a guid on our system - we aren't fixing any collisions.
732 // we're ignoring them
734 $g = q("select * from guid where guid = '%s' limit 1",
738 q("insert into guid ( guid ) values ( '%s' )",
743 $created = unxmlify($xml->created_at);
744 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
750 $tags = get_tags($body);
753 foreach($tags as $tag) {
754 if(strpos($tag,'#') === 0) {
755 if(strpos($tag,'[url='))
757 $basetag = str_replace('_',' ',substr($tag,1));
758 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
759 if(strlen($str_tags))
761 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
767 $datarray['uid'] = $importer['uid'];
768 $datarray['contact-id'] = $contact['id'];
769 $datarray['wall'] = 0;
770 $datarray['guid'] = $guid;
771 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
772 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
773 $datarray['private'] = $private;
774 $datarray['parent'] = 0;
775 $datarray['owner-name'] = $contact['name'];
776 $datarray['owner-link'] = $contact['url'];
777 $datarray['owner-avatar'] = $contact['thumb'];
778 $datarray['author-name'] = $contact['name'];
779 $datarray['author-link'] = $contact['url'];
780 $datarray['author-avatar'] = $contact['thumb'];
781 $datarray['body'] = $prefix . $body;
782 $datarray['tag'] = $str_tags;
783 $datarray['app'] = 'Diaspora';
785 $message_id = item_store($datarray);
788 q("update item set plink = '%s' where id = %d limit 1",
789 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
799 function diaspora_asphoto($importer,$xml) {
800 logger('diaspora_asphoto called');
803 $guid = notags(unxmlify($xml->guid));
804 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
806 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
810 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
811 logger('diaspora_asphoto: Ignoring this author.');
815 $message_id = $diaspora_handle . ':' . $guid;
816 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
817 intval($importer['uid']),
822 logger('diaspora_asphoto: message exists: ' . $guid);
826 // allocate a guid on our system - we aren't fixing any collisions.
827 // we're ignoring them
829 $g = q("select * from guid where guid = '%s' limit 1",
833 q("insert into guid ( guid ) values ( '%s' )",
838 $created = unxmlify($xml->created_at);
839 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
841 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
842 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
843 $body = scale_diaspora_images($body,false);
845 elseif($xml->image_url) {
846 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
847 $body = scale_diaspora_images($body);
850 logger('diaspora_asphoto: no photo url found.');
857 $datarray['uid'] = $importer['uid'];
858 $datarray['contact-id'] = $contact['id'];
859 $datarray['wall'] = 0;
860 $datarray['guid'] = $guid;
861 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
862 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
863 $datarray['private'] = $private;
864 $datarray['parent'] = 0;
865 $datarray['owner-name'] = $contact['name'];
866 $datarray['owner-link'] = $contact['url'];
867 $datarray['owner-avatar'] = $contact['thumb'];
868 $datarray['author-name'] = $contact['name'];
869 $datarray['author-link'] = $contact['url'];
870 $datarray['author-avatar'] = $contact['thumb'];
871 $datarray['body'] = $body;
873 $datarray['app'] = 'Diaspora/Cubbi.es';
875 $message_id = item_store($datarray);
878 q("update item set plink = '%s' where id = %d limit 1",
879 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
893 function diaspora_comment($importer,$xml,$msg) {
896 $guid = notags(unxmlify($xml->guid));
897 $parent_guid = notags(unxmlify($xml->parent_guid));
898 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
899 $target_type = notags(unxmlify($xml->target_type));
900 $text = unxmlify($xml->text);
901 $author_signature = notags(unxmlify($xml->author_signature));
903 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
907 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
909 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
913 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
914 logger('diaspora_comment: Ignoring this author.');
918 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
919 intval($importer['uid']),
923 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
927 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
928 intval($importer['uid']),
932 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
935 $parent_item = $r[0];
937 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
939 $author_signature = base64_decode($author_signature);
941 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
946 $person = find_diaspora_person_by_handle($diaspora_handle);
948 if(is_array($person) && x($person,'pubkey'))
949 $key = $person['pubkey'];
951 logger('diaspora_comment: unable to find author details');
956 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
957 logger('diaspora_comment: verification failed.');
961 if($parent_author_signature) {
962 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
964 $parent_author_signature = base64_decode($parent_author_signature);
968 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
969 logger('diaspora_comment: owner verification failed.');
974 // Phew! Everything checks out. Now create an item.
976 $body = diaspora2bb($text);
978 $message_id = $diaspora_handle . ':' . $guid;
984 $tags = get_tags($body);
987 foreach($tags as $tag) {
988 if(strpos($tag,'#') === 0) {
989 if(strpos($tag,'[url='))
991 $basetag = str_replace('_',' ',substr($tag,1));
992 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
993 if(strlen($str_tags))
995 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1001 $datarray['uid'] = $importer['uid'];
1002 $datarray['contact-id'] = $contact['id'];
1003 $datarray['wall'] = $parent_item['wall'];
1004 $datarray['gravity'] = GRAVITY_COMMENT;
1005 $datarray['guid'] = $guid;
1006 $datarray['uri'] = $message_id;
1007 $datarray['parent-uri'] = $parent_item['uri'];
1009 // No timestamps for comments? OK, we'll the use current time.
1010 $datarray['created'] = $datarray['edited'] = datetime_convert();
1011 $datarray['private'] = $parent_item['private'];
1013 $datarray['owner-name'] = $parent_item['owner-name'];
1014 $datarray['owner-link'] = $parent_item['owner-link'];
1015 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1017 $datarray['author-name'] = $person['name'];
1018 $datarray['author-link'] = $person['url'];
1019 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1020 $datarray['body'] = $body;
1021 $datarray['tag'] = $str_tags;
1023 // We can't be certain what the original app is if the message is relayed.
1024 if(($parent_item['origin']) && (! $parent_author_signature))
1025 $datarray['app'] = 'Diaspora';
1027 $message_id = item_store($datarray);
1030 q("update item set plink = '%s' where id = %d limit 1",
1031 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1036 if(($parent_item['origin']) && (! $parent_author_signature)) {
1037 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1038 intval($message_id),
1039 dbesc($author_signed_data),
1040 dbesc(base64_encode($author_signature)),
1041 dbesc($diaspora_handle)
1044 // if the message isn't already being relayed, notify others
1045 // the existence of parent_author_signature means the parent_author or owner
1046 // is already relaying.
1048 proc_run('php','include/notifier.php','comment',$message_id);
1053 function diaspora_photo($importer,$xml,$msg) {
1056 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1058 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1060 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1062 $guid = notags(unxmlify($xml->guid));
1064 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1066 $public = notags(unxmlify($xml->public));
1068 $created_at = notags(unxmlify($xml_created_at));
1071 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1075 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1076 logger('diaspora_photo: Ignoring this author.');
1080 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1081 intval($importer['uid']),
1082 dbesc($status_message_guid)
1085 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1088 $parent_item = $r[0];
1090 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1092 $link_text = scale_diaspora_images($link_text);
1094 if(strpos($parent_item['body'],$link_text) === false) {
1095 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1096 dbesc($link_text . $parent_item['body']),
1097 intval($parent_item['id']),
1098 intval($parent_item['uid'])
1108 function diaspora_like($importer,$xml,$msg) {
1111 $guid = notags(unxmlify($xml->guid));
1112 $parent_guid = notags(unxmlify($xml->parent_guid));
1113 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1114 $target_type = notags(unxmlify($xml->target_type));
1115 $positive = notags(unxmlify($xml->positive));
1116 $author_signature = notags(unxmlify($xml->author_signature));
1118 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1120 // likes on comments not supported here and likes on photos not supported by Diaspora
1122 if($target_type !== 'Post')
1125 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1127 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1131 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1132 logger('diaspora_like: Ignoring this author.');
1136 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1137 intval($importer['uid']),
1141 logger('diaspora_like: parent item not found: ' . $guid);
1145 $parent_item = $r[0];
1147 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1148 intval($importer['uid']),
1152 if($positive === 'true') {
1153 logger('diaspora_like: duplicate like: ' . $guid);
1156 if($positive === 'false') {
1157 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1158 intval($r[0]['id']),
1159 intval($importer['uid'])
1162 // send notification via proc_run()
1166 if($positive === 'false') {
1167 logger('diaspora_like: unlike received with no corresponding like');
1171 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1173 $author_signature = base64_decode($author_signature);
1175 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1180 $person = find_diaspora_person_by_handle($diaspora_handle);
1181 if(is_array($person) && x($person,'pubkey'))
1182 $key = $person['pubkey'];
1184 logger('diaspora_like: unable to find author details');
1189 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1190 logger('diaspora_like: verification failed.');
1194 if($parent_author_signature) {
1196 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1198 $parent_author_signature = base64_decode($parent_author_signature);
1202 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1203 logger('diaspora_like: owner verification failed.');
1208 // Phew! Everything checks out. Now create an item.
1210 $uri = $diaspora_handle . ':' . $guid;
1212 $activity = ACTIVITY_LIKE;
1213 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1214 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1215 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1216 $body = $parent_item['body'];
1221 <type>$objtype</type>
1223 <id>{$parent_item['uri']}</id>
1226 <content>$body</content>
1229 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1234 $arr['uid'] = $importer['uid'];
1235 $arr['guid'] = $guid;
1236 $arr['contact-id'] = $contact['id'];
1237 $arr['type'] = 'activity';
1238 $arr['wall'] = $parent_item['wall'];
1239 $arr['gravity'] = GRAVITY_LIKE;
1240 $arr['parent'] = $parent_item['id'];
1241 $arr['parent-uri'] = $parent_item['uri'];
1243 $arr['owner-name'] = $parent_item['name'];
1244 $arr['owner-link'] = $parent_item['url'];
1245 $arr['owner-avatar'] = $parent_item['thumb'];
1247 $arr['author-name'] = $person['name'];
1248 $arr['author-link'] = $person['url'];
1249 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1251 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1252 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1253 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1254 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1256 $arr['app'] = 'Diaspora';
1258 $arr['private'] = $parent_item['private'];
1259 $arr['verb'] = $activity;
1260 $arr['object-type'] = $objtype;
1261 $arr['object'] = $obj;
1262 $arr['visible'] = 1;
1264 $arr['last-child'] = 0;
1266 $message_id = item_store($arr);
1270 q("update item set plink = '%s' where id = %d limit 1",
1271 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1276 if(! $parent_author_signature) {
1277 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1278 intval($message_id),
1279 dbesc($author_signed_data),
1280 dbesc(base64_encode($author_signature)),
1281 dbesc($diaspora_handle)
1285 // if the message isn't already being relayed, notify others
1286 // the existence of parent_author_signature means the parent_author or owner
1287 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1289 if(($parent_item['origin']) && (! $parent_author_signature))
1290 proc_run('php','include/notifier.php','comment',$message_id);
1295 function diaspora_retraction($importer,$xml) {
1297 $guid = notags(unxmlify($xml->guid));
1298 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1299 $type = notags(unxmlify($xml->type));
1301 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1305 if($type === 'Person') {
1306 require_once('include/Contact.php');
1307 contact_remove($contact['id']);
1309 elseif($type === 'Post') {
1310 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1312 intval($importer['uid'])
1315 if(link_compare($r[0]['author-link'],$contact['url'])) {
1316 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1317 dbesc(datetime_convert()),
1328 function diaspora_signed_retraction($importer,$xml) {
1330 $guid = notags(unxmlify($xml->target_guid));
1331 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1332 $type = notags(unxmlify($xml->target_type));
1333 $sig = notags(unxmlify($xml->target_author_signature));
1335 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1339 // this may not yet work for comments. Need to see how the relaying works
1340 // and figure out who signs it.
1343 $signed_data = $guid . ';' . $type ;
1345 $sig = base64_decode($sig);
1349 if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1350 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1354 if($type === 'StatusMessage') {
1355 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1357 intval($importer['uid'])
1360 if(link_compare($r[0]['author-link'],$contact['url'])) {
1361 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1362 dbesc(datetime_convert()),
1373 function diaspora_profile($importer,$xml) {
1376 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1378 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1382 if($contact['blocked']) {
1383 logger('diaspora_post: Ignoring this author.');
1387 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1388 $image_url = unxmlify($xml->image_url);
1389 $birthday = unxmlify($xml->birthday);
1391 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1392 intval($importer['uid']),
1393 intval($contact['id'])
1395 $oldphotos = ((count($r)) ? $r : null);
1397 require_once('include/Photo.php');
1399 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1401 // Generic birthday. We don't know the timezone. The year is irrelevant.
1403 $birthday = str_replace('1000','1901',$birthday);
1405 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1407 $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",
1409 dbesc(datetime_convert()),
1413 dbesc(datetime_convert()),
1415 intval($contact['id']),
1416 intval($importer['uid'])
1421 foreach($oldphotos as $ph) {
1422 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1423 intval($importer['uid']),
1424 intval($contact['id']),
1425 dbesc($ph['resource-id'])
1456 function diaspora_share($me,$contact) {
1458 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1459 $theiraddr = $contact['addr'];
1461 $tpl = get_markup_template('diaspora_share.tpl');
1462 $msg = replace_macros($tpl, array(
1463 '$sender' => $myaddr,
1464 '$recipient' => $theiraddr
1467 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1469 return(diaspora_transmit($owner,$contact,$slap, false));
1472 function diaspora_unshare($me,$contact) {
1475 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1477 $tpl = get_markup_template('diaspora_retract.tpl');
1478 $msg = replace_macros($tpl, array(
1479 '$guid' => $me['guid'],
1480 '$type' => 'Person',
1481 '$handle' => $myaddr
1484 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1486 return(diaspora_transmit($owner,$contact,$slap, false));
1492 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1495 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1496 $theiraddr = $contact['addr'];
1500 $body = $item['body'];
1503 // We're trying to match Diaspora's split message/photo protocol but
1504 // all the photos are displayed on D* as links and not img's - even
1505 // though we're sending pretty much precisely what they send us when
1506 // doing the same operation.
1507 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1508 // which seems to get through intact.
1510 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1512 foreach($matches as $mtch) {
1514 $detail['str'] = $mtch[0];
1515 $detail['path'] = dirname($mtch[1]) . '/';
1516 $detail['file'] = basename($mtch[1]);
1517 $detail['guid'] = $item['guid'];
1518 $detail['handle'] = $myaddr;
1519 $images[] = $detail;
1520 $body = str_replace($detail['str'],$mtch[1],$body);
1525 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1527 if($item['attach']) {
1528 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1530 $body .= "\n" . t('Attachments:') . "\n";
1531 foreach($matches as $mtch) {
1532 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1538 $public = (($item['private']) ? 'false' : 'true');
1540 require_once('include/datetime.php');
1541 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1543 $tpl = get_markup_template('diaspora_post.tpl');
1544 $msg = replace_macros($tpl, array(
1546 '$guid' => $item['guid'],
1547 '$handle' => xmlify($myaddr),
1548 '$public' => $public,
1549 '$created' => $created
1552 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1554 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1556 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1558 if(count($images)) {
1559 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1562 return $return_code;
1566 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1568 if(! count($images))
1570 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1572 $tpl = get_markup_template('diaspora_photo.tpl');
1573 foreach($images as $image) {
1574 if(! stristr($image['path'],$mysite))
1576 $resource = str_replace('.jpg','',$image['file']);
1577 $resource = substr($resource,0,strpos($resource,'-'));
1579 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1581 intval($owner['uid'])
1585 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1586 $msg = replace_macros($tpl,array(
1587 '$path' => xmlify($image['path']),
1588 '$filename' => xmlify($image['file']),
1589 '$msg_guid' => xmlify($image['guid']),
1590 '$guid' => xmlify($r[0]['guid']),
1591 '$handle' => xmlify($image['handle']),
1592 '$public' => xmlify($public),
1593 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1597 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1598 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1600 diaspora_transmit($owner,$contact,$slap,$public_batch);
1605 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1608 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1609 $theiraddr = $contact['addr'];
1611 $p = q("select guid from item where parent = %d limit 1",
1615 $parent_guid = $p[0]['guid'];
1619 if($item['verb'] === ACTIVITY_LIKE) {
1620 $tpl = get_markup_template('diaspora_like.tpl');
1622 $target_type = 'Post';
1623 $positive = (($item['deleted']) ? 'false' : 'true');
1626 $tpl = get_markup_template('diaspora_comment.tpl');
1630 $text = html_entity_decode(bb2diaspora($item['body']));
1635 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1637 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1639 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1641 $msg = replace_macros($tpl,array(
1642 '$guid' => xmlify($item['guid']),
1643 '$parent_guid' => xmlify($parent_guid),
1644 '$target_type' =>xmlify($target_type),
1645 '$authorsig' => xmlify($authorsig),
1646 '$body' => xmlify($text),
1647 '$positive' => xmlify($positive),
1648 '$handle' => xmlify($myaddr)
1651 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1653 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1655 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1659 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1663 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1664 $theiraddr = $contact['addr'];
1667 $p = q("select guid from item where parent = %d limit 1",
1671 $parent_guid = $p[0]['guid'];
1675 if($item['verb'] === ACTIVITY_LIKE) {
1676 $tpl = get_markup_template('diaspora_like_relay.tpl');
1678 $target_type = 'Post';
1679 $positive = (($item['deleted']) ? 'false' : 'true');
1682 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1686 $body = $item['body'];
1688 $text = html_entity_decode(bb2diaspora($body));
1690 // fetch the original signature if somebody sent the post to us to relay
1691 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1692 // action. It wasn't needed. In that case create the original signature and the
1693 // owner (parent author) signature
1694 // comments from other networks will be relayed under our name, with a brief
1695 // preamble to describe what's happening and noting the real author
1697 $r = q("select * from sign where iid = %d limit 1",
1702 $signed_text = $orig_sign['signed_text'];
1703 $authorsig = $orig_sign['signature'];
1704 $handle = $orig_sign['signer'];
1708 $itemcontact = q("select * from contact where `id` = %d limit 1",
1709 intval($item['contact-id'])
1711 if(count($itemcontact)) {
1712 if(! $itemcontact[0]['self']) {
1713 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1714 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1715 network_to_name($itemcontact['network'])) . "\n";
1716 $body = $prefix . $body;
1722 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1724 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1726 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1728 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1729 intval($item['id']),
1730 dbesc($signed_text),
1731 dbesc(base64_encode($authorsig)),
1740 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1742 $msg = replace_macros($tpl,array(
1743 '$guid' => xmlify($item['guid']),
1744 '$parent_guid' => xmlify($parent_guid),
1745 '$target_type' =>xmlify($target_type),
1746 '$authorsig' => xmlify($orig_sign['signature']),
1747 '$parentsig' => xmlify($parentauthorsig),
1748 '$body' => xmlify($text),
1749 '$positive' => xmlify($positive),
1750 '$handle' => xmlify($handle)
1753 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1755 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1757 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1763 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1766 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1768 $signed_text = $item['guid'] . ';' . 'StatusMessage';
1770 $tpl = get_markup_template('diaspora_signed_retract.tpl');
1771 $msg = replace_macros($tpl, array(
1772 '$guid' => $item['guid'],
1773 '$type' => 'StatusMessage',
1774 '$handle' => $myaddr,
1775 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1778 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1780 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1785 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1788 $logid = random_string(4);
1789 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
1791 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
1795 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
1797 post_url($dest_url . '/', $slap);
1799 $return_code = $a->get_curl_code();
1800 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1802 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1803 logger('diaspora_transmit: queue message');
1805 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
1806 intval($contact['id']),
1807 dbesc(NETWORK_DIASPORA),
1809 intval($public_batch)
1812 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
1815 // queue message for redelivery
1816 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
1821 return(($return_code) ? $return_code : (-1));