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');
8 require_once('include/lock.php');
11 function diaspora_dispatch_public($msg) {
13 $enabled = intval(get_config('system','diaspora_enabled'));
15 logger('mod-diaspora: disabled');
19 $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 ",
20 dbesc(NETWORK_DIASPORA),
25 logger('diaspora_public: delivering to: ' . $rr['username']);
26 diaspora_dispatch($rr,$msg);
30 logger('diaspora_public: no subscribers');
35 function diaspora_dispatch($importer,$msg) {
39 $enabled = intval(get_config('system','diaspora_enabled'));
41 logger('mod-diaspora: disabled');
45 // php doesn't like dashes in variable names
47 $msg['message'] = str_replace(
48 array('<activity_streams-photo>','</activity_streams-photo>'),
49 array('<asphoto>','</asphoto>'),
53 $parsed_xml = parse_xml_string($msg['message'],false);
55 $xmlbase = $parsed_xml->post;
57 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
60 if($xmlbase->request) {
61 $ret = diaspora_request($importer,$xmlbase->request);
63 elseif($xmlbase->status_message) {
64 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
66 elseif($xmlbase->profile) {
67 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
69 elseif($xmlbase->comment) {
70 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
72 elseif($xmlbase->like) {
73 $ret = diaspora_like($importer,$xmlbase->like,$msg);
75 elseif($xmlbase->asphoto) {
76 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
78 elseif($xmlbase->reshare) {
79 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
81 elseif($xmlbase->retraction) {
82 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
84 elseif($xmlbase->signed_retraction) {
85 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
87 elseif($xmlbase->relayable_retraction) {
88 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
90 elseif($xmlbase->photo) {
91 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
93 elseif($xmlbase->conversation) {
94 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
96 elseif($xmlbase->message) {
97 $ret = diaspora_message($importer,$xmlbase->message,$msg);
100 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
105 function diaspora_handle_from_contact($contact_id) {
108 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
110 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
116 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
118 if($contact['network'] === NETWORK_DIASPORA) {
119 $handle = $contact['addr'];
121 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
123 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
124 $baseurl_start = strpos($contact['url'],'://') + 3;
125 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
126 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
127 $handle = $contact['nick'] . '@' . $baseurl;
129 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
136 function diaspora_get_contact_by_handle($uid,$handle) {
137 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
138 dbesc(NETWORK_DIASPORA),
147 function find_diaspora_person_by_handle($handle) {
157 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
158 dbesc(NETWORK_DIASPORA),
163 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
165 // update record occasionally so it doesn't get stale
166 $d = strtotime($person['updated'] . ' +00:00');
167 if($d < strtotime('now - 14 days'))
172 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
174 // If the person isn't in our 'fcontact' table, or if he/she is but
175 // his/her information hasn't been updated for more than 14 days, then
176 // we want to fetch the person's information from the remote server.
178 // Note that $person isn't changed by this block of code unless the
179 // person's information has been successfully fetched from the remote
180 // server. So if $person was 'false' to begin with (because he/she wasn't
181 // in the local cache), it'll stay false, and if $person held the local
182 // cache information to begin with, it'll keep that information. That way
183 // if there's a problem with the remote fetch, we can at least use our
184 // cached information--it's better than nothing.
186 if((! $person) || ($update)) {
187 // Lock the function to prevent race conditions if multiple items
188 // come in at the same time from a person who doesn't exist in
191 // Don't loop forever. On the last loop, try to create the contact
192 // whether the function is locked or not. Maybe the locking thread
193 // has died or something. At any rate, a duplicate in 'fcontact'
194 // is a much smaller problem than a deadlocked thread
195 $got_lock = lock_function('find_diaspora_person_by_handle', false);
196 if(($endlessloop + 1) >= $maxloops)
200 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
201 require_once('include/Scrape.php');
202 $r = probe_url($handle, PROBE_DIASPORA);
204 // Note that Friendica contacts can return a "Diaspora person"
205 // if Diaspora connectivity is enabled on their server
206 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
207 add_fcontact($r,$update);
211 unlock_function('find_diaspora_person_by_handle');
214 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
216 block_on_function_lock('find_diaspora_person_by_handle');
219 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
220 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
221 // The fact that the function was locked may mean that another process was creating the
222 // person's record. It could also mean another process was creating or updating an unrelated
225 // At any rate, we need to keep trying until we've either got the person or had a chance to
226 // try to fetch his/her remote information. But we don't want to block on locking the
227 // function, because if the other process is creating the record, then when we acquire the lock
228 // we'll dive right into creating another, duplicate record. We DO want to at least wait
229 // until the lock is released, so we don't flood the database with requests.
231 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
232 // we do have some information for the person
238 function get_diaspora_key($uri) {
239 logger('Fetching diaspora key for: ' . $uri);
241 $r = find_diaspora_person_by_handle($uri);
248 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
251 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
254 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
256 // $b64_data = base64_encode($msg);
257 // $b64url_data = base64url_encode($b64_data);
259 $b64url_data = base64url_encode($msg);
261 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
263 $type = 'application/xml';
264 $encoding = 'base64url';
267 $signable_data = $data . '.' . base64url_encode($type) . '.'
268 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
270 $signature = rsa_sign($signable_data,$prvkey);
271 $sig = base64url_encode($signature);
274 <?xml version='1.0' encoding='UTF-8'?>
275 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
277 <author_id>$handle</author_id>
280 <me:encoding>base64url</me:encoding>
281 <me:alg>RSA-SHA256</me:alg>
282 <me:data type="application/xml">$data</me:data>
283 <me:sig>$sig</me:sig>
288 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
296 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
300 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
302 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
304 // without a public key nothing will work
307 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
311 $inner_aes_key = random_string(32);
312 $b_inner_aes_key = base64_encode($inner_aes_key);
313 $inner_iv = random_string(16);
314 $b_inner_iv = base64_encode($inner_iv);
316 $outer_aes_key = random_string(32);
317 $b_outer_aes_key = base64_encode($outer_aes_key);
318 $outer_iv = random_string(16);
319 $b_outer_iv = base64_encode($outer_iv);
321 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
323 $padded_data = pkcs5_pad($msg,16);
324 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
326 $b64_data = base64_encode($inner_encrypted);
329 $b64url_data = base64url_encode($b64_data);
330 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
332 $type = 'application/xml';
333 $encoding = 'base64url';
336 $signable_data = $data . '.' . base64url_encode($type) . '.'
337 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
339 $signature = rsa_sign($signable_data,$prvkey);
340 $sig = base64url_encode($signature);
342 $decrypted_header = <<< EOT
345 <aes_key>$b_inner_aes_key</aes_key>
346 <author_id>$handle</author_id>
350 $decrypted_header = pkcs5_pad($decrypted_header,16);
352 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
354 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
356 $encrypted_outer_key_bundle = '';
357 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
359 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
361 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
363 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
364 'ciphertext' => base64_encode($ciphertext)));
365 $cipher_json = base64_encode($encrypted_header_json_object);
367 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
370 <?xml version='1.0' encoding='UTF-8'?>
371 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
374 <me:encoding>base64url</me:encoding>
375 <me:alg>RSA-SHA256</me:alg>
376 <me:data type="application/xml">$data</me:data>
377 <me:sig>$sig</me:sig>
382 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
389 * diaspora_decode($importer,$xml)
390 * array $importer -> from user table
391 * string $xml -> urldecoded Diaspora salmon
394 * 'message' -> decoded Diaspora XML message
395 * 'author' -> author diaspora handle
396 * 'key' -> author public key (converted to pkcs#8)
398 * Author and key are used elsewhere to save a lookup for verifying replies and likes
402 function diaspora_decode($importer,$xml) {
405 $basedom = parse_xml_string($xml);
407 $children = $basedom->children('https://joindiaspora.com/protocol');
409 if($children->header) {
411 $author_link = str_replace('acct:','',$children->header->author_id);
415 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
417 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
418 $ciphertext = base64_decode($encrypted_header->ciphertext);
420 $outer_key_bundle = '';
421 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
423 $j_outer_key_bundle = json_decode($outer_key_bundle);
425 $outer_iv = base64_decode($j_outer_key_bundle->iv);
426 $outer_key = base64_decode($j_outer_key_bundle->key);
428 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
431 $decrypted = pkcs5_unpad($decrypted);
434 * $decrypted now contains something like
437 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
438 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
443 * <name>Ryan Hughes</name>
444 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
449 * <author_id>galaxor@diaspora.priateship.org</author_id>
453 * </decrypted_header>
456 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
457 $idom = parse_xml_string($decrypted,false);
459 $inner_iv = base64_decode($idom->iv);
460 $inner_aes_key = base64_decode($idom->aes_key);
462 $author_link = str_replace('acct:','',$idom->author_id);
466 $dom = $basedom->children(NAMESPACE_SALMON_ME);
468 // figure out where in the DOM tree our data is hiding
470 if($dom->provenance->data)
471 $base = $dom->provenance;
472 elseif($dom->env->data)
478 logger('mod-diaspora: unable to locate salmon data in xml ');
479 http_status_exit(400);
483 // Stash the signature away for now. We have to find their key or it won't be good for anything.
484 $signature = base64url_decode($base->sig);
488 // strip whitespace so our data element will return to one big base64 blob
489 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
492 // stash away some other stuff for later
494 $type = $base->data[0]->attributes()->type[0];
495 $keyhash = $base->sig[0]->attributes()->keyhash[0];
496 $encoding = $base->encoding;
500 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
504 $data = base64url_decode($data);
508 $inner_decrypted = $data;
512 // Decode the encrypted blob
514 $inner_encrypted = base64_decode($data);
515 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
516 $inner_decrypted = pkcs5_unpad($inner_decrypted);
520 logger('mod-diaspora: Could not retrieve author URI.');
521 http_status_exit(400);
524 // Once we have the author URI, go to the web and try to find their public key
525 // (first this will look it up locally if it is in the fcontact cache)
526 // This will also convert diaspora public key from pkcs#1 to pkcs#8
528 logger('mod-diaspora: Fetching key for ' . $author_link );
529 $key = get_diaspora_key($author_link);
532 logger('mod-diaspora: Could not retrieve author key.');
533 http_status_exit(400);
536 $verify = rsa_verify($signed_data,$signature,$key);
539 logger('mod-diaspora: Message did not verify. Discarding.');
540 http_status_exit(400);
543 logger('mod-diaspora: Message verified.');
545 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
550 function diaspora_request($importer,$xml) {
554 $sender_handle = unxmlify($xml->sender_handle);
555 $recipient_handle = unxmlify($xml->recipient_handle);
557 if(! $sender_handle || ! $recipient_handle)
560 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
564 // perhaps we were already sharing with this person. Now they're sharing with us.
565 // That makes us friends.
567 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
568 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
569 intval(CONTACT_IS_FRIEND),
570 intval($contact['id']),
571 intval($importer['uid'])
576 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
577 intval($importer['uid'])
580 if((count($r)) && (! $r[0]['hide-friends']) && (! $contact['hidden'])) {
581 require_once('include/items.php');
583 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
584 intval($importer['uid'])
587 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
589 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
592 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
593 $arr['uid'] = $importer['uid'];
594 $arr['contact-id'] = $self[0]['id'];
596 $arr['type'] = 'wall';
599 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
600 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
601 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
602 $arr['verb'] = ACTIVITY_FRIEND;
603 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
605 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
606 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
607 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
608 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
610 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
611 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
612 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
613 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
614 $arr['object'] .= '</link></object>' . "\n";
615 $arr['last-child'] = 1;
617 $arr['allow_cid'] = $user[0]['allow_cid'];
618 $arr['allow_gid'] = $user[0]['allow_gid'];
619 $arr['deny_cid'] = $user[0]['deny_cid'];
620 $arr['deny_gid'] = $user[0]['deny_gid'];
622 $i = item_store($arr);
624 proc_run('php',"include/notifier.php","activity","$i");
633 $ret = find_diaspora_person_by_handle($sender_handle);
636 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
637 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
641 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
645 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
646 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
647 intval($importer['uid']),
648 dbesc($ret['network']),
652 dbesc(normalise_link($ret['url'])),
656 dbesc($ret['photo']),
657 dbesc($ret['pubkey']),
658 dbesc($ret['notify']),
664 // find the contact record we just created
666 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
668 if(! $contact_record) {
669 logger('diaspora_request: unable to locate newly created contact record.');
673 $g = q("select def_gid from user where uid = %d limit 1",
674 intval($importer['uid'])
676 if($g && intval($g[0]['def_gid'])) {
677 require_once('include/group.php');
678 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
681 if($importer['page-flags'] == PAGE_NORMAL) {
683 $hash = random_string() . (string) time(); // Generate a confirm_key
685 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
686 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
687 intval($importer['uid']),
688 intval($contact_record['id']),
691 dbesc( t('Sharing notification from Diaspora network')),
693 dbesc(datetime_convert())
698 // automatic friend approval
700 require_once('include/Photo.php');
702 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
704 // technically they are sharing with us (CONTACT_IS_SHARING),
705 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
706 // we are going to change the relationship and make them a follower.
708 if($importer['page-flags'] == PAGE_FREELOVE)
709 $new_relation = CONTACT_IS_FRIEND;
711 $new_relation = CONTACT_IS_FOLLOWER;
713 $r = q("UPDATE `contact` SET
720 `avatar-date` = '%s',
723 WHERE `id` = %d LIMIT 1
728 intval($new_relation),
729 dbesc(datetime_convert()),
730 dbesc(datetime_convert()),
731 dbesc(datetime_convert()),
732 intval($contact_record['id'])
735 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
737 $ret = diaspora_share($u[0],$contact_record);
743 function diaspora_post_allow($importer,$contact) {
744 if(($contact['blocked']) || ($contact['readonly']))
746 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
748 if($contact['rel'] == CONTACT_IS_FOLLOWER)
749 if($importer['page-flags'] == PAGE_COMMUNITY)
755 function diaspora_post($importer,$xml,$msg) {
758 $guid = notags(unxmlify($xml->guid));
759 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
761 if($diaspora_handle != $msg['author']) {
762 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
766 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
770 if(! diaspora_post_allow($importer,$contact)) {
771 logger('diaspora_post: Ignoring this author.');
775 $message_id = $diaspora_handle . ':' . $guid;
776 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
777 intval($importer['uid']),
782 logger('diaspora_post: message exists: ' . $guid);
786 // allocate a guid on our system - we aren't fixing any collisions.
787 // we're ignoring them
789 $g = q("select * from guid where guid = '%s' limit 1",
793 q("insert into guid ( guid ) values ( '%s' )",
798 $created = unxmlify($xml->created_at);
799 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
801 $body = diaspora2bb($xml->raw_message);
807 $tags = get_tags($body);
810 foreach($tags as $tag) {
811 if(strpos($tag,'#') === 0) {
812 if(strpos($tag,'[url='))
815 // don't link tags that are already embedded in links
817 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
819 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
822 $basetag = str_replace('_',' ',substr($tag,1));
823 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
824 if(strlen($str_tags))
826 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
832 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
834 foreach($matches as $mtch) {
835 if(strlen($str_tags))
837 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
841 $datarray['uid'] = $importer['uid'];
842 $datarray['contact-id'] = $contact['id'];
843 $datarray['wall'] = 0;
844 $datarray['guid'] = $guid;
845 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
846 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
847 $datarray['private'] = $private;
848 $datarray['parent'] = 0;
849 $datarray['owner-name'] = $contact['name'];
850 $datarray['owner-link'] = $contact['url'];
851 $datarray['owner-avatar'] = $contact['thumb'];
852 $datarray['author-name'] = $contact['name'];
853 $datarray['author-link'] = $contact['url'];
854 $datarray['author-avatar'] = $contact['thumb'];
855 $datarray['body'] = $body;
856 $datarray['tag'] = $str_tags;
857 $datarray['app'] = 'Diaspora';
859 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
861 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
863 $message_id = item_store($datarray);
866 q("update item set plink = '%s' where id = %d limit 1",
867 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
876 function diaspora_reshare($importer,$xml,$msg) {
878 logger('diaspora_reshare: init: ' . print_r($xml,true));
881 $guid = notags(unxmlify($xml->guid));
882 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
885 if($diaspora_handle != $msg['author']) {
886 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
890 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
894 if(! diaspora_post_allow($importer,$contact)) {
895 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
899 $message_id = $diaspora_handle . ':' . $guid;
900 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
901 intval($importer['uid']),
906 logger('diaspora_reshare: message exists: ' . $guid);
910 $orig_author = notags(unxmlify($xml->root_diaspora_id));
911 $orig_guid = notags(unxmlify($xml->root_guid));
913 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
914 $x = fetch_url($source_url);
916 $x = fetch_url(str_replace('https://','http://',$source_url));
918 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
921 logger('diaspora_reshare: source: ' . $x);
923 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
924 $source_xml = parse_xml_string($x,false);
926 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
927 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
928 $body = scale_external_images($body,false);
930 elseif($source_xml->post->asphoto->image_url) {
931 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
932 $body = scale_external_images($body);
934 elseif($source_xml->post->status_message) {
935 $body = diaspora2bb($source_xml->post->status_message->raw_message);
936 $body = scale_external_images($body);
940 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
944 logger('diaspora_reshare: empty body: source= ' . $x);
948 $person = find_diaspora_person_by_handle($orig_author);
950 if(is_array($person) && x($person,'name') && x($person,'url'))
951 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
953 $details = $orig_author;
955 $prefix = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . $details . "\n";
958 // allocate a guid on our system - we aren't fixing any collisions.
959 // we're ignoring them
961 $g = q("select * from guid where guid = '%s' limit 1",
965 q("insert into guid ( guid ) values ( '%s' )",
970 $created = unxmlify($xml->created_at);
971 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
977 $tags = get_tags($body);
980 foreach($tags as $tag) {
981 if(strpos($tag,'#') === 0) {
982 if(strpos($tag,'[url='))
985 // don't link tags that are already embedded in links
987 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
989 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
993 $basetag = str_replace('_',' ',substr($tag,1));
994 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
995 if(strlen($str_tags))
997 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1003 $datarray['uid'] = $importer['uid'];
1004 $datarray['contact-id'] = $contact['id'];
1005 $datarray['wall'] = 0;
1006 $datarray['guid'] = $guid;
1007 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1008 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1009 $datarray['private'] = $private;
1010 $datarray['parent'] = 0;
1011 $datarray['owner-name'] = $contact['name'];
1012 $datarray['owner-link'] = $contact['url'];
1013 $datarray['owner-avatar'] = $contact['thumb'];
1014 $datarray['author-name'] = $contact['name'];
1015 $datarray['author-link'] = $contact['url'];
1016 $datarray['author-avatar'] = $contact['thumb'];
1017 $datarray['body'] = $prefix . $body;
1018 $datarray['tag'] = $str_tags;
1019 $datarray['app'] = 'Diaspora';
1021 $message_id = item_store($datarray);
1024 q("update item set plink = '%s' where id = %d limit 1",
1025 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1035 function diaspora_asphoto($importer,$xml,$msg) {
1036 logger('diaspora_asphoto called');
1039 $guid = notags(unxmlify($xml->guid));
1040 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1042 if($diaspora_handle != $msg['author']) {
1043 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1047 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1051 if(! diaspora_post_allow($importer,$contact)) {
1052 logger('diaspora_asphoto: Ignoring this author.');
1056 $message_id = $diaspora_handle . ':' . $guid;
1057 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1058 intval($importer['uid']),
1063 logger('diaspora_asphoto: message exists: ' . $guid);
1067 // allocate a guid on our system - we aren't fixing any collisions.
1068 // we're ignoring them
1070 $g = q("select * from guid where guid = '%s' limit 1",
1074 q("insert into guid ( guid ) values ( '%s' )",
1079 $created = unxmlify($xml->created_at);
1080 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1082 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1083 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1084 $body = scale_external_images($body,false);
1086 elseif($xml->image_url) {
1087 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1088 $body = scale_external_images($body);
1091 logger('diaspora_asphoto: no photo url found.');
1095 $datarray = array();
1098 $datarray['uid'] = $importer['uid'];
1099 $datarray['contact-id'] = $contact['id'];
1100 $datarray['wall'] = 0;
1101 $datarray['guid'] = $guid;
1102 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1103 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1104 $datarray['private'] = $private;
1105 $datarray['parent'] = 0;
1106 $datarray['owner-name'] = $contact['name'];
1107 $datarray['owner-link'] = $contact['url'];
1108 $datarray['owner-avatar'] = $contact['thumb'];
1109 $datarray['author-name'] = $contact['name'];
1110 $datarray['author-link'] = $contact['url'];
1111 $datarray['author-avatar'] = $contact['thumb'];
1112 $datarray['body'] = $body;
1114 $datarray['app'] = 'Diaspora/Cubbi.es';
1116 $message_id = item_store($datarray);
1119 q("update item set plink = '%s' where id = %d limit 1",
1120 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1134 function diaspora_comment($importer,$xml,$msg) {
1137 $guid = notags(unxmlify($xml->guid));
1138 $parent_guid = notags(unxmlify($xml->parent_guid));
1139 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1140 $target_type = notags(unxmlify($xml->target_type));
1141 $text = unxmlify($xml->text);
1142 $author_signature = notags(unxmlify($xml->author_signature));
1144 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1146 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1148 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1152 if(! diaspora_post_allow($importer,$contact)) {
1153 logger('diaspora_comment: Ignoring this author.');
1157 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1158 intval($importer['uid']),
1162 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1166 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1167 intval($importer['uid']),
1171 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1174 $parent_item = $r[0];
1177 /* How Diaspora performs comment signature checking:
1179 - If an item has been sent by the comment author to the top-level post owner to relay on
1180 to the rest of the contacts on the top-level post, the top-level post owner should check
1181 the author_signature, then create a parent_author_signature before relaying the comment on
1182 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1183 check only the parent_author_signature. Basically, they trust that the top-level post
1184 owner has already verified the authenticity of anything he/she sends out
1185 - In either case, the signature that get checked is the signature created by the person
1189 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1192 if($parent_author_signature) {
1193 // If a parent_author_signature exists, then we've received the comment
1194 // relayed from the top-level post owner. There's no need to check the
1195 // author_signature if the parent_author_signature is valid
1197 $parent_author_signature = base64_decode($parent_author_signature);
1199 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1200 logger('diaspora_comment: top-level owner verification failed.');
1205 // If there's no parent_author_signature, then we've received the comment
1206 // from the comment creator. In that case, the person is commenting on
1207 // our post, so he/she must be a contact of ours and his/her public key
1208 // should be in $msg['key']
1210 $author_signature = base64_decode($author_signature);
1212 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1213 logger('diaspora_comment: comment author verification failed.');
1218 // Phew! Everything checks out. Now create an item.
1220 // Find the original comment author information.
1221 // We need this to make sure we display the comment author
1222 // information (name and avatar) correctly.
1223 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1226 $person = find_diaspora_person_by_handle($diaspora_handle);
1228 if(! is_array($person)) {
1229 logger('diaspora_comment: unable to find author details');
1234 $body = diaspora2bb($text);
1236 $message_id = $diaspora_handle . ':' . $guid;
1238 $datarray = array();
1242 $tags = get_tags($body);
1245 foreach($tags as $tag) {
1246 if(strpos($tag,'#') === 0) {
1247 if(strpos($tag,'[url='))
1250 // don't link tags that are already embedded in links
1252 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1254 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1258 $basetag = str_replace('_',' ',substr($tag,1));
1259 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1260 if(strlen($str_tags))
1262 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1268 $datarray['uid'] = $importer['uid'];
1269 $datarray['contact-id'] = $contact['id'];
1270 $datarray['type'] = 'remote-comment';
1271 $datarray['wall'] = $parent_item['wall'];
1272 $datarray['gravity'] = GRAVITY_COMMENT;
1273 $datarray['guid'] = $guid;
1274 $datarray['uri'] = $message_id;
1275 $datarray['parent-uri'] = $parent_item['uri'];
1277 // No timestamps for comments? OK, we'll the use current time.
1278 $datarray['created'] = $datarray['edited'] = datetime_convert();
1279 $datarray['private'] = $parent_item['private'];
1281 $datarray['owner-name'] = $parent_item['owner-name'];
1282 $datarray['owner-link'] = $parent_item['owner-link'];
1283 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1285 $datarray['author-name'] = $person['name'];
1286 $datarray['author-link'] = $person['url'];
1287 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1288 $datarray['body'] = $body;
1289 $datarray['tag'] = $str_tags;
1291 // We can't be certain what the original app is if the message is relayed.
1292 if(($parent_item['origin']) && (! $parent_author_signature))
1293 $datarray['app'] = 'Diaspora';
1295 $message_id = item_store($datarray);
1298 q("update item set plink = '%s' where id = %d limit 1",
1299 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1304 if(($parent_item['origin']) && (! $parent_author_signature)) {
1305 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1306 intval($message_id),
1307 dbesc($signed_data),
1308 dbesc(base64_encode($author_signature)),
1309 dbesc($diaspora_handle)
1312 // if the message isn't already being relayed, notify others
1313 // the existence of parent_author_signature means the parent_author or owner
1314 // is already relaying.
1316 proc_run('php','include/notifier.php','comment-import',$message_id);
1319 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1320 dbesc($parent_item['uri']),
1321 intval($importer['uid'])
1324 if(count($myconv)) {
1325 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1327 foreach($myconv as $conv) {
1329 // now if we find a match, it means we're in this conversation
1331 if(! link_compare($conv['author-link'],$importer_url))
1334 require_once('include/enotify.php');
1336 $conv_parent = $conv['parent'];
1339 'type' => NOTIFY_COMMENT,
1340 'notify_flags' => $importer['notify-flags'],
1341 'language' => $importer['language'],
1342 'to_name' => $importer['username'],
1343 'to_email' => $importer['email'],
1344 'uid' => $importer['uid'],
1345 'item' => $datarray,
1346 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id,
1347 'source_name' => $datarray['author-name'],
1348 'source_link' => $datarray['author-link'],
1349 'source_photo' => $datarray['author-avatar'],
1350 'verb' => ACTIVITY_POST,
1352 'parent' => $conv_parent,
1353 'parent_uri' => $parent_uri
1356 // only send one notification
1366 function diaspora_conversation($importer,$xml,$msg) {
1370 $guid = notags(unxmlify($xml->guid));
1371 $subject = notags(unxmlify($xml->subject));
1372 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1373 $participant_handles = notags(unxmlify($xml->participant_handles));
1374 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1376 $parent_uri = $diaspora_handle . ':' . $guid;
1378 $messages = $xml->message;
1380 if(! count($messages)) {
1381 logger('diaspora_conversation: empty conversation');
1385 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1387 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1391 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1392 logger('diaspora_conversation: Ignoring this author.');
1396 $conversation = null;
1398 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1399 intval($importer['uid']),
1403 $conversation = $c[0];
1405 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1406 intval($importer['uid']),
1408 dbesc($diaspora_handle),
1409 dbesc(datetime_convert('UTC','UTC',$created_at)),
1410 dbesc(datetime_convert()),
1412 dbesc($participant_handles)
1415 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1416 intval($importer['uid']),
1420 $conversation = $c[0];
1422 if(! $conversation) {
1423 logger('diaspora_conversation: unable to create conversation.');
1427 foreach($messages as $mesg) {
1431 $msg_guid = notags(unxmlify($mesg->guid));
1432 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1433 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1434 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1435 $msg_text = unxmlify($mesg->text);
1436 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1437 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1438 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1439 if($msg_conversation_guid != $guid) {
1440 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1444 $body = diaspora2bb($msg_text);
1445 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1447 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1449 $author_signature = base64_decode($msg_author_signature);
1451 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1456 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1458 if(is_array($person) && x($person,'pubkey'))
1459 $key = $person['pubkey'];
1461 logger('diaspora_conversation: unable to find author details');
1466 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1467 logger('diaspora_conversation: verification failed.');
1471 if($msg_parent_author_signature) {
1472 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1474 $parent_author_signature = base64_decode($msg_parent_author_signature);
1478 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1479 logger('diaspora_conversation: owner verification failed.');
1484 $r = q("select id from mail where `uri` = '%s' limit 1",
1488 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1492 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')",
1493 intval($importer['uid']),
1495 intval($conversation['id']),
1496 dbesc($person['name']),
1497 dbesc($person['photo']),
1498 dbesc($person['url']),
1499 intval($contact['id']),
1506 dbesc($msg_created_at)
1509 q("update conv set updated = '%s' where id = %d limit 1",
1510 dbesc(datetime_convert()),
1511 intval($conversation['id'])
1514 require_once('include/enotify.php');
1516 'type' => NOTIFY_MAIL,
1517 'notify_flags' => $importer['notify-flags'],
1518 'language' => $importer['language'],
1519 'to_name' => $importer['username'],
1520 'to_email' => $importer['email'],
1521 'uid' =>$importer['importer_uid'],
1522 'item' => array('subject' => $subject, 'body' => $body),
1523 'source_name' => $person['name'],
1524 'source_link' => $person['url'],
1525 'source_photo' => $person['thumb'],
1526 'verb' => ACTIVITY_POST,
1534 function diaspora_message($importer,$xml,$msg) {
1538 $msg_guid = notags(unxmlify($xml->guid));
1539 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1540 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1541 $msg_author_signature = notags(unxmlify($xml->author_signature));
1542 $msg_text = unxmlify($xml->text);
1543 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1544 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1545 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1547 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1549 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1551 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1555 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1556 logger('diaspora_message: Ignoring this author.');
1560 $conversation = null;
1562 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1563 intval($importer['uid']),
1564 dbesc($msg_conversation_guid)
1567 $conversation = $c[0];
1569 logger('diaspora_message: conversation not available.');
1575 $body = diaspora2bb($msg_text);
1576 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1578 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1581 $author_signature = base64_decode($msg_author_signature);
1583 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1584 if(is_array($person) && x($person,'pubkey'))
1585 $key = $person['pubkey'];
1587 logger('diaspora_message: unable to find author details');
1591 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1592 logger('diaspora_message: verification failed.');
1596 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1598 intval($importer['uid'])
1601 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1605 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')",
1606 intval($importer['uid']),
1608 intval($conversation['id']),
1609 dbesc($person['name']),
1610 dbesc($person['photo']),
1611 dbesc($person['url']),
1612 intval($contact['id']),
1613 dbesc($conversation['subject']),
1619 dbesc($msg_created_at)
1622 q("update conv set updated = '%s' where id = %d limit 1",
1623 dbesc(datetime_convert()),
1624 intval($conversation['id'])
1631 function diaspora_photo($importer,$xml,$msg) {
1635 logger('diaspora_photo: init',LOGGER_DEBUG);
1637 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1639 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1641 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1643 $guid = notags(unxmlify($xml->guid));
1645 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1647 $public = notags(unxmlify($xml->public));
1649 $created_at = notags(unxmlify($xml_created_at));
1651 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1653 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1655 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1659 if(! diaspora_post_allow($importer,$contact)) {
1660 logger('diaspora_photo: Ignoring this author.');
1664 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1665 intval($importer['uid']),
1666 dbesc($status_message_guid)
1669 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1673 $parent_item = $r[0];
1675 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1677 $link_text = scale_external_images($link_text, true,
1678 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1680 if(strpos($parent_item['body'],$link_text) === false) {
1681 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1682 dbesc($link_text . $parent_item['body']),
1683 intval($parent_item['id']),
1684 intval($parent_item['uid'])
1694 function diaspora_like($importer,$xml,$msg) {
1697 $guid = notags(unxmlify($xml->guid));
1698 $parent_guid = notags(unxmlify($xml->parent_guid));
1699 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1700 $target_type = notags(unxmlify($xml->target_type));
1701 $positive = notags(unxmlify($xml->positive));
1702 $author_signature = notags(unxmlify($xml->author_signature));
1704 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1706 // likes on comments not supported here and likes on photos not supported by Diaspora
1708 // if($target_type !== 'Post')
1711 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1713 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1717 if(! diaspora_post_allow($importer,$contact)) {
1718 logger('diaspora_like: Ignoring this author.');
1722 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1723 intval($importer['uid']),
1727 logger('diaspora_like: parent item not found: ' . $guid);
1731 $parent_item = $r[0];
1733 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1734 intval($importer['uid']),
1738 if($positive === 'true') {
1739 logger('diaspora_like: duplicate like: ' . $guid);
1742 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1743 // It looks like "RelayableRetractions" are used for "unlike" instead
1744 if($positive === 'false') {
1745 logger('diaspora_like: received a like with positive set to "false"...ignoring');
1746 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1747 intval($r[0]['id']),
1748 intval($importer['uid'])
1750 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1751 // send notification via proc_run()
1755 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1756 // It looks like "RelayableRetractions" are used for "unlike" instead
1757 if($positive === 'false') {
1758 logger('diaspora_like: received a like with positive set to "false"');
1759 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1764 /* How Diaspora performs "like" signature checking:
1766 - If an item has been sent by the like author to the top-level post owner to relay on
1767 to the rest of the contacts on the top-level post, the top-level post owner should check
1768 the author_signature, then create a parent_author_signature before relaying the like on
1769 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1770 check only the parent_author_signature. Basically, they trust that the top-level post
1771 owner has already verified the authenticity of anything he/she sends out
1772 - In either case, the signature that get checked is the signature created by the person
1776 $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1779 if($parent_author_signature) {
1780 // If a parent_author_signature exists, then we've received the like
1781 // relayed from the top-level post owner. There's no need to check the
1782 // author_signature if the parent_author_signature is valid
1784 $parent_author_signature = base64_decode($parent_author_signature);
1786 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1787 logger('diaspora_like: top-level owner verification failed.');
1792 // If there's no parent_author_signature, then we've received the like
1793 // from the like creator. In that case, the person is "like"ing
1794 // our post, so he/she must be a contact of ours and his/her public key
1795 // should be in $msg['key']
1797 $author_signature = base64_decode($author_signature);
1799 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1800 logger('diaspora_like: like creator verification failed.');
1805 // Phew! Everything checks out. Now create an item.
1807 // Find the original comment author information.
1808 // We need this to make sure we display the comment author
1809 // information (name and avatar) correctly.
1810 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1813 $person = find_diaspora_person_by_handle($diaspora_handle);
1815 if(! is_array($person)) {
1816 logger('diaspora_like: unable to find author details');
1821 $uri = $diaspora_handle . ':' . $guid;
1823 $activity = ACTIVITY_LIKE;
1824 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1825 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1826 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1827 $body = $parent_item['body'];
1832 <type>$objtype</type>
1834 <id>{$parent_item['uri']}</id>
1837 <content>$body</content>
1840 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1845 $arr['uid'] = $importer['uid'];
1846 $arr['guid'] = $guid;
1847 $arr['contact-id'] = $contact['id'];
1848 $arr['type'] = 'activity';
1849 $arr['wall'] = $parent_item['wall'];
1850 $arr['gravity'] = GRAVITY_LIKE;
1851 $arr['parent'] = $parent_item['id'];
1852 $arr['parent-uri'] = $parent_item['uri'];
1854 $arr['owner-name'] = $parent_item['name'];
1855 $arr['owner-link'] = $parent_item['url'];
1856 $arr['owner-avatar'] = $parent_item['thumb'];
1858 $arr['author-name'] = $person['name'];
1859 $arr['author-link'] = $person['url'];
1860 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1862 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1863 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1864 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1865 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1867 $arr['app'] = 'Diaspora';
1869 $arr['private'] = $parent_item['private'];
1870 $arr['verb'] = $activity;
1871 $arr['object-type'] = $objtype;
1872 $arr['object'] = $obj;
1873 $arr['visible'] = 1;
1875 $arr['last-child'] = 0;
1877 $message_id = item_store($arr);
1881 q("update item set plink = '%s' where id = %d limit 1",
1882 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1887 if(! $parent_author_signature) {
1888 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1889 intval($message_id),
1890 dbesc($signed_data),
1891 dbesc(base64_encode($author_signature)),
1892 dbesc($diaspora_handle)
1896 // if the message isn't already being relayed, notify others
1897 // the existence of parent_author_signature means the parent_author or owner
1898 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1900 if(($parent_item['origin']) && (! $parent_author_signature))
1901 proc_run('php','include/notifier.php','comment-import',$message_id);
1906 function diaspora_retraction($importer,$xml) {
1909 $guid = notags(unxmlify($xml->guid));
1910 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1911 $type = notags(unxmlify($xml->type));
1913 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1917 if($type === 'Person') {
1918 require_once('include/Contact.php');
1919 contact_remove($contact['id']);
1921 elseif($type === 'Post') {
1922 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1924 intval($importer['uid'])
1927 if(link_compare($r[0]['author-link'],$contact['url'])) {
1928 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1929 dbesc(datetime_convert()),
1940 function diaspora_signed_retraction($importer,$xml,$msg) {
1943 $guid = notags(unxmlify($xml->target_guid));
1944 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1945 $type = notags(unxmlify($xml->target_type));
1946 $sig = notags(unxmlify($xml->target_author_signature));
1948 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1950 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1952 logger('diaspora_signed_retraction: no contact');
1957 $signed_data = $guid . ';' . $type ;
1960 /* How Diaspora performs relayable_retraction signature checking:
1962 - If an item has been sent by the item author to the top-level post owner to relay on
1963 to the rest of the contacts on the top-level post, the top-level post owner checks
1964 the author_signature, then creates a parent_author_signature before relaying the item on
1965 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1966 check only the parent_author_signature. Basically, they trust that the top-level post
1967 owner has already verified the authenticity of anything he/she sends out
1968 - In either case, the signature that get checked is the signature created by the person
1972 if($parent_author_signature) {
1974 $parent_author_signature = base64_decode($parent_author_signature);
1976 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1977 logger('diaspora_signed_retraction: top-level post owner verification failed');
1984 $sig_decode = base64_decode($sig);
1986 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
1987 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
1992 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
1993 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1995 intval($importer['uid'])
1998 if(link_compare($r[0]['author-link'],$contact['url'])) {
1999 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d limit 1",
2000 dbesc(datetime_convert()),
2001 dbesc(datetime_convert()),
2005 // Now check if the retraction needs to be relayed by us
2007 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2008 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2009 // The only item with `parent` and `id` as the parent id is the parent item.
2010 $p = q("select origin from item where parent = %d and id = %d limit 1",
2015 if(($p[0]['origin']) && (! $parent_author_signature)) {
2016 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2018 dbesc($signed_data),
2020 dbesc($diaspora_handle)
2023 // the existence of parent_author_signature would have meant the parent_author or owner
2024 // is already relaying.
2025 logger('diaspora_signed_retraction: relaying relayable_retraction');
2027 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2034 logger('diaspora_signed_retraction: unknown type: ' . $type);
2040 function diaspora_profile($importer,$xml,$msg) {
2043 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2046 if($diaspora_handle != $msg['author']) {
2047 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2051 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2055 if($contact['blocked']) {
2056 logger('diaspora_post: Ignoring this author.');
2060 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2061 $image_url = unxmlify($xml->image_url);
2062 $birthday = unxmlify($xml->birthday);
2064 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2065 intval($importer['uid']),
2066 intval($contact['id'])
2068 $oldphotos = ((count($r)) ? $r : null);
2070 require_once('include/Photo.php');
2072 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2074 // Generic birthday. We don't know the timezone. The year is irrelevant.
2076 $birthday = str_replace('1000','1901',$birthday);
2078 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2080 // this is to prevent multiple birthday notifications in a single year
2081 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2083 if(substr($birthday,5) === substr($contact['bd'],5))
2084 $birthday = $contact['bd'];
2086 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2087 // Not doing this currently because D* protocol is scheduled for revision soon.
2089 $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",
2091 dbesc(datetime_convert()),
2095 dbesc(datetime_convert()),
2097 intval($contact['id']),
2098 intval($importer['uid'])
2103 foreach($oldphotos as $ph) {
2104 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2105 intval($importer['uid']),
2106 intval($contact['id']),
2107 dbesc($ph['resource-id'])
2117 function diaspora_share($me,$contact) {
2119 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2120 $theiraddr = $contact['addr'];
2122 $tpl = get_markup_template('diaspora_share.tpl');
2123 $msg = replace_macros($tpl, array(
2124 '$sender' => $myaddr,
2125 '$recipient' => $theiraddr
2128 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2129 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2131 return(diaspora_transmit($owner,$contact,$slap, false));
2134 function diaspora_unshare($me,$contact) {
2137 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2139 $tpl = get_markup_template('diaspora_retract.tpl');
2140 $msg = replace_macros($tpl, array(
2141 '$guid' => $me['guid'],
2142 '$type' => 'Person',
2143 '$handle' => $myaddr
2146 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2147 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2149 return(diaspora_transmit($owner,$contact,$slap, false));
2154 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2157 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2158 $theiraddr = $contact['addr'];
2162 $title = $item['title'];
2163 $body = $item['body'];
2166 // We're trying to match Diaspora's split message/photo protocol but
2167 // all the photos are displayed on D* as links and not img's - even
2168 // though we're sending pretty much precisely what they send us when
2169 // doing the same operation.
2170 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2171 // which seems to get through intact.
2173 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2175 foreach($matches as $mtch) {
2177 $detail['str'] = $mtch[0];
2178 $detail['path'] = dirname($mtch[1]) . '/';
2179 $detail['file'] = basename($mtch[1]);
2180 $detail['guid'] = $item['guid'];
2181 $detail['handle'] = $myaddr;
2182 $images[] = $detail;
2183 $body = str_replace($detail['str'],$mtch[1],$body);
2188 //if(strlen($title))
2189 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2191 // convert to markdown
2192 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2193 //$body = bb2diaspora($body);
2197 $body = "## ".html_entity_decode($title)."\n\n".$body;
2199 if($item['attach']) {
2200 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2202 $body .= "\n" . t('Attachments:') . "\n";
2203 foreach($matches as $mtch) {
2204 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2210 $public = (($item['private']) ? 'false' : 'true');
2212 require_once('include/datetime.php');
2213 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2215 $tpl = get_markup_template('diaspora_post.tpl');
2216 $msg = replace_macros($tpl, array(
2218 '$guid' => $item['guid'],
2219 '$handle' => xmlify($myaddr),
2220 '$public' => $public,
2221 '$created' => $created
2224 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
2226 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2227 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2229 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2231 if(count($images)) {
2232 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2235 return $return_code;
2239 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2241 if(! count($images))
2243 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2245 $tpl = get_markup_template('diaspora_photo.tpl');
2246 foreach($images as $image) {
2247 if(! stristr($image['path'],$mysite))
2249 $resource = str_replace('.jpg','',$image['file']);
2250 $resource = substr($resource,0,strpos($resource,'-'));
2252 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2254 intval($owner['uid'])
2258 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2259 $msg = replace_macros($tpl,array(
2260 '$path' => xmlify($image['path']),
2261 '$filename' => xmlify($image['file']),
2262 '$msg_guid' => xmlify($image['guid']),
2263 '$guid' => xmlify($r[0]['guid']),
2264 '$handle' => xmlify($image['handle']),
2265 '$public' => xmlify($public),
2266 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2270 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2271 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2272 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2274 diaspora_transmit($owner,$contact,$slap,$public_batch);
2279 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2282 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2283 // $theiraddr = $contact['addr'];
2285 // Diaspora doesn't support threaded comments
2286 /*if($item['thr-parent']) {
2287 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2288 dbesc($item['thr-parent'])
2292 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2293 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2294 // The only item with `parent` and `id` as the parent id is the parent item.
2295 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2296 intval($item['parent']),
2297 intval($item['parent'])
2305 if($item['verb'] === ACTIVITY_LIKE) {
2306 $tpl = get_markup_template('diaspora_like.tpl');
2308 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2309 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2310 // $positive = (($item['deleted']) ? 'false' : 'true');
2313 if(($item['deleted']))
2314 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2317 $tpl = get_markup_template('diaspora_comment.tpl');
2321 $text = html_entity_decode(bb2diaspora($item['body']));
2326 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2328 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2330 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2332 $msg = replace_macros($tpl,array(
2333 '$guid' => xmlify($item['guid']),
2334 '$parent_guid' => xmlify($parent['guid']),
2335 '$target_type' =>xmlify($target_type),
2336 '$authorsig' => xmlify($authorsig),
2337 '$body' => xmlify($text),
2338 '$positive' => xmlify($positive),
2339 '$handle' => xmlify($myaddr)
2342 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2344 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2345 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2347 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2351 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2355 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2356 // $theiraddr = $contact['addr'];
2358 $body = $item['body'];
2359 $text = html_entity_decode(bb2diaspora($body));
2361 // Diaspora doesn't support threaded comments
2362 /*if($item['thr-parent']) {
2363 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2364 dbesc($item['thr-parent'])
2368 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2369 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2370 // The only item with `parent` and `id` as the parent id is the parent item.
2371 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2372 intval($item['parent']),
2373 intval($item['parent'])
2382 $relay_retract = false;
2383 $sql_sign_id = 'iid';
2384 if( $item['deleted']) {
2385 $relay_retract = true;
2387 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2389 $sql_sign_id = 'retract_iid';
2390 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2392 elseif($item['verb'] === ACTIVITY_LIKE) {
2395 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2396 // $positive = (($item['deleted']) ? 'false' : 'true');
2399 $tpl = get_markup_template('diaspora_like_relay.tpl');
2401 else { // item is a comment
2402 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2406 // fetch the original signature if the relayable was created by a Diaspora
2407 // or DFRN user. Relayables for other networks are not supported.
2409 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2414 $signed_text = $orig_sign['signed_text'];
2415 $authorsig = $orig_sign['signature'];
2416 $handle = $orig_sign['signer'];
2420 // Author signature information (for likes, comments, and retractions of likes or comments,
2421 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2422 // function is called
2423 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2427 /* Since the author signature is only checked by the parent, not by the relay recipients,
2428 * I think it may not be necessary for us to do so much work to preserve all the original
2429 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2430 * Let's just generate that and forget about all the original author signature stuff.
2432 * Note: this might be more of an problem if we want to support likes on comments for older
2433 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2434 * doing that, let's ignore it for now.
2436 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2440 $handle = diaspora_handle_from_contact($item['contact-id']);
2446 $sender_signed_text = $item['guid'] . ';' . $target_type;
2448 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2450 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2452 // Sign the relayable with the top-level owner's signature
2454 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2455 // stored in the database, because that provides the best chance that Diaspora will
2456 // be able to reconstruct the signed text the same way we did. This is particularly a
2457 // concern for the comment, whose signed text includes the text of the comment. The
2458 // smallest change in the text of the comment, including removing whitespace, will
2459 // make the signature verification fail. Since we translate from BB code to Diaspora's
2460 // markup at the top of this function, which is AFTER we placed the original $signed_text
2461 // in the database, it's hazardous to trust the original $signed_text.
2463 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2465 $msg = replace_macros($tpl,array(
2466 '$guid' => xmlify($item['guid']),
2467 '$parent_guid' => xmlify($parent['guid']),
2468 '$target_type' =>xmlify($target_type),
2469 '$authorsig' => xmlify($authorsig),
2470 '$parentsig' => xmlify($parentauthorsig),
2471 '$body' => xmlify($text),
2472 '$positive' => xmlify($positive),
2473 '$handle' => xmlify($handle)
2476 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2479 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2480 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2482 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2488 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2491 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2493 // Check whether the retraction is for a top-level post or whether it's a relayable
2494 if( $item['uri'] !== $item['parent-uri'] ) {
2496 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2497 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2501 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2502 $target_type = 'StatusMessage';
2505 $signed_text = $item['guid'] . ';' . $target_type;
2507 $msg = replace_macros($tpl, array(
2508 '$guid' => xmlify($item['guid']),
2509 '$type' => xmlify($target_type),
2510 '$handle' => xmlify($myaddr),
2511 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2514 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2515 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2517 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2520 function diaspora_send_mail($item,$owner,$contact) {
2523 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2525 $r = q("select * from conv where id = %d and uid = %d limit 1",
2526 intval($item['convid']),
2527 intval($item['uid'])
2531 logger('diaspora_send_mail: conversation not found.');
2537 'guid' => xmlify($cnv['guid']),
2538 'subject' => xmlify($cnv['subject']),
2539 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2540 'diaspora_handle' => xmlify($cnv['creator']),
2541 'participant_handles' => xmlify($cnv['recips'])
2544 $body = bb2diaspora($item['body']);
2545 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2547 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2548 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2550 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2553 'guid' => xmlify($item['guid']),
2554 'parent_guid' => xmlify($cnv['guid']),
2555 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2556 'author_signature' => xmlify($sig),
2557 'text' => xmlify($body),
2558 'created_at' => xmlify($created),
2559 'diaspora_handle' => xmlify($myaddr),
2560 'conversation_guid' => xmlify($cnv['guid'])
2563 if($item['reply']) {
2564 $tpl = get_markup_template('diaspora_message.tpl');
2565 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2568 $conv['messages'] = array($msg);
2569 $tpl = get_markup_template('diaspora_conversation.tpl');
2570 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2573 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2575 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2576 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2578 return(diaspora_transmit($owner,$contact,$slap,false));
2583 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2585 $enabled = intval(get_config('system','diaspora_enabled'));
2591 $logid = random_string(4);
2592 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2594 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2598 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2600 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2604 if(! intval(get_config('system','diaspora_test'))) {
2605 post_url($dest_url . '/', $slap);
2606 $return_code = $a->get_curl_code();
2609 logger('diaspora_transmit: test_mode');
2614 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2616 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2617 logger('diaspora_transmit: queue message');
2619 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2620 intval($contact['id']),
2621 dbesc(NETWORK_DIASPORA),
2623 intval($public_batch)
2626 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2629 // queue message for redelivery
2630 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2635 return(($return_code) ? $return_code : (-1));