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 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
47 if($xmlbase->request) {
48 $ret = diaspora_request($importer,$xmlbase->request);
50 elseif($xmlbase->status_message) {
51 $ret = diaspora_post($importer,$xmlbase->status_message);
53 elseif($xmlbase->profile) {
54 $ret = diaspora_profile($importer,$xmlbase->profile);
56 elseif($xmlbase->comment) {
57 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
59 elseif($xmlbase->like) {
60 $ret = diaspora_like($importer,$xmlbase->like,$msg);
62 elseif($xmlbase->asphoto) {
63 $ret = diaspora_asphoto($importer,$xmlbase->asphoto);
65 elseif($xmlbase->reshare) {
66 $ret = diaspora_reshare($importer,$xmlbase->reshare);
68 elseif($xmlbase->retraction) {
69 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
71 elseif($xmlbase->signed_retraction) {
72 $ret = diaspora_signed_retraction($importer,$xmlbase->retraction,$msg);
74 elseif($xmlbase->photo) {
75 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
77 elseif($xmlbase->conversation) {
78 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
80 elseif($xmlbase->message) {
81 $ret = diaspora_message($importer,$xmlbase->message,$msg);
84 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
89 function diaspora_get_contact_by_handle($uid,$handle) {
90 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
91 dbesc(NETWORK_DIASPORA),
100 function find_diaspora_person_by_handle($handle) {
102 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
103 dbesc(NETWORK_DIASPORA),
107 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
108 // update record occasionally so it doesn't get stale
109 $d = strtotime($r[0]['updated'] . ' +00:00');
110 if($d > strtotime('now - 14 days'))
114 logger('find_diaspora_person_by_handle: refresh',LOGGER_DEBUG);
115 require_once('include/Scrape.php');
116 $r = probe_url($handle, PROBE_DIASPORA);
117 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
118 add_fcontact($r,$update);
125 function get_diaspora_key($uri) {
126 logger('Fetching diaspora key for: ' . $uri);
128 $r = find_diaspora_person_by_handle($uri);
135 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
138 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
141 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
143 // $b64_data = base64_encode($msg);
144 // $b64url_data = base64url_encode($b64_data);
146 $b64url_data = base64url_encode($msg);
148 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
150 $type = 'application/xml';
151 $encoding = 'base64url';
154 $signable_data = $data . '.' . base64url_encode($type) . '.'
155 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
157 $signature = rsa_sign($signable_data,$prvkey);
158 $sig = base64url_encode($signature);
161 <?xml version='1.0' encoding='UTF-8'?>
162 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
164 <author_id>$handle</author_id>
167 <me:encoding>base64url</me:encoding>
168 <me:alg>RSA-SHA256</me:alg>
169 <me:data type="application/xml">$data</me:data>
170 <me:sig>$sig</me:sig>
175 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
183 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
187 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
189 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
191 $inner_aes_key = random_string(32);
192 $b_inner_aes_key = base64_encode($inner_aes_key);
193 $inner_iv = random_string(16);
194 $b_inner_iv = base64_encode($inner_iv);
196 $outer_aes_key = random_string(32);
197 $b_outer_aes_key = base64_encode($outer_aes_key);
198 $outer_iv = random_string(16);
199 $b_outer_iv = base64_encode($outer_iv);
201 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
203 $padded_data = pkcs5_pad($msg,16);
204 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
206 $b64_data = base64_encode($inner_encrypted);
209 $b64url_data = base64url_encode($b64_data);
210 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
212 $type = 'application/xml';
213 $encoding = 'base64url';
216 $signable_data = $data . '.' . base64url_encode($type) . '.'
217 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
219 $signature = rsa_sign($signable_data,$prvkey);
220 $sig = base64url_encode($signature);
222 $decrypted_header = <<< EOT
225 <aes_key>$b_inner_aes_key</aes_key>
226 <author_id>$handle</author_id>
230 $decrypted_header = pkcs5_pad($decrypted_header,16);
232 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
234 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
236 $encrypted_outer_key_bundle = '';
237 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
239 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
241 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
243 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
244 'ciphertext' => base64_encode($ciphertext)));
245 $cipher_json = base64_encode($encrypted_header_json_object);
247 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
250 <?xml version='1.0' encoding='UTF-8'?>
251 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
254 <me:encoding>base64url</me:encoding>
255 <me:alg>RSA-SHA256</me:alg>
256 <me:data type="application/xml">$data</me:data>
257 <me:sig>$sig</me:sig>
262 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
269 * diaspora_decode($importer,$xml)
270 * array $importer -> from user table
271 * string $xml -> urldecoded Diaspora salmon
274 * 'message' -> decoded Diaspora XML message
275 * 'author' -> author diaspora handle
276 * 'key' -> author public key (converted to pkcs#8)
278 * Author and key are used elsewhere to save a lookup for verifying replies and likes
282 function diaspora_decode($importer,$xml) {
285 $basedom = parse_xml_string($xml);
287 $children = $basedom->children('https://joindiaspora.com/protocol');
289 if($children->header) {
291 $author_link = str_replace('acct:','',$children->header->author_id);
295 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
297 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
298 $ciphertext = base64_decode($encrypted_header->ciphertext);
300 $outer_key_bundle = '';
301 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
303 $j_outer_key_bundle = json_decode($outer_key_bundle);
305 $outer_iv = base64_decode($j_outer_key_bundle->iv);
306 $outer_key = base64_decode($j_outer_key_bundle->key);
308 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
311 $decrypted = pkcs5_unpad($decrypted);
314 * $decrypted now contains something like
317 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
318 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
323 * <name>Ryan Hughes</name>
324 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
329 * <author_id>galaxor@diaspora.priateship.org</author_id>
333 * </decrypted_header>
336 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
337 $idom = parse_xml_string($decrypted,false);
339 $inner_iv = base64_decode($idom->iv);
340 $inner_aes_key = base64_decode($idom->aes_key);
342 $author_link = str_replace('acct:','',$idom->author_id);
346 $dom = $basedom->children(NAMESPACE_SALMON_ME);
348 // figure out where in the DOM tree our data is hiding
350 if($dom->provenance->data)
351 $base = $dom->provenance;
352 elseif($dom->env->data)
358 logger('mod-diaspora: unable to locate salmon data in xml ');
359 http_status_exit(400);
363 // Stash the signature away for now. We have to find their key or it won't be good for anything.
364 $signature = base64url_decode($base->sig);
368 // strip whitespace so our data element will return to one big base64 blob
369 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
372 // stash away some other stuff for later
374 $type = $base->data[0]->attributes()->type[0];
375 $keyhash = $base->sig[0]->attributes()->keyhash[0];
376 $encoding = $base->encoding;
380 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
384 $data = base64url_decode($data);
388 $inner_decrypted = $data;
392 // Decode the encrypted blob
394 $inner_encrypted = base64_decode($data);
395 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
396 $inner_decrypted = pkcs5_unpad($inner_decrypted);
400 logger('mod-diaspora: Could not retrieve author URI.');
401 http_status_exit(400);
404 // Once we have the author URI, go to the web and try to find their public key
405 // (first this will look it up locally if it is in the fcontact cache)
406 // This will also convert diaspora public key from pkcs#1 to pkcs#8
408 logger('mod-diaspora: Fetching key for ' . $author_link );
409 $key = get_diaspora_key($author_link);
412 logger('mod-diaspora: Could not retrieve author key.');
413 http_status_exit(400);
416 $verify = rsa_verify($signed_data,$signature,$key);
419 logger('mod-diaspora: Message did not verify. Discarding.');
420 http_status_exit(400);
423 logger('mod-diaspora: Message verified.');
425 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
430 function diaspora_request($importer,$xml) {
434 $sender_handle = unxmlify($xml->sender_handle);
435 $recipient_handle = unxmlify($xml->recipient_handle);
437 if(! $sender_handle || ! $recipient_handle)
440 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
444 // perhaps we were already sharing with this person. Now they're sharing with us.
445 // That makes us friends.
447 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
448 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
449 intval(CONTACT_IS_FRIEND),
450 intval($contact['id']),
451 intval($importer['uid'])
456 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
457 intval($importer['uid'])
460 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
461 require_once('include/items.php');
463 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
464 intval($importer['uid'])
467 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
469 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
472 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
473 $arr['uid'] = $importer['uid'];
474 $arr['contact-id'] = $self[0]['id'];
476 $arr['type'] = 'wall';
479 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
480 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
481 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
482 $arr['verb'] = ACTIVITY_FRIEND;
483 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
485 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
486 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
487 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
488 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
490 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
491 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
492 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
493 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
494 $arr['object'] .= '</link></object>' . "\n";
495 $arr['last-child'] = 1;
497 $arr['allow_cid'] = $user[0]['allow_cid'];
498 $arr['allow_gid'] = $user[0]['allow_gid'];
499 $arr['deny_cid'] = $user[0]['deny_cid'];
500 $arr['deny_gid'] = $user[0]['deny_gid'];
502 $i = item_store($arr);
504 proc_run('php',"include/notifier.php","activity","$i");
513 $ret = find_diaspora_person_by_handle($sender_handle);
516 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
517 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
521 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
523 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
524 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
525 intval($importer['uid']),
526 dbesc($ret['network']),
530 dbesc(normalise_link($ret['url'])),
534 dbesc($ret['photo']),
535 dbesc($ret['pubkey']),
536 dbesc($ret['notify']),
542 // find the contact record we just created
544 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
546 $hash = random_string() . (string) time(); // Generate a confirm_key
548 if($contact_record) {
549 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
550 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
551 intval($importer['uid']),
552 intval($contact_record['id']),
555 dbesc( t('Sharing notification from Diaspora network')),
557 dbesc(datetime_convert())
564 function diaspora_post($importer,$xml) {
567 $guid = notags(unxmlify($xml->guid));
568 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
570 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
574 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
575 logger('diaspora_post: Ignoring this author.');
579 $message_id = $diaspora_handle . ':' . $guid;
580 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
581 intval($importer['uid']),
586 logger('diaspora_post: message exists: ' . $guid);
590 // allocate a guid on our system - we aren't fixing any collisions.
591 // we're ignoring them
593 $g = q("select * from guid where guid = '%s' limit 1",
597 q("insert into guid ( guid ) values ( '%s' )",
602 $created = unxmlify($xml->created_at);
603 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
605 $body = diaspora2bb($xml->raw_message);
611 $tags = get_tags($body);
614 foreach($tags as $tag) {
615 if(strpos($tag,'#') === 0) {
616 if(strpos($tag,'[url='))
618 $basetag = str_replace('_',' ',substr($tag,1));
619 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
620 if(strlen($str_tags))
622 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
628 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
630 foreach($matches as $mtch) {
631 if(strlen($str_tags))
633 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
637 $datarray['uid'] = $importer['uid'];
638 $datarray['contact-id'] = $contact['id'];
639 $datarray['wall'] = 0;
640 $datarray['guid'] = $guid;
641 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
642 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
643 $datarray['private'] = $private;
644 $datarray['parent'] = 0;
645 $datarray['owner-name'] = $contact['name'];
646 $datarray['owner-link'] = $contact['url'];
647 $datarray['owner-avatar'] = $contact['thumb'];
648 $datarray['author-name'] = $contact['name'];
649 $datarray['author-link'] = $contact['url'];
650 $datarray['author-avatar'] = $contact['thumb'];
651 $datarray['body'] = $body;
652 $datarray['tag'] = $str_tags;
653 $datarray['app'] = 'Diaspora';
655 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
657 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
659 $message_id = item_store($datarray);
662 q("update item set plink = '%s' where id = %d limit 1",
663 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
672 function diaspora_reshare($importer,$xml) {
674 logger('diaspora_reshare: init: ' . print_r($xml,true));
677 $guid = notags(unxmlify($xml->guid));
678 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
681 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
685 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
686 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
690 $message_id = $diaspora_handle . ':' . $guid;
691 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
692 intval($importer['uid']),
697 logger('diaspora_reshare: message exists: ' . $guid);
701 $orig_author = notags(unxmlify($xml->root_diaspora_id));
702 $orig_guid = notags(unxmlify($xml->root_guid));
704 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
705 $x = fetch_url($source_url);
707 $x = fetch_url(str_replace('https://','http://',$source_url));
709 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
712 logger('diaspora_reshare: source: ' . $x);
714 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
715 $source_xml = parse_xml_string($x,false);
717 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
718 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
719 $body = scale_diaspora_images($body,false);
721 elseif($source_xml->post->asphoto->image_url) {
722 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
723 $body = scale_diaspora_images($body);
725 elseif($source_xml->post->status_message) {
726 $body = diaspora2bb($source_xml->post->status_message->raw_message);
727 $body = scale_diaspora_images($body);
731 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
735 logger('diaspora_reshare: empty body: source= ' . $x);
739 $person = find_diaspora_person_by_handle($orig_author);
741 if(is_array($person) && x($person,'name') && x($person,'url'))
742 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
744 $details = $orig_author;
746 $prefix = '♲ ' . $details . "\n";
749 // allocate a guid on our system - we aren't fixing any collisions.
750 // we're ignoring them
752 $g = q("select * from guid where guid = '%s' limit 1",
756 q("insert into guid ( guid ) values ( '%s' )",
761 $created = unxmlify($xml->created_at);
762 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
768 $tags = get_tags($body);
771 foreach($tags as $tag) {
772 if(strpos($tag,'#') === 0) {
773 if(strpos($tag,'[url='))
775 $basetag = str_replace('_',' ',substr($tag,1));
776 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
777 if(strlen($str_tags))
779 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
785 $datarray['uid'] = $importer['uid'];
786 $datarray['contact-id'] = $contact['id'];
787 $datarray['wall'] = 0;
788 $datarray['guid'] = $guid;
789 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
790 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
791 $datarray['private'] = $private;
792 $datarray['parent'] = 0;
793 $datarray['owner-name'] = $contact['name'];
794 $datarray['owner-link'] = $contact['url'];
795 $datarray['owner-avatar'] = $contact['thumb'];
796 $datarray['author-name'] = $contact['name'];
797 $datarray['author-link'] = $contact['url'];
798 $datarray['author-avatar'] = $contact['thumb'];
799 $datarray['body'] = $prefix . $body;
800 $datarray['tag'] = $str_tags;
801 $datarray['app'] = 'Diaspora';
803 $message_id = item_store($datarray);
806 q("update item set plink = '%s' where id = %d limit 1",
807 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
817 function diaspora_asphoto($importer,$xml) {
818 logger('diaspora_asphoto called');
821 $guid = notags(unxmlify($xml->guid));
822 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
824 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
828 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
829 logger('diaspora_asphoto: Ignoring this author.');
833 $message_id = $diaspora_handle . ':' . $guid;
834 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
835 intval($importer['uid']),
840 logger('diaspora_asphoto: message exists: ' . $guid);
844 // allocate a guid on our system - we aren't fixing any collisions.
845 // we're ignoring them
847 $g = q("select * from guid where guid = '%s' limit 1",
851 q("insert into guid ( guid ) values ( '%s' )",
856 $created = unxmlify($xml->created_at);
857 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
859 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
860 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
861 $body = scale_diaspora_images($body,false);
863 elseif($xml->image_url) {
864 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
865 $body = scale_diaspora_images($body);
868 logger('diaspora_asphoto: no photo url found.');
875 $datarray['uid'] = $importer['uid'];
876 $datarray['contact-id'] = $contact['id'];
877 $datarray['wall'] = 0;
878 $datarray['guid'] = $guid;
879 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
880 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
881 $datarray['private'] = $private;
882 $datarray['parent'] = 0;
883 $datarray['owner-name'] = $contact['name'];
884 $datarray['owner-link'] = $contact['url'];
885 $datarray['owner-avatar'] = $contact['thumb'];
886 $datarray['author-name'] = $contact['name'];
887 $datarray['author-link'] = $contact['url'];
888 $datarray['author-avatar'] = $contact['thumb'];
889 $datarray['body'] = $body;
891 $datarray['app'] = 'Diaspora/Cubbi.es';
893 $message_id = item_store($datarray);
896 q("update item set plink = '%s' where id = %d limit 1",
897 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
911 function diaspora_comment($importer,$xml,$msg) {
914 $guid = notags(unxmlify($xml->guid));
915 $parent_guid = notags(unxmlify($xml->parent_guid));
916 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
917 $target_type = notags(unxmlify($xml->target_type));
918 $text = unxmlify($xml->text);
919 $author_signature = notags(unxmlify($xml->author_signature));
921 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
923 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
925 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
929 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
930 logger('diaspora_comment: Ignoring this author.');
934 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
935 intval($importer['uid']),
939 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
943 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
944 intval($importer['uid']),
948 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
951 $parent_item = $r[0];
953 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
955 $author_signature = base64_decode($author_signature);
957 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
962 $person = find_diaspora_person_by_handle($diaspora_handle);
964 if(is_array($person) && x($person,'pubkey'))
965 $key = $person['pubkey'];
967 logger('diaspora_comment: unable to find author details');
972 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
973 logger('diaspora_comment: verification failed.');
977 if($parent_author_signature) {
978 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
980 $parent_author_signature = base64_decode($parent_author_signature);
984 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
985 logger('diaspora_comment: owner verification failed.');
990 // Phew! Everything checks out. Now create an item.
992 $body = diaspora2bb($text);
994 $message_id = $diaspora_handle . ':' . $guid;
1000 $tags = get_tags($body);
1003 foreach($tags as $tag) {
1004 if(strpos($tag,'#') === 0) {
1005 if(strpos($tag,'[url='))
1007 $basetag = str_replace('_',' ',substr($tag,1));
1008 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1009 if(strlen($str_tags))
1011 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1017 $datarray['uid'] = $importer['uid'];
1018 $datarray['contact-id'] = $contact['id'];
1019 $datarray['wall'] = $parent_item['wall'];
1020 $datarray['gravity'] = GRAVITY_COMMENT;
1021 $datarray['guid'] = $guid;
1022 $datarray['uri'] = $message_id;
1023 $datarray['parent-uri'] = $parent_item['uri'];
1025 // No timestamps for comments? OK, we'll the use current time.
1026 $datarray['created'] = $datarray['edited'] = datetime_convert();
1027 $datarray['private'] = $parent_item['private'];
1029 $datarray['owner-name'] = $parent_item['owner-name'];
1030 $datarray['owner-link'] = $parent_item['owner-link'];
1031 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1033 $datarray['author-name'] = $person['name'];
1034 $datarray['author-link'] = $person['url'];
1035 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1036 $datarray['body'] = $body;
1037 $datarray['tag'] = $str_tags;
1039 // We can't be certain what the original app is if the message is relayed.
1040 if(($parent_item['origin']) && (! $parent_author_signature))
1041 $datarray['app'] = 'Diaspora';
1043 $message_id = item_store($datarray);
1046 q("update item set plink = '%s' where id = %d limit 1",
1047 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1052 if(($parent_item['origin']) && (! $parent_author_signature)) {
1053 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1054 intval($message_id),
1055 dbesc($author_signed_data),
1056 dbesc(base64_encode($author_signature)),
1057 dbesc($diaspora_handle)
1060 // if the message isn't already being relayed, notify others
1061 // the existence of parent_author_signature means the parent_author or owner
1062 // is already relaying.
1064 proc_run('php','include/notifier.php','comment',$message_id);
1072 function diaspora_conversation($importer,$xml,$msg) {
1076 $guid = notags(unxmlify($xml->guid));
1077 $subject = notags(unxmlify($xml->subject));
1078 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1079 $participant_handles = notags(unxmlify($xml->participant_handles));
1080 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1082 $parent_uri = $diaspora_handle . ':' . $guid;
1084 $messages = $xml->message;
1086 if(! count($messages)) {
1087 logger('diaspora_conversation: empty conversation');
1091 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1093 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1097 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1098 logger('diaspora_conversation: Ignoring this author.');
1102 $conversation = null;
1104 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1105 intval($importer['uid']),
1109 $conversation = $c[0];
1111 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1112 intval($importer['uid']),
1114 dbesc($diaspora_handle),
1115 dbesc(datetime_convert('UTC','UTC',$created_at)),
1116 dbesc(datetime_convert()),
1118 dbesc($participant_handles)
1121 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1122 intval($importer['uid']),
1126 $conversation = $c[0];
1128 if(! $conversation) {
1129 logger('diaspora_conversation: unable to create conversation.');
1133 foreach($messages as $mesg) {
1137 $msg_guid = notags(unxmlify($mesg->guid));
1138 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1139 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1140 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1141 $msg_text = unxmlify($mesg->text);
1142 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1143 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1144 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1145 if($msg_conversation_guid != $guid) {
1146 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1150 $body = diaspora2bb($msg_text);
1151 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1153 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1155 $author_signature = base64_decode($msg_author_signature);
1157 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1162 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1164 if(is_array($person) && x($person,'pubkey'))
1165 $key = $person['pubkey'];
1167 logger('diaspora_conversation: unable to find author details');
1172 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1173 logger('diaspora_conversation: verification failed.');
1177 if($msg_parent_author_signature) {
1178 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1180 $parent_author_signature = base64_decode($msg_parent_author_signature);
1184 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1185 logger('diaspora_conversation: owner verification failed.');
1190 $r = q("select id from mail where `uri` = '%s' limit 1",
1194 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1198 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1199 intval($importer['uid']),
1201 intval($conversation['id']),
1202 dbesc($person['name']),
1203 dbesc($person['photo']),
1204 dbesc($person['url']),
1205 intval($contact['id']),
1212 dbesc($msg_created_at)
1215 q("update conv set updated = '%s' where id = %d limit 1",
1216 dbesc(datetime_convert()),
1217 intval($conversation['id'])
1224 function diaspora_message($importer,$xml,$msg) {
1228 $msg_guid = notags(unxmlify($xml->guid));
1229 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1230 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1231 $msg_author_signature = notags(unxmlify($xml->author_signature));
1232 $msg_text = unxmlify($xml->text);
1233 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1234 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1235 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1237 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1239 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1241 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1245 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1246 logger('diaspora_message: Ignoring this author.');
1250 $conversation = null;
1252 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1253 intval($importer['uid']),
1254 dbesc($msg_conversation_guid)
1257 $conversation = $c[0];
1259 logger('diaspora_message: conversation not available.');
1265 $body = diaspora2bb($msg_text);
1266 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1268 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1271 $author_signature = base64_decode($msg_author_signature);
1273 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1274 if(is_array($person) && x($person,'pubkey'))
1275 $key = $person['pubkey'];
1277 logger('diaspora_message: unable to find author details');
1281 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1282 logger('diaspora_message: verification failed.');
1286 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1288 intval($importer['uid'])
1291 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1295 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1296 intval($importer['uid']),
1298 intval($conversation['id']),
1299 dbesc($person['name']),
1300 dbesc($person['photo']),
1301 dbesc($person['url']),
1302 intval($contact['id']),
1303 dbesc($conversation['subject']),
1309 dbesc($msg_created_at)
1312 q("update conv set updated = '%s' where id = %d limit 1",
1313 dbesc(datetime_convert()),
1314 intval($conversation['id'])
1321 function diaspora_photo($importer,$xml,$msg) {
1324 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1326 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1328 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1330 $guid = notags(unxmlify($xml->guid));
1332 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1334 $public = notags(unxmlify($xml->public));
1336 $created_at = notags(unxmlify($xml_created_at));
1339 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1343 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1344 logger('diaspora_photo: Ignoring this author.');
1348 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1349 intval($importer['uid']),
1350 dbesc($status_message_guid)
1353 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1356 $parent_item = $r[0];
1358 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1360 $link_text = scale_diaspora_images($link_text);
1362 if(strpos($parent_item['body'],$link_text) === false) {
1363 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1364 dbesc($link_text . $parent_item['body']),
1365 intval($parent_item['id']),
1366 intval($parent_item['uid'])
1376 function diaspora_like($importer,$xml,$msg) {
1379 $guid = notags(unxmlify($xml->guid));
1380 $parent_guid = notags(unxmlify($xml->parent_guid));
1381 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1382 $target_type = notags(unxmlify($xml->target_type));
1383 $positive = notags(unxmlify($xml->positive));
1384 $author_signature = notags(unxmlify($xml->author_signature));
1386 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1388 // likes on comments not supported here and likes on photos not supported by Diaspora
1390 if($target_type !== 'Post')
1393 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1395 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1399 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1400 logger('diaspora_like: Ignoring this author.');
1404 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1405 intval($importer['uid']),
1409 logger('diaspora_like: parent item not found: ' . $guid);
1413 $parent_item = $r[0];
1415 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1416 intval($importer['uid']),
1420 if($positive === 'true') {
1421 logger('diaspora_like: duplicate like: ' . $guid);
1424 if($positive === 'false') {
1425 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1426 intval($r[0]['id']),
1427 intval($importer['uid'])
1430 // send notification via proc_run()
1434 if($positive === 'false') {
1435 logger('diaspora_like: unlike received with no corresponding like');
1439 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1441 $author_signature = base64_decode($author_signature);
1443 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1448 $person = find_diaspora_person_by_handle($diaspora_handle);
1449 if(is_array($person) && x($person,'pubkey'))
1450 $key = $person['pubkey'];
1452 logger('diaspora_like: unable to find author details');
1457 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1458 logger('diaspora_like: verification failed.');
1462 if($parent_author_signature) {
1464 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1466 $parent_author_signature = base64_decode($parent_author_signature);
1470 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1471 logger('diaspora_like: owner verification failed.');
1476 // Phew! Everything checks out. Now create an item.
1478 $uri = $diaspora_handle . ':' . $guid;
1480 $activity = ACTIVITY_LIKE;
1481 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1482 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1483 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1484 $body = $parent_item['body'];
1489 <type>$objtype</type>
1491 <id>{$parent_item['uri']}</id>
1494 <content>$body</content>
1497 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1502 $arr['uid'] = $importer['uid'];
1503 $arr['guid'] = $guid;
1504 $arr['contact-id'] = $contact['id'];
1505 $arr['type'] = 'activity';
1506 $arr['wall'] = $parent_item['wall'];
1507 $arr['gravity'] = GRAVITY_LIKE;
1508 $arr['parent'] = $parent_item['id'];
1509 $arr['parent-uri'] = $parent_item['uri'];
1511 $arr['owner-name'] = $parent_item['name'];
1512 $arr['owner-link'] = $parent_item['url'];
1513 $arr['owner-avatar'] = $parent_item['thumb'];
1515 $arr['author-name'] = $person['name'];
1516 $arr['author-link'] = $person['url'];
1517 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1519 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1520 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1521 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1522 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1524 $arr['app'] = 'Diaspora';
1526 $arr['private'] = $parent_item['private'];
1527 $arr['verb'] = $activity;
1528 $arr['object-type'] = $objtype;
1529 $arr['object'] = $obj;
1530 $arr['visible'] = 1;
1532 $arr['last-child'] = 0;
1534 $message_id = item_store($arr);
1538 q("update item set plink = '%s' where id = %d limit 1",
1539 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1544 if(! $parent_author_signature) {
1545 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1546 intval($message_id),
1547 dbesc($author_signed_data),
1548 dbesc(base64_encode($author_signature)),
1549 dbesc($diaspora_handle)
1553 // if the message isn't already being relayed, notify others
1554 // the existence of parent_author_signature means the parent_author or owner
1555 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1557 if(($parent_item['origin']) && (! $parent_author_signature))
1558 proc_run('php','include/notifier.php','comment',$message_id);
1563 function diaspora_retraction($importer,$xml) {
1565 $guid = notags(unxmlify($xml->guid));
1566 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1567 $type = notags(unxmlify($xml->type));
1569 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1573 if($type === 'Person') {
1574 require_once('include/Contact.php');
1575 contact_remove($contact['id']);
1577 elseif($type === 'Post') {
1578 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1580 intval($importer['uid'])
1583 if(link_compare($r[0]['author-link'],$contact['url'])) {
1584 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1585 dbesc(datetime_convert()),
1596 function diaspora_signed_retraction($importer,$xml) {
1598 $guid = notags(unxmlify($xml->target_guid));
1599 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1600 $type = notags(unxmlify($xml->target_type));
1601 $sig = notags(unxmlify($xml->target_author_signature));
1603 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1607 // this may not yet work for comments. Need to see how the relaying works
1608 // and figure out who signs it.
1611 $signed_data = $guid . ';' . $type ;
1613 $sig = base64_decode($sig);
1617 if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1618 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1622 if($type === 'StatusMessage') {
1623 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1625 intval($importer['uid'])
1628 if(link_compare($r[0]['author-link'],$contact['url'])) {
1629 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1630 dbesc(datetime_convert()),
1641 function diaspora_profile($importer,$xml) {
1644 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1646 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1650 if($contact['blocked']) {
1651 logger('diaspora_post: Ignoring this author.');
1655 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1656 $image_url = unxmlify($xml->image_url);
1657 $birthday = unxmlify($xml->birthday);
1659 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1660 intval($importer['uid']),
1661 intval($contact['id'])
1663 $oldphotos = ((count($r)) ? $r : null);
1665 require_once('include/Photo.php');
1667 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1669 // Generic birthday. We don't know the timezone. The year is irrelevant.
1671 $birthday = str_replace('1000','1901',$birthday);
1673 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1675 $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",
1677 dbesc(datetime_convert()),
1681 dbesc(datetime_convert()),
1683 intval($contact['id']),
1684 intval($importer['uid'])
1689 foreach($oldphotos as $ph) {
1690 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1691 intval($importer['uid']),
1692 intval($contact['id']),
1693 dbesc($ph['resource-id'])
1724 function diaspora_share($me,$contact) {
1726 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1727 $theiraddr = $contact['addr'];
1729 $tpl = get_markup_template('diaspora_share.tpl');
1730 $msg = replace_macros($tpl, array(
1731 '$sender' => $myaddr,
1732 '$recipient' => $theiraddr
1735 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1737 return(diaspora_transmit($owner,$contact,$slap, false));
1740 function diaspora_unshare($me,$contact) {
1743 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1745 $tpl = get_markup_template('diaspora_retract.tpl');
1746 $msg = replace_macros($tpl, array(
1747 '$guid' => $me['guid'],
1748 '$type' => 'Person',
1749 '$handle' => $myaddr
1752 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1754 return(diaspora_transmit($owner,$contact,$slap, false));
1760 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1763 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1764 $theiraddr = $contact['addr'];
1768 $body = $item['body'];
1771 // We're trying to match Diaspora's split message/photo protocol but
1772 // all the photos are displayed on D* as links and not img's - even
1773 // though we're sending pretty much precisely what they send us when
1774 // doing the same operation.
1775 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1776 // which seems to get through intact.
1778 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1780 foreach($matches as $mtch) {
1782 $detail['str'] = $mtch[0];
1783 $detail['path'] = dirname($mtch[1]) . '/';
1784 $detail['file'] = basename($mtch[1]);
1785 $detail['guid'] = $item['guid'];
1786 $detail['handle'] = $myaddr;
1787 $images[] = $detail;
1788 $body = str_replace($detail['str'],$mtch[1],$body);
1793 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1795 if($item['attach']) {
1796 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1798 $body .= "\n" . t('Attachments:') . "\n";
1799 foreach($matches as $mtch) {
1800 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1806 $public = (($item['private']) ? 'false' : 'true');
1808 require_once('include/datetime.php');
1809 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1811 $tpl = get_markup_template('diaspora_post.tpl');
1812 $msg = replace_macros($tpl, array(
1814 '$guid' => $item['guid'],
1815 '$handle' => xmlify($myaddr),
1816 '$public' => $public,
1817 '$created' => $created
1820 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1822 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1824 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1826 if(count($images)) {
1827 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1830 return $return_code;
1834 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1836 if(! count($images))
1838 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1840 $tpl = get_markup_template('diaspora_photo.tpl');
1841 foreach($images as $image) {
1842 if(! stristr($image['path'],$mysite))
1844 $resource = str_replace('.jpg','',$image['file']);
1845 $resource = substr($resource,0,strpos($resource,'-'));
1847 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1849 intval($owner['uid'])
1853 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1854 $msg = replace_macros($tpl,array(
1855 '$path' => xmlify($image['path']),
1856 '$filename' => xmlify($image['file']),
1857 '$msg_guid' => xmlify($image['guid']),
1858 '$guid' => xmlify($r[0]['guid']),
1859 '$handle' => xmlify($image['handle']),
1860 '$public' => xmlify($public),
1861 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1865 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1866 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1868 diaspora_transmit($owner,$contact,$slap,$public_batch);
1873 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1876 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1877 $theiraddr = $contact['addr'];
1879 $p = q("select guid from item where parent = %d limit 1",
1883 $parent_guid = $p[0]['guid'];
1887 if($item['verb'] === ACTIVITY_LIKE) {
1888 $tpl = get_markup_template('diaspora_like.tpl');
1890 $target_type = 'Post';
1891 $positive = (($item['deleted']) ? 'false' : 'true');
1894 $tpl = get_markup_template('diaspora_comment.tpl');
1898 $text = html_entity_decode(bb2diaspora($item['body']));
1903 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1905 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1907 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1909 $msg = replace_macros($tpl,array(
1910 '$guid' => xmlify($item['guid']),
1911 '$parent_guid' => xmlify($parent_guid),
1912 '$target_type' =>xmlify($target_type),
1913 '$authorsig' => xmlify($authorsig),
1914 '$body' => xmlify($text),
1915 '$positive' => xmlify($positive),
1916 '$handle' => xmlify($myaddr)
1919 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1921 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1923 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1927 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1931 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1932 $theiraddr = $contact['addr'];
1935 $p = q("select guid from item where parent = %d limit 1",
1939 $parent_guid = $p[0]['guid'];
1943 if($item['verb'] === ACTIVITY_LIKE) {
1944 $tpl = get_markup_template('diaspora_like_relay.tpl');
1946 $target_type = 'Post';
1947 $positive = (($item['deleted']) ? 'false' : 'true');
1950 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1954 $body = $item['body'];
1956 $text = html_entity_decode(bb2diaspora($body));
1958 // fetch the original signature if somebody sent the post to us to relay
1959 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1960 // action. It wasn't needed. In that case create the original signature and the
1961 // owner (parent author) signature
1962 // comments from other networks will be relayed under our name, with a brief
1963 // preamble to describe what's happening and noting the real author
1965 $r = q("select * from sign where iid = %d limit 1",
1970 $signed_text = $orig_sign['signed_text'];
1971 $authorsig = $orig_sign['signature'];
1972 $handle = $orig_sign['signer'];
1976 $itemcontact = q("select * from contact where `id` = %d limit 1",
1977 intval($item['contact-id'])
1979 if(count($itemcontact)) {
1980 if(! $itemcontact[0]['self']) {
1981 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1982 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1983 network_to_name($itemcontact['network'])) . "\n";
1984 $body = $prefix . $body;
1990 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1992 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1994 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1996 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1997 intval($item['id']),
1998 dbesc($signed_text),
1999 dbesc(base64_encode($authorsig)),
2008 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2010 $msg = replace_macros($tpl,array(
2011 '$guid' => xmlify($item['guid']),
2012 '$parent_guid' => xmlify($parent_guid),
2013 '$target_type' =>xmlify($target_type),
2014 '$authorsig' => xmlify($orig_sign['signature']),
2015 '$parentsig' => xmlify($parentauthorsig),
2016 '$body' => xmlify($text),
2017 '$positive' => xmlify($positive),
2018 '$handle' => xmlify($handle)
2021 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
2023 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2025 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2031 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2034 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2036 $signed_text = $item['guid'] . ';' . 'StatusMessage';
2038 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2039 $msg = replace_macros($tpl, array(
2040 '$guid' => $item['guid'],
2041 '$type' => 'StatusMessage',
2042 '$handle' => $myaddr,
2043 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
2046 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2048 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2051 function diaspora_send_mail($item,$owner,$contact) {
2054 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2056 $r = q("select * from conv where id = %d and uid = %d limit 1",
2057 intval($item['convid']),
2058 intval($item['uid'])
2062 logger('diaspora_send_mail: conversation not found.');
2068 'guid' => xmlify($cnv['guid']),
2069 'subject' => xmlify($cnv['subject']),
2070 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2071 'diaspora_handle' => xmlify($cnv['creator']),
2072 'participant_handles' => xmlify($cnv['recips'])
2075 $body = bb2diaspora($item['body']);
2076 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2078 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2079 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2081 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2084 'guid' => xmlify($item['guid']),
2085 'parent_guid' => xmlify($cnv['guid']),
2086 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2087 'author_signature' => xmlify($sig),
2088 'text' => xmlify($body),
2089 'created_at' => xmlify($created),
2090 'diaspora_handle' => xmlify($myaddr),
2091 'conversation_guid' => xmlify($cnv['guid'])
2094 if($item['reply']) {
2095 $tpl = get_markup_template('diaspora_message.tpl');
2096 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2099 $conv['messages'] = array($msg);
2100 $tpl = get_markup_template('diaspora_conversation.tpl');
2101 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2104 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2106 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2108 return(diaspora_transmit($owner,$contact,$slap,false));
2113 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
2116 $logid = random_string(4);
2117 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2119 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2123 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2125 post_url($dest_url . '/', $slap);
2127 $return_code = $a->get_curl_code();
2128 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2130 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2131 logger('diaspora_transmit: queue message');
2133 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2134 intval($contact['id']),
2135 dbesc(NETWORK_DIASPORA),
2137 intval($public_batch)
2140 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2143 // queue message for redelivery
2144 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2149 return(($return_code) ? $return_code : (-1));