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 // without a public key nothing will work
194 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
198 $inner_aes_key = random_string(32);
199 $b_inner_aes_key = base64_encode($inner_aes_key);
200 $inner_iv = random_string(16);
201 $b_inner_iv = base64_encode($inner_iv);
203 $outer_aes_key = random_string(32);
204 $b_outer_aes_key = base64_encode($outer_aes_key);
205 $outer_iv = random_string(16);
206 $b_outer_iv = base64_encode($outer_iv);
208 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
210 $padded_data = pkcs5_pad($msg,16);
211 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
213 $b64_data = base64_encode($inner_encrypted);
216 $b64url_data = base64url_encode($b64_data);
217 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
219 $type = 'application/xml';
220 $encoding = 'base64url';
223 $signable_data = $data . '.' . base64url_encode($type) . '.'
224 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
226 $signature = rsa_sign($signable_data,$prvkey);
227 $sig = base64url_encode($signature);
229 $decrypted_header = <<< EOT
232 <aes_key>$b_inner_aes_key</aes_key>
233 <author_id>$handle</author_id>
237 $decrypted_header = pkcs5_pad($decrypted_header,16);
239 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
241 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
243 $encrypted_outer_key_bundle = '';
244 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
246 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
248 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
250 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
251 'ciphertext' => base64_encode($ciphertext)));
252 $cipher_json = base64_encode($encrypted_header_json_object);
254 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
257 <?xml version='1.0' encoding='UTF-8'?>
258 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
261 <me:encoding>base64url</me:encoding>
262 <me:alg>RSA-SHA256</me:alg>
263 <me:data type="application/xml">$data</me:data>
264 <me:sig>$sig</me:sig>
269 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
276 * diaspora_decode($importer,$xml)
277 * array $importer -> from user table
278 * string $xml -> urldecoded Diaspora salmon
281 * 'message' -> decoded Diaspora XML message
282 * 'author' -> author diaspora handle
283 * 'key' -> author public key (converted to pkcs#8)
285 * Author and key are used elsewhere to save a lookup for verifying replies and likes
289 function diaspora_decode($importer,$xml) {
292 $basedom = parse_xml_string($xml);
294 $children = $basedom->children('https://joindiaspora.com/protocol');
296 if($children->header) {
298 $author_link = str_replace('acct:','',$children->header->author_id);
302 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
304 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
305 $ciphertext = base64_decode($encrypted_header->ciphertext);
307 $outer_key_bundle = '';
308 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
310 $j_outer_key_bundle = json_decode($outer_key_bundle);
312 $outer_iv = base64_decode($j_outer_key_bundle->iv);
313 $outer_key = base64_decode($j_outer_key_bundle->key);
315 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
318 $decrypted = pkcs5_unpad($decrypted);
321 * $decrypted now contains something like
324 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
325 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
330 * <name>Ryan Hughes</name>
331 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
336 * <author_id>galaxor@diaspora.priateship.org</author_id>
340 * </decrypted_header>
343 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
344 $idom = parse_xml_string($decrypted,false);
346 $inner_iv = base64_decode($idom->iv);
347 $inner_aes_key = base64_decode($idom->aes_key);
349 $author_link = str_replace('acct:','',$idom->author_id);
353 $dom = $basedom->children(NAMESPACE_SALMON_ME);
355 // figure out where in the DOM tree our data is hiding
357 if($dom->provenance->data)
358 $base = $dom->provenance;
359 elseif($dom->env->data)
365 logger('mod-diaspora: unable to locate salmon data in xml ');
366 http_status_exit(400);
370 // Stash the signature away for now. We have to find their key or it won't be good for anything.
371 $signature = base64url_decode($base->sig);
375 // strip whitespace so our data element will return to one big base64 blob
376 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
379 // stash away some other stuff for later
381 $type = $base->data[0]->attributes()->type[0];
382 $keyhash = $base->sig[0]->attributes()->keyhash[0];
383 $encoding = $base->encoding;
387 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
391 $data = base64url_decode($data);
395 $inner_decrypted = $data;
399 // Decode the encrypted blob
401 $inner_encrypted = base64_decode($data);
402 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
403 $inner_decrypted = pkcs5_unpad($inner_decrypted);
407 logger('mod-diaspora: Could not retrieve author URI.');
408 http_status_exit(400);
411 // Once we have the author URI, go to the web and try to find their public key
412 // (first this will look it up locally if it is in the fcontact cache)
413 // This will also convert diaspora public key from pkcs#1 to pkcs#8
415 logger('mod-diaspora: Fetching key for ' . $author_link );
416 $key = get_diaspora_key($author_link);
419 logger('mod-diaspora: Could not retrieve author key.');
420 http_status_exit(400);
423 $verify = rsa_verify($signed_data,$signature,$key);
426 logger('mod-diaspora: Message did not verify. Discarding.');
427 http_status_exit(400);
430 logger('mod-diaspora: Message verified.');
432 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
437 function diaspora_request($importer,$xml) {
441 $sender_handle = unxmlify($xml->sender_handle);
442 $recipient_handle = unxmlify($xml->recipient_handle);
444 if(! $sender_handle || ! $recipient_handle)
447 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
451 // perhaps we were already sharing with this person. Now they're sharing with us.
452 // That makes us friends.
454 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
455 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
456 intval(CONTACT_IS_FRIEND),
457 intval($contact['id']),
458 intval($importer['uid'])
463 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
464 intval($importer['uid'])
467 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
468 require_once('include/items.php');
470 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
471 intval($importer['uid'])
474 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
476 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
479 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
480 $arr['uid'] = $importer['uid'];
481 $arr['contact-id'] = $self[0]['id'];
483 $arr['type'] = 'wall';
486 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
487 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
488 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
489 $arr['verb'] = ACTIVITY_FRIEND;
490 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
492 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
493 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
494 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
495 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
497 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
498 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
499 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
500 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
501 $arr['object'] .= '</link></object>' . "\n";
502 $arr['last-child'] = 1;
504 $arr['allow_cid'] = $user[0]['allow_cid'];
505 $arr['allow_gid'] = $user[0]['allow_gid'];
506 $arr['deny_cid'] = $user[0]['deny_cid'];
507 $arr['deny_gid'] = $user[0]['deny_gid'];
509 $i = item_store($arr);
511 proc_run('php',"include/notifier.php","activity","$i");
520 $ret = find_diaspora_person_by_handle($sender_handle);
523 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
524 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
528 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
530 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
531 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
532 intval($importer['uid']),
533 dbesc($ret['network']),
537 dbesc(normalise_link($ret['url'])),
541 dbesc($ret['photo']),
542 dbesc($ret['pubkey']),
543 dbesc($ret['notify']),
549 // find the contact record we just created
551 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
553 $hash = random_string() . (string) time(); // Generate a confirm_key
555 if($contact_record) {
556 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
557 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
558 intval($importer['uid']),
559 intval($contact_record['id']),
562 dbesc( t('Sharing notification from Diaspora network')),
564 dbesc(datetime_convert())
571 function diaspora_post($importer,$xml) {
574 $guid = notags(unxmlify($xml->guid));
575 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
577 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
581 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
582 logger('diaspora_post: Ignoring this author.');
586 $message_id = $diaspora_handle . ':' . $guid;
587 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
588 intval($importer['uid']),
593 logger('diaspora_post: message exists: ' . $guid);
597 // allocate a guid on our system - we aren't fixing any collisions.
598 // we're ignoring them
600 $g = q("select * from guid where guid = '%s' limit 1",
604 q("insert into guid ( guid ) values ( '%s' )",
609 $created = unxmlify($xml->created_at);
610 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
612 $body = diaspora2bb($xml->raw_message);
618 $tags = get_tags($body);
621 foreach($tags as $tag) {
622 if(strpos($tag,'#') === 0) {
623 if(strpos($tag,'[url='))
625 $basetag = str_replace('_',' ',substr($tag,1));
626 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
627 if(strlen($str_tags))
629 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
635 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
637 foreach($matches as $mtch) {
638 if(strlen($str_tags))
640 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
644 $datarray['uid'] = $importer['uid'];
645 $datarray['contact-id'] = $contact['id'];
646 $datarray['wall'] = 0;
647 $datarray['guid'] = $guid;
648 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
649 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
650 $datarray['private'] = $private;
651 $datarray['parent'] = 0;
652 $datarray['owner-name'] = $contact['name'];
653 $datarray['owner-link'] = $contact['url'];
654 $datarray['owner-avatar'] = $contact['thumb'];
655 $datarray['author-name'] = $contact['name'];
656 $datarray['author-link'] = $contact['url'];
657 $datarray['author-avatar'] = $contact['thumb'];
658 $datarray['body'] = $body;
659 $datarray['tag'] = $str_tags;
660 $datarray['app'] = 'Diaspora';
662 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
664 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
666 $message_id = item_store($datarray);
669 q("update item set plink = '%s' where id = %d limit 1",
670 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
679 function diaspora_reshare($importer,$xml) {
681 logger('diaspora_reshare: init: ' . print_r($xml,true));
684 $guid = notags(unxmlify($xml->guid));
685 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
688 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
692 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
693 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
697 $message_id = $diaspora_handle . ':' . $guid;
698 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
699 intval($importer['uid']),
704 logger('diaspora_reshare: message exists: ' . $guid);
708 $orig_author = notags(unxmlify($xml->root_diaspora_id));
709 $orig_guid = notags(unxmlify($xml->root_guid));
711 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
712 $x = fetch_url($source_url);
714 $x = fetch_url(str_replace('https://','http://',$source_url));
716 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
719 logger('diaspora_reshare: source: ' . $x);
721 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
722 $source_xml = parse_xml_string($x,false);
724 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
725 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
726 $body = scale_diaspora_images($body,false);
728 elseif($source_xml->post->asphoto->image_url) {
729 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
730 $body = scale_diaspora_images($body);
732 elseif($source_xml->post->status_message) {
733 $body = diaspora2bb($source_xml->post->status_message->raw_message);
734 $body = scale_diaspora_images($body);
738 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
742 logger('diaspora_reshare: empty body: source= ' . $x);
746 $person = find_diaspora_person_by_handle($orig_author);
748 if(is_array($person) && x($person,'name') && x($person,'url'))
749 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
751 $details = $orig_author;
753 $prefix = '♲ ' . $details . "\n";
756 // allocate a guid on our system - we aren't fixing any collisions.
757 // we're ignoring them
759 $g = q("select * from guid where guid = '%s' limit 1",
763 q("insert into guid ( guid ) values ( '%s' )",
768 $created = unxmlify($xml->created_at);
769 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
775 $tags = get_tags($body);
778 foreach($tags as $tag) {
779 if(strpos($tag,'#') === 0) {
780 if(strpos($tag,'[url='))
782 $basetag = str_replace('_',' ',substr($tag,1));
783 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
784 if(strlen($str_tags))
786 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
792 $datarray['uid'] = $importer['uid'];
793 $datarray['contact-id'] = $contact['id'];
794 $datarray['wall'] = 0;
795 $datarray['guid'] = $guid;
796 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
797 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
798 $datarray['private'] = $private;
799 $datarray['parent'] = 0;
800 $datarray['owner-name'] = $contact['name'];
801 $datarray['owner-link'] = $contact['url'];
802 $datarray['owner-avatar'] = $contact['thumb'];
803 $datarray['author-name'] = $contact['name'];
804 $datarray['author-link'] = $contact['url'];
805 $datarray['author-avatar'] = $contact['thumb'];
806 $datarray['body'] = $prefix . $body;
807 $datarray['tag'] = $str_tags;
808 $datarray['app'] = 'Diaspora';
810 $message_id = item_store($datarray);
813 q("update item set plink = '%s' where id = %d limit 1",
814 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
824 function diaspora_asphoto($importer,$xml) {
825 logger('diaspora_asphoto called');
828 $guid = notags(unxmlify($xml->guid));
829 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
831 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
835 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
836 logger('diaspora_asphoto: Ignoring this author.');
840 $message_id = $diaspora_handle . ':' . $guid;
841 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
842 intval($importer['uid']),
847 logger('diaspora_asphoto: message exists: ' . $guid);
851 // allocate a guid on our system - we aren't fixing any collisions.
852 // we're ignoring them
854 $g = q("select * from guid where guid = '%s' limit 1",
858 q("insert into guid ( guid ) values ( '%s' )",
863 $created = unxmlify($xml->created_at);
864 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
866 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
867 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
868 $body = scale_diaspora_images($body,false);
870 elseif($xml->image_url) {
871 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
872 $body = scale_diaspora_images($body);
875 logger('diaspora_asphoto: no photo url found.');
882 $datarray['uid'] = $importer['uid'];
883 $datarray['contact-id'] = $contact['id'];
884 $datarray['wall'] = 0;
885 $datarray['guid'] = $guid;
886 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
887 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
888 $datarray['private'] = $private;
889 $datarray['parent'] = 0;
890 $datarray['owner-name'] = $contact['name'];
891 $datarray['owner-link'] = $contact['url'];
892 $datarray['owner-avatar'] = $contact['thumb'];
893 $datarray['author-name'] = $contact['name'];
894 $datarray['author-link'] = $contact['url'];
895 $datarray['author-avatar'] = $contact['thumb'];
896 $datarray['body'] = $body;
898 $datarray['app'] = 'Diaspora/Cubbi.es';
900 $message_id = item_store($datarray);
903 q("update item set plink = '%s' where id = %d limit 1",
904 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
918 function diaspora_comment($importer,$xml,$msg) {
921 $guid = notags(unxmlify($xml->guid));
922 $parent_guid = notags(unxmlify($xml->parent_guid));
923 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
924 $target_type = notags(unxmlify($xml->target_type));
925 $text = unxmlify($xml->text);
926 $author_signature = notags(unxmlify($xml->author_signature));
928 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
930 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
932 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
936 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
937 logger('diaspora_comment: Ignoring this author.');
941 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
942 intval($importer['uid']),
946 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
950 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
951 intval($importer['uid']),
955 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
958 $parent_item = $r[0];
960 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
962 $author_signature = base64_decode($author_signature);
964 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
969 $person = find_diaspora_person_by_handle($diaspora_handle);
971 if(is_array($person) && x($person,'pubkey'))
972 $key = $person['pubkey'];
974 logger('diaspora_comment: unable to find author details');
979 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
980 logger('diaspora_comment: verification failed.');
984 if($parent_author_signature) {
985 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
987 $parent_author_signature = base64_decode($parent_author_signature);
991 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
992 logger('diaspora_comment: owner verification failed.');
997 // Phew! Everything checks out. Now create an item.
999 $body = diaspora2bb($text);
1001 $message_id = $diaspora_handle . ':' . $guid;
1003 $datarray = array();
1007 $tags = get_tags($body);
1010 foreach($tags as $tag) {
1011 if(strpos($tag,'#') === 0) {
1012 if(strpos($tag,'[url='))
1014 $basetag = str_replace('_',' ',substr($tag,1));
1015 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1016 if(strlen($str_tags))
1018 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1024 $datarray['uid'] = $importer['uid'];
1025 $datarray['contact-id'] = $contact['id'];
1026 $datarray['wall'] = $parent_item['wall'];
1027 $datarray['gravity'] = GRAVITY_COMMENT;
1028 $datarray['guid'] = $guid;
1029 $datarray['uri'] = $message_id;
1030 $datarray['parent-uri'] = $parent_item['uri'];
1032 // No timestamps for comments? OK, we'll the use current time.
1033 $datarray['created'] = $datarray['edited'] = datetime_convert();
1034 $datarray['private'] = $parent_item['private'];
1036 $datarray['owner-name'] = $parent_item['owner-name'];
1037 $datarray['owner-link'] = $parent_item['owner-link'];
1038 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1040 $datarray['author-name'] = $person['name'];
1041 $datarray['author-link'] = $person['url'];
1042 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1043 $datarray['body'] = $body;
1044 $datarray['tag'] = $str_tags;
1046 // We can't be certain what the original app is if the message is relayed.
1047 if(($parent_item['origin']) && (! $parent_author_signature))
1048 $datarray['app'] = 'Diaspora';
1050 $message_id = item_store($datarray);
1053 q("update item set plink = '%s' where id = %d limit 1",
1054 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1059 if(($parent_item['origin']) && (! $parent_author_signature)) {
1060 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1061 intval($message_id),
1062 dbesc($author_signed_data),
1063 dbesc(base64_encode($author_signature)),
1064 dbesc($diaspora_handle)
1067 // if the message isn't already being relayed, notify others
1068 // the existence of parent_author_signature means the parent_author or owner
1069 // is already relaying.
1071 proc_run('php','include/notifier.php','comment',$message_id);
1079 function diaspora_conversation($importer,$xml,$msg) {
1083 $guid = notags(unxmlify($xml->guid));
1084 $subject = notags(unxmlify($xml->subject));
1085 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1086 $participant_handles = notags(unxmlify($xml->participant_handles));
1087 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1089 $parent_uri = $diaspora_handle . ':' . $guid;
1091 $messages = $xml->message;
1093 if(! count($messages)) {
1094 logger('diaspora_conversation: empty conversation');
1098 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1100 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1104 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1105 logger('diaspora_conversation: Ignoring this author.');
1109 $conversation = null;
1111 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1112 intval($importer['uid']),
1116 $conversation = $c[0];
1118 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1119 intval($importer['uid']),
1121 dbesc($diaspora_handle),
1122 dbesc(datetime_convert('UTC','UTC',$created_at)),
1123 dbesc(datetime_convert()),
1125 dbesc($participant_handles)
1128 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1129 intval($importer['uid']),
1133 $conversation = $c[0];
1135 if(! $conversation) {
1136 logger('diaspora_conversation: unable to create conversation.');
1140 foreach($messages as $mesg) {
1144 $msg_guid = notags(unxmlify($mesg->guid));
1145 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1146 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1147 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1148 $msg_text = unxmlify($mesg->text);
1149 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1150 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1151 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1152 if($msg_conversation_guid != $guid) {
1153 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1157 $body = diaspora2bb($msg_text);
1158 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1160 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1162 $author_signature = base64_decode($msg_author_signature);
1164 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1169 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1171 if(is_array($person) && x($person,'pubkey'))
1172 $key = $person['pubkey'];
1174 logger('diaspora_conversation: unable to find author details');
1179 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1180 logger('diaspora_conversation: verification failed.');
1184 if($msg_parent_author_signature) {
1185 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1187 $parent_author_signature = base64_decode($msg_parent_author_signature);
1191 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1192 logger('diaspora_conversation: owner verification failed.');
1197 $r = q("select id from mail where `uri` = '%s' limit 1",
1201 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1205 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')",
1206 intval($importer['uid']),
1208 intval($conversation['id']),
1209 dbesc($person['name']),
1210 dbesc($person['photo']),
1211 dbesc($person['url']),
1212 intval($contact['id']),
1219 dbesc($msg_created_at)
1222 q("update conv set updated = '%s' where id = %d limit 1",
1223 dbesc(datetime_convert()),
1224 intval($conversation['id'])
1231 function diaspora_message($importer,$xml,$msg) {
1235 $msg_guid = notags(unxmlify($xml->guid));
1236 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1237 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1238 $msg_author_signature = notags(unxmlify($xml->author_signature));
1239 $msg_text = unxmlify($xml->text);
1240 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1241 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1242 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1244 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1246 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1248 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1252 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1253 logger('diaspora_message: Ignoring this author.');
1257 $conversation = null;
1259 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1260 intval($importer['uid']),
1261 dbesc($msg_conversation_guid)
1264 $conversation = $c[0];
1266 logger('diaspora_message: conversation not available.');
1272 $body = diaspora2bb($msg_text);
1273 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1275 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1278 $author_signature = base64_decode($msg_author_signature);
1280 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1281 if(is_array($person) && x($person,'pubkey'))
1282 $key = $person['pubkey'];
1284 logger('diaspora_message: unable to find author details');
1288 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1289 logger('diaspora_message: verification failed.');
1293 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1295 intval($importer['uid'])
1298 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1302 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')",
1303 intval($importer['uid']),
1305 intval($conversation['id']),
1306 dbesc($person['name']),
1307 dbesc($person['photo']),
1308 dbesc($person['url']),
1309 intval($contact['id']),
1310 dbesc($conversation['subject']),
1316 dbesc($msg_created_at)
1319 q("update conv set updated = '%s' where id = %d limit 1",
1320 dbesc(datetime_convert()),
1321 intval($conversation['id'])
1328 function diaspora_photo($importer,$xml,$msg) {
1331 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1333 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1335 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1337 $guid = notags(unxmlify($xml->guid));
1339 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1341 $public = notags(unxmlify($xml->public));
1343 $created_at = notags(unxmlify($xml_created_at));
1346 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1350 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1351 logger('diaspora_photo: Ignoring this author.');
1355 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1356 intval($importer['uid']),
1357 dbesc($status_message_guid)
1360 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1363 $parent_item = $r[0];
1365 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1367 $link_text = scale_diaspora_images($link_text);
1369 if(strpos($parent_item['body'],$link_text) === false) {
1370 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1371 dbesc($link_text . $parent_item['body']),
1372 intval($parent_item['id']),
1373 intval($parent_item['uid'])
1383 function diaspora_like($importer,$xml,$msg) {
1386 $guid = notags(unxmlify($xml->guid));
1387 $parent_guid = notags(unxmlify($xml->parent_guid));
1388 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1389 $target_type = notags(unxmlify($xml->target_type));
1390 $positive = notags(unxmlify($xml->positive));
1391 $author_signature = notags(unxmlify($xml->author_signature));
1393 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1395 // likes on comments not supported here and likes on photos not supported by Diaspora
1397 if($target_type !== 'Post')
1400 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1402 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1406 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1407 logger('diaspora_like: Ignoring this author.');
1411 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1412 intval($importer['uid']),
1416 logger('diaspora_like: parent item not found: ' . $guid);
1420 $parent_item = $r[0];
1422 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1423 intval($importer['uid']),
1427 if($positive === 'true') {
1428 logger('diaspora_like: duplicate like: ' . $guid);
1431 if($positive === 'false') {
1432 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1433 intval($r[0]['id']),
1434 intval($importer['uid'])
1437 // send notification via proc_run()
1441 if($positive === 'false') {
1442 logger('diaspora_like: unlike received with no corresponding like');
1446 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1448 $author_signature = base64_decode($author_signature);
1450 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1455 $person = find_diaspora_person_by_handle($diaspora_handle);
1456 if(is_array($person) && x($person,'pubkey'))
1457 $key = $person['pubkey'];
1459 logger('diaspora_like: unable to find author details');
1464 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1465 logger('diaspora_like: verification failed.');
1469 if($parent_author_signature) {
1471 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1473 $parent_author_signature = base64_decode($parent_author_signature);
1477 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1478 logger('diaspora_like: owner verification failed.');
1483 // Phew! Everything checks out. Now create an item.
1485 $uri = $diaspora_handle . ':' . $guid;
1487 $activity = ACTIVITY_LIKE;
1488 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1489 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1490 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1491 $body = $parent_item['body'];
1496 <type>$objtype</type>
1498 <id>{$parent_item['uri']}</id>
1501 <content>$body</content>
1504 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1509 $arr['uid'] = $importer['uid'];
1510 $arr['guid'] = $guid;
1511 $arr['contact-id'] = $contact['id'];
1512 $arr['type'] = 'activity';
1513 $arr['wall'] = $parent_item['wall'];
1514 $arr['gravity'] = GRAVITY_LIKE;
1515 $arr['parent'] = $parent_item['id'];
1516 $arr['parent-uri'] = $parent_item['uri'];
1518 $arr['owner-name'] = $parent_item['name'];
1519 $arr['owner-link'] = $parent_item['url'];
1520 $arr['owner-avatar'] = $parent_item['thumb'];
1522 $arr['author-name'] = $person['name'];
1523 $arr['author-link'] = $person['url'];
1524 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1526 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1527 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1528 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1529 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1531 $arr['app'] = 'Diaspora';
1533 $arr['private'] = $parent_item['private'];
1534 $arr['verb'] = $activity;
1535 $arr['object-type'] = $objtype;
1536 $arr['object'] = $obj;
1537 $arr['visible'] = 1;
1539 $arr['last-child'] = 0;
1541 $message_id = item_store($arr);
1545 q("update item set plink = '%s' where id = %d limit 1",
1546 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1551 if(! $parent_author_signature) {
1552 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1553 intval($message_id),
1554 dbesc($author_signed_data),
1555 dbesc(base64_encode($author_signature)),
1556 dbesc($diaspora_handle)
1560 // if the message isn't already being relayed, notify others
1561 // the existence of parent_author_signature means the parent_author or owner
1562 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1564 if(($parent_item['origin']) && (! $parent_author_signature))
1565 proc_run('php','include/notifier.php','comment',$message_id);
1570 function diaspora_retraction($importer,$xml) {
1572 $guid = notags(unxmlify($xml->guid));
1573 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1574 $type = notags(unxmlify($xml->type));
1576 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1580 if($type === 'Person') {
1581 require_once('include/Contact.php');
1582 contact_remove($contact['id']);
1584 elseif($type === 'Post') {
1585 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1587 intval($importer['uid'])
1590 if(link_compare($r[0]['author-link'],$contact['url'])) {
1591 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1592 dbesc(datetime_convert()),
1603 function diaspora_signed_retraction($importer,$xml) {
1605 $guid = notags(unxmlify($xml->target_guid));
1606 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1607 $type = notags(unxmlify($xml->target_type));
1608 $sig = notags(unxmlify($xml->target_author_signature));
1610 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1614 // this may not yet work for comments. Need to see how the relaying works
1615 // and figure out who signs it.
1618 $signed_data = $guid . ';' . $type ;
1620 $sig = base64_decode($sig);
1624 if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1625 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1629 if($type === 'StatusMessage') {
1630 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1632 intval($importer['uid'])
1635 if(link_compare($r[0]['author-link'],$contact['url'])) {
1636 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1637 dbesc(datetime_convert()),
1648 function diaspora_profile($importer,$xml) {
1651 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1653 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1657 if($contact['blocked']) {
1658 logger('diaspora_post: Ignoring this author.');
1662 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1663 $image_url = unxmlify($xml->image_url);
1664 $birthday = unxmlify($xml->birthday);
1666 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1667 intval($importer['uid']),
1668 intval($contact['id'])
1670 $oldphotos = ((count($r)) ? $r : null);
1672 require_once('include/Photo.php');
1674 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1676 // Generic birthday. We don't know the timezone. The year is irrelevant.
1678 $birthday = str_replace('1000','1901',$birthday);
1680 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1682 $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",
1684 dbesc(datetime_convert()),
1688 dbesc(datetime_convert()),
1690 intval($contact['id']),
1691 intval($importer['uid'])
1696 foreach($oldphotos as $ph) {
1697 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1698 intval($importer['uid']),
1699 intval($contact['id']),
1700 dbesc($ph['resource-id'])
1731 function diaspora_share($me,$contact) {
1733 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1734 $theiraddr = $contact['addr'];
1736 $tpl = get_markup_template('diaspora_share.tpl');
1737 $msg = replace_macros($tpl, array(
1738 '$sender' => $myaddr,
1739 '$recipient' => $theiraddr
1742 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1744 return(diaspora_transmit($owner,$contact,$slap, false));
1747 function diaspora_unshare($me,$contact) {
1750 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1752 $tpl = get_markup_template('diaspora_retract.tpl');
1753 $msg = replace_macros($tpl, array(
1754 '$guid' => $me['guid'],
1755 '$type' => 'Person',
1756 '$handle' => $myaddr
1759 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1761 return(diaspora_transmit($owner,$contact,$slap, false));
1767 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1770 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1771 $theiraddr = $contact['addr'];
1775 $body = $item['body'];
1778 // We're trying to match Diaspora's split message/photo protocol but
1779 // all the photos are displayed on D* as links and not img's - even
1780 // though we're sending pretty much precisely what they send us when
1781 // doing the same operation.
1782 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1783 // which seems to get through intact.
1785 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1787 foreach($matches as $mtch) {
1789 $detail['str'] = $mtch[0];
1790 $detail['path'] = dirname($mtch[1]) . '/';
1791 $detail['file'] = basename($mtch[1]);
1792 $detail['guid'] = $item['guid'];
1793 $detail['handle'] = $myaddr;
1794 $images[] = $detail;
1795 $body = str_replace($detail['str'],$mtch[1],$body);
1800 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1802 if($item['attach']) {
1803 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1805 $body .= "\n" . t('Attachments:') . "\n";
1806 foreach($matches as $mtch) {
1807 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1813 $public = (($item['private']) ? 'false' : 'true');
1815 require_once('include/datetime.php');
1816 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1818 $tpl = get_markup_template('diaspora_post.tpl');
1819 $msg = replace_macros($tpl, array(
1821 '$guid' => $item['guid'],
1822 '$handle' => xmlify($myaddr),
1823 '$public' => $public,
1824 '$created' => $created
1827 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1829 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1831 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1833 if(count($images)) {
1834 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1837 return $return_code;
1841 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1843 if(! count($images))
1845 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1847 $tpl = get_markup_template('diaspora_photo.tpl');
1848 foreach($images as $image) {
1849 if(! stristr($image['path'],$mysite))
1851 $resource = str_replace('.jpg','',$image['file']);
1852 $resource = substr($resource,0,strpos($resource,'-'));
1854 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1856 intval($owner['uid'])
1860 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1861 $msg = replace_macros($tpl,array(
1862 '$path' => xmlify($image['path']),
1863 '$filename' => xmlify($image['file']),
1864 '$msg_guid' => xmlify($image['guid']),
1865 '$guid' => xmlify($r[0]['guid']),
1866 '$handle' => xmlify($image['handle']),
1867 '$public' => xmlify($public),
1868 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1872 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1873 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1875 diaspora_transmit($owner,$contact,$slap,$public_batch);
1880 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1883 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1884 $theiraddr = $contact['addr'];
1886 $p = q("select guid from item where parent = %d limit 1",
1890 $parent_guid = $p[0]['guid'];
1894 if($item['verb'] === ACTIVITY_LIKE) {
1895 $tpl = get_markup_template('diaspora_like.tpl');
1897 $target_type = 'Post';
1898 $positive = (($item['deleted']) ? 'false' : 'true');
1901 $tpl = get_markup_template('diaspora_comment.tpl');
1905 $text = html_entity_decode(bb2diaspora($item['body']));
1910 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1912 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1914 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1916 $msg = replace_macros($tpl,array(
1917 '$guid' => xmlify($item['guid']),
1918 '$parent_guid' => xmlify($parent_guid),
1919 '$target_type' =>xmlify($target_type),
1920 '$authorsig' => xmlify($authorsig),
1921 '$body' => xmlify($text),
1922 '$positive' => xmlify($positive),
1923 '$handle' => xmlify($myaddr)
1926 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1928 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1930 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1934 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1938 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1939 $theiraddr = $contact['addr'];
1942 $p = q("select guid from item where parent = %d limit 1",
1946 $parent_guid = $p[0]['guid'];
1950 if($item['verb'] === ACTIVITY_LIKE) {
1951 $tpl = get_markup_template('diaspora_like_relay.tpl');
1953 $target_type = 'Post';
1954 $positive = (($item['deleted']) ? 'false' : 'true');
1957 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1961 $body = $item['body'];
1963 $text = html_entity_decode(bb2diaspora($body));
1965 // fetch the original signature if somebody sent the post to us to relay
1966 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1967 // action. It wasn't needed. In that case create the original signature and the
1968 // owner (parent author) signature
1969 // comments from other networks will be relayed under our name, with a brief
1970 // preamble to describe what's happening and noting the real author
1972 $r = q("select * from sign where iid = %d limit 1",
1977 $signed_text = $orig_sign['signed_text'];
1978 $authorsig = $orig_sign['signature'];
1979 $handle = $orig_sign['signer'];
1983 $itemcontact = q("select * from contact where `id` = %d limit 1",
1984 intval($item['contact-id'])
1986 if(count($itemcontact)) {
1987 if(! $itemcontact[0]['self']) {
1988 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1989 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1990 network_to_name($itemcontact['network'])) . "\n";
1991 $body = $prefix . $body;
1997 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1999 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
2001 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2003 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2004 intval($item['id']),
2005 dbesc($signed_text),
2006 dbesc(base64_encode($authorsig)),
2015 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2017 $msg = replace_macros($tpl,array(
2018 '$guid' => xmlify($item['guid']),
2019 '$parent_guid' => xmlify($parent_guid),
2020 '$target_type' =>xmlify($target_type),
2021 '$authorsig' => xmlify($orig_sign['signature']),
2022 '$parentsig' => xmlify($parentauthorsig),
2023 '$body' => xmlify($text),
2024 '$positive' => xmlify($positive),
2025 '$handle' => xmlify($handle)
2028 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
2030 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2032 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2038 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2041 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2043 $signed_text = $item['guid'] . ';' . 'StatusMessage';
2045 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2046 $msg = replace_macros($tpl, array(
2047 '$guid' => $item['guid'],
2048 '$type' => 'StatusMessage',
2049 '$handle' => $myaddr,
2050 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
2053 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2055 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2058 function diaspora_send_mail($item,$owner,$contact) {
2061 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2063 $r = q("select * from conv where id = %d and uid = %d limit 1",
2064 intval($item['convid']),
2065 intval($item['uid'])
2069 logger('diaspora_send_mail: conversation not found.');
2075 'guid' => xmlify($cnv['guid']),
2076 'subject' => xmlify($cnv['subject']),
2077 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2078 'diaspora_handle' => xmlify($cnv['creator']),
2079 'participant_handles' => xmlify($cnv['recips'])
2082 $body = bb2diaspora($item['body']);
2083 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2085 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2086 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2088 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2091 'guid' => xmlify($item['guid']),
2092 'parent_guid' => xmlify($cnv['guid']),
2093 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2094 'author_signature' => xmlify($sig),
2095 'text' => xmlify($body),
2096 'created_at' => xmlify($created),
2097 'diaspora_handle' => xmlify($myaddr),
2098 'conversation_guid' => xmlify($cnv['guid'])
2101 if($item['reply']) {
2102 $tpl = get_markup_template('diaspora_message.tpl');
2103 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2106 $conv['messages'] = array($msg);
2107 $tpl = get_markup_template('diaspora_conversation.tpl');
2108 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2111 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2113 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2115 return(diaspora_transmit($owner,$contact,$slap,false));
2120 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
2123 $logid = random_string(4);
2124 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2126 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2130 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2132 post_url($dest_url . '/', $slap);
2134 $return_code = $a->get_curl_code();
2135 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2137 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2138 logger('diaspora_transmit: queue message');
2140 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2141 intval($contact['id']),
2142 dbesc(NETWORK_DIASPORA),
2144 intval($public_batch)
2147 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2150 // queue message for redelivery
2151 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2156 return(($return_code) ? $return_code : (-1));