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');
9 require_once('include/threads.php');
10 require_once('mod/share.php');
12 function diaspora_dispatch_public($msg) {
14 $enabled = intval(get_config('system','diaspora_enabled'));
16 logger('mod-diaspora: disabled');
20 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
21 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
22 AND `account_expired` = 0 AND `account_removed` = 0 ",
23 dbesc(NETWORK_DIASPORA),
28 logger('diaspora_public: delivering to: ' . $rr['username']);
29 diaspora_dispatch($rr,$msg);
33 logger('diaspora_public: no subscribers');
38 function diaspora_dispatch($importer,$msg,$attempt=1) {
42 $enabled = intval(get_config('system','diaspora_enabled'));
44 logger('mod-diaspora: disabled');
48 // php doesn't like dashes in variable names
50 $msg['message'] = str_replace(
51 array('<activity_streams-photo>','</activity_streams-photo>'),
52 array('<asphoto>','</asphoto>'),
56 $parsed_xml = parse_xml_string($msg['message'],false);
58 $xmlbase = $parsed_xml->post;
60 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
63 if($xmlbase->request) {
64 $ret = diaspora_request($importer,$xmlbase->request);
66 elseif($xmlbase->status_message) {
67 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
69 elseif($xmlbase->profile) {
70 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
72 elseif($xmlbase->comment) {
73 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
75 elseif($xmlbase->like) {
76 $ret = diaspora_like($importer,$xmlbase->like,$msg);
78 elseif($xmlbase->asphoto) {
79 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
81 elseif($xmlbase->reshare) {
82 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
84 elseif($xmlbase->retraction) {
85 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
87 elseif($xmlbase->signed_retraction) {
88 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
90 elseif($xmlbase->relayable_retraction) {
91 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
93 elseif($xmlbase->photo) {
94 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
96 elseif($xmlbase->conversation) {
97 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
99 elseif($xmlbase->message) {
100 $ret = diaspora_message($importer,$xmlbase->message,$msg);
103 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
108 function diaspora_handle_from_contact($contact_id) {
111 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
113 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
119 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
121 if($contact['network'] === NETWORK_DIASPORA) {
122 $handle = $contact['addr'];
124 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
126 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
127 $baseurl_start = strpos($contact['url'],'://') + 3;
128 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
129 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
130 $handle = $contact['nick'] . '@' . $baseurl;
132 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
139 function diaspora_get_contact_by_handle($uid,$handle) {
140 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
141 dbesc(NETWORK_DIASPORA),
148 $handle_parts = explode("@", $handle);
149 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
150 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
161 function find_diaspora_person_by_handle($handle) {
171 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
172 dbesc(NETWORK_DIASPORA),
177 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
179 // update record occasionally so it doesn't get stale
180 $d = strtotime($person['updated'] . ' +00:00');
181 if($d < strtotime('now - 14 days'))
186 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
188 // If the person isn't in our 'fcontact' table, or if he/she is but
189 // his/her information hasn't been updated for more than 14 days, then
190 // we want to fetch the person's information from the remote server.
192 // Note that $person isn't changed by this block of code unless the
193 // person's information has been successfully fetched from the remote
194 // server. So if $person was 'false' to begin with (because he/she wasn't
195 // in the local cache), it'll stay false, and if $person held the local
196 // cache information to begin with, it'll keep that information. That way
197 // if there's a problem with the remote fetch, we can at least use our
198 // cached information--it's better than nothing.
200 if((! $person) || ($update)) {
201 // Lock the function to prevent race conditions if multiple items
202 // come in at the same time from a person who doesn't exist in
205 // Don't loop forever. On the last loop, try to create the contact
206 // whether the function is locked or not. Maybe the locking thread
207 // has died or something. At any rate, a duplicate in 'fcontact'
208 // is a much smaller problem than a deadlocked thread
209 $got_lock = lock_function('find_diaspora_person_by_handle', false);
210 if(($endlessloop + 1) >= $maxloops)
214 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
215 require_once('include/Scrape.php');
216 $r = probe_url($handle, PROBE_DIASPORA);
218 // Note that Friendica contacts can return a "Diaspora person"
219 // if Diaspora connectivity is enabled on their server
220 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
221 add_fcontact($r,$update);
225 unlock_function('find_diaspora_person_by_handle');
228 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
230 block_on_function_lock('find_diaspora_person_by_handle');
233 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
234 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
235 // The fact that the function was locked may mean that another process was creating the
236 // person's record. It could also mean another process was creating or updating an unrelated
239 // At any rate, we need to keep trying until we've either got the person or had a chance to
240 // try to fetch his/her remote information. But we don't want to block on locking the
241 // function, because if the other process is creating the record, then when we acquire the lock
242 // we'll dive right into creating another, duplicate record. We DO want to at least wait
243 // until the lock is released, so we don't flood the database with requests.
245 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
246 // we do have some information for the person
252 function get_diaspora_key($uri) {
253 logger('Fetching diaspora key for: ' . $uri);
255 $r = find_diaspora_person_by_handle($uri);
262 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
265 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
268 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
270 // $b64_data = base64_encode($msg);
271 // $b64url_data = base64url_encode($b64_data);
273 $b64url_data = base64url_encode($msg);
275 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
277 $type = 'application/xml';
278 $encoding = 'base64url';
281 $signable_data = $data . '.' . base64url_encode($type) . '.'
282 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
284 $signature = rsa_sign($signable_data,$prvkey);
285 $sig = base64url_encode($signature);
288 <?xml version='1.0' encoding='UTF-8'?>
289 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
291 <author_id>$handle</author_id>
294 <me:encoding>base64url</me:encoding>
295 <me:alg>RSA-SHA256</me:alg>
296 <me:data type="application/xml">$data</me:data>
297 <me:sig>$sig</me:sig>
302 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
310 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
314 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
316 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
318 // without a public key nothing will work
321 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
325 $inner_aes_key = random_string(32);
326 $b_inner_aes_key = base64_encode($inner_aes_key);
327 $inner_iv = random_string(16);
328 $b_inner_iv = base64_encode($inner_iv);
330 $outer_aes_key = random_string(32);
331 $b_outer_aes_key = base64_encode($outer_aes_key);
332 $outer_iv = random_string(16);
333 $b_outer_iv = base64_encode($outer_iv);
335 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
337 $padded_data = pkcs5_pad($msg,16);
338 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
340 $b64_data = base64_encode($inner_encrypted);
343 $b64url_data = base64url_encode($b64_data);
344 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
346 $type = 'application/xml';
347 $encoding = 'base64url';
350 $signable_data = $data . '.' . base64url_encode($type) . '.'
351 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
353 $signature = rsa_sign($signable_data,$prvkey);
354 $sig = base64url_encode($signature);
356 $decrypted_header = <<< EOT
359 <aes_key>$b_inner_aes_key</aes_key>
360 <author_id>$handle</author_id>
364 $decrypted_header = pkcs5_pad($decrypted_header,16);
366 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
368 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
370 $encrypted_outer_key_bundle = '';
371 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
373 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
375 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
377 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
378 'ciphertext' => base64_encode($ciphertext)));
379 $cipher_json = base64_encode($encrypted_header_json_object);
381 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
384 <?xml version='1.0' encoding='UTF-8'?>
385 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
388 <me:encoding>base64url</me:encoding>
389 <me:alg>RSA-SHA256</me:alg>
390 <me:data type="application/xml">$data</me:data>
391 <me:sig>$sig</me:sig>
396 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
403 * diaspora_decode($importer,$xml)
404 * array $importer -> from user table
405 * string $xml -> urldecoded Diaspora salmon
408 * 'message' -> decoded Diaspora XML message
409 * 'author' -> author diaspora handle
410 * 'key' -> author public key (converted to pkcs#8)
412 * Author and key are used elsewhere to save a lookup for verifying replies and likes
416 function diaspora_decode($importer,$xml) {
419 $basedom = parse_xml_string($xml);
421 $children = $basedom->children('https://joindiaspora.com/protocol');
423 if($children->header) {
425 $author_link = str_replace('acct:','',$children->header->author_id);
429 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
431 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
432 $ciphertext = base64_decode($encrypted_header->ciphertext);
434 $outer_key_bundle = '';
435 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
437 $j_outer_key_bundle = json_decode($outer_key_bundle);
439 $outer_iv = base64_decode($j_outer_key_bundle->iv);
440 $outer_key = base64_decode($j_outer_key_bundle->key);
442 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
445 $decrypted = pkcs5_unpad($decrypted);
448 * $decrypted now contains something like
451 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
452 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
457 * <name>Ryan Hughes</name>
458 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
463 * <author_id>galaxor@diaspora.priateship.org</author_id>
467 * </decrypted_header>
470 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
471 $idom = parse_xml_string($decrypted,false);
473 $inner_iv = base64_decode($idom->iv);
474 $inner_aes_key = base64_decode($idom->aes_key);
476 $author_link = str_replace('acct:','',$idom->author_id);
480 $dom = $basedom->children(NAMESPACE_SALMON_ME);
482 // figure out where in the DOM tree our data is hiding
484 if($dom->provenance->data)
485 $base = $dom->provenance;
486 elseif($dom->env->data)
492 logger('mod-diaspora: unable to locate salmon data in xml ');
493 http_status_exit(400);
497 // Stash the signature away for now. We have to find their key or it won't be good for anything.
498 $signature = base64url_decode($base->sig);
502 // strip whitespace so our data element will return to one big base64 blob
503 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
506 // stash away some other stuff for later
508 $type = $base->data[0]->attributes()->type[0];
509 $keyhash = $base->sig[0]->attributes()->keyhash[0];
510 $encoding = $base->encoding;
514 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
518 $data = base64url_decode($data);
522 $inner_decrypted = $data;
526 // Decode the encrypted blob
528 $inner_encrypted = base64_decode($data);
529 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
530 $inner_decrypted = pkcs5_unpad($inner_decrypted);
534 logger('mod-diaspora: Could not retrieve author URI.');
535 http_status_exit(400);
538 // Once we have the author URI, go to the web and try to find their public key
539 // (first this will look it up locally if it is in the fcontact cache)
540 // This will also convert diaspora public key from pkcs#1 to pkcs#8
542 logger('mod-diaspora: Fetching key for ' . $author_link );
543 $key = get_diaspora_key($author_link);
546 logger('mod-diaspora: Could not retrieve author key.');
547 http_status_exit(400);
550 $verify = rsa_verify($signed_data,$signature,$key);
553 logger('mod-diaspora: Message did not verify. Discarding.');
554 http_status_exit(400);
557 logger('mod-diaspora: Message verified.');
559 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
564 function diaspora_request($importer,$xml) {
568 $sender_handle = unxmlify($xml->sender_handle);
569 $recipient_handle = unxmlify($xml->recipient_handle);
571 if(! $sender_handle || ! $recipient_handle)
574 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
578 // perhaps we were already sharing with this person. Now they're sharing with us.
579 // That makes us friends.
581 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
582 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
583 intval(CONTACT_IS_FRIEND),
584 intval($contact['id']),
585 intval($importer['uid'])
590 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
591 intval($importer['uid'])
594 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
595 require_once('include/items.php');
597 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
598 intval($importer['uid'])
601 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
603 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
606 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
607 $arr['uid'] = $importer['uid'];
608 $arr['contact-id'] = $self[0]['id'];
610 $arr['type'] = 'wall';
613 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
614 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
615 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
616 $arr['verb'] = ACTIVITY_FRIEND;
617 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
619 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
620 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
621 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
622 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
624 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
625 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
626 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
627 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
628 $arr['object'] .= '</link></object>' . "\n";
629 $arr['last-child'] = 1;
631 $arr['allow_cid'] = $user[0]['allow_cid'];
632 $arr['allow_gid'] = $user[0]['allow_gid'];
633 $arr['deny_cid'] = $user[0]['deny_cid'];
634 $arr['deny_gid'] = $user[0]['deny_gid'];
636 $i = item_store($arr);
638 proc_run('php',"include/notifier.php","activity","$i");
647 $ret = find_diaspora_person_by_handle($sender_handle);
650 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
651 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
655 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
659 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
660 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
661 intval($importer['uid']),
662 dbesc($ret['network']),
666 dbesc(normalise_link($ret['url'])),
670 dbesc($ret['photo']),
671 dbesc($ret['pubkey']),
672 dbesc($ret['notify']),
678 // find the contact record we just created
680 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
682 if(! $contact_record) {
683 logger('diaspora_request: unable to locate newly created contact record.');
687 $g = q("select def_gid from user where uid = %d limit 1",
688 intval($importer['uid'])
690 if($g && intval($g[0]['def_gid'])) {
691 require_once('include/group.php');
692 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
695 if($importer['page-flags'] == PAGE_NORMAL) {
697 $hash = random_string() . (string) time(); // Generate a confirm_key
699 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
700 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
701 intval($importer['uid']),
702 intval($contact_record['id']),
705 dbesc( t('Sharing notification from Diaspora network')),
707 dbesc(datetime_convert())
712 // automatic friend approval
714 require_once('include/Photo.php');
716 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
718 // technically they are sharing with us (CONTACT_IS_SHARING),
719 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
720 // we are going to change the relationship and make them a follower.
722 if($importer['page-flags'] == PAGE_FREELOVE)
723 $new_relation = CONTACT_IS_FRIEND;
725 $new_relation = CONTACT_IS_FOLLOWER;
727 $r = q("UPDATE `contact` SET
734 `avatar-date` = '%s',
743 intval($new_relation),
744 dbesc(datetime_convert()),
745 dbesc(datetime_convert()),
746 dbesc(datetime_convert()),
747 intval($contact_record['id'])
750 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
752 $ret = diaspora_share($u[0],$contact_record);
758 function diaspora_post_allow($importer,$contact) {
760 // perhaps we were already sharing with this person. Now they're sharing with us.
761 // That makes us friends.
762 // Normally this should have handled by getting a request - but this could get lost
763 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
764 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
765 intval(CONTACT_IS_FRIEND),
766 intval($contact['id']),
767 intval($importer['uid'])
769 $contact['rel'] = CONTACT_IS_FRIEND;
770 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
773 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
775 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
777 if($contact['rel'] == CONTACT_IS_FOLLOWER)
778 if($importer['page-flags'] == PAGE_COMMUNITY)
783 function diaspora_is_redmatrix($url) {
784 return(strstr($url, "/channel/"));
787 function diaspora_plink($addr, $guid) {
788 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", $addr);
792 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
794 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
795 // So we try another way as well.
796 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
798 $r[0]["network"] = $s[0]["network"];
800 if ($r[0]["network"] == NETWORK_DFRN)
801 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
803 if (diaspora_is_redmatrix($r[0]["url"]))
804 return $r[0]["url"]."/?f=&mid=".$guid;
806 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
809 function diaspora_post($importer,$xml,$msg) {
812 $guid = notags(unxmlify($xml->guid));
813 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
815 if($diaspora_handle != $msg['author']) {
816 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
820 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
824 if(! diaspora_post_allow($importer,$contact)) {
825 logger('diaspora_post: Ignoring this author.');
829 $message_id = $diaspora_handle . ':' . $guid;
830 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
831 intval($importer['uid']),
836 logger('diaspora_post: message exists: ' . $guid);
840 $created = unxmlify($xml->created_at);
841 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
843 $body = diaspora2bb($xml->raw_message);
847 $datarray["object"] = json_encode($xml);
849 if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
850 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
852 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
853 // Add OEmbed and other information to the body
854 if (!diaspora_is_redmatrix($contact['url']))
855 $body = add_page_info_to_body($body, false, true);
860 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
862 foreach($matches as $mtch) {
863 if(strlen($str_tags))
865 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
869 $plink = diaspora_plink($diaspora_handle, $guid);
871 $datarray['uid'] = $importer['uid'];
872 $datarray['contact-id'] = $contact['id'];
873 $datarray['wall'] = 0;
874 $datarray['network'] = NETWORK_DIASPORA;
875 $datarray['verb'] = ACTIVITY_POST;
876 $datarray['guid'] = $guid;
877 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
878 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
879 $datarray['private'] = $private;
880 $datarray['parent'] = 0;
881 $datarray['plink'] = $plink;
882 $datarray['owner-name'] = $contact['name'];
883 $datarray['owner-link'] = $contact['url'];
884 //$datarray['owner-avatar'] = $contact['thumb'];
885 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
886 $datarray['author-name'] = $contact['name'];
887 $datarray['author-link'] = $contact['url'];
888 $datarray['author-avatar'] = $contact['thumb'];
889 $datarray['body'] = $body;
890 $datarray['tag'] = $str_tags;
891 if ($xml->provider_display_name)
892 $datarray["app"] = unxmlify($xml->provider_display_name);
894 $datarray['app'] = 'Diaspora';
896 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
898 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
900 DiasporaFetchGuid($datarray);
901 $message_id = item_store($datarray);
907 function DiasporaFetchGuid($item) {
908 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
909 function ($match) use ($item){
910 return(DiasporaFetchGuidSub($match, $item));
914 function DiasporaFetchGuidSub($match, $item) {
917 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
918 diaspora_store_by_guid($match[1], $item["owner-link"]);
921 function diaspora_store_by_guid($guid, $server, $uid = 0) {
922 require_once("include/Contact.php");
924 $serverparts = parse_url($server);
925 $server = $serverparts["scheme"]."://".$serverparts["host"];
927 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
929 $item = diaspora_fetch_message($guid, $server);
934 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
936 $body = $item["body"];
937 $str_tags = $item["tag"];
939 $created = $item["created"];
940 $author = $item["author"];
941 $guid = $item["guid"];
942 $private = $item["private"];
943 $object = $item["object"];
944 $objecttype = $item["object-type"];
946 $message_id = $author.':'.$guid;
947 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
955 $person = find_diaspora_person_by_handle($author);
958 $datarray['uid'] = $uid;
959 $datarray['contact-id'] = get_contact($person['url'], $uid);
960 $datarray['wall'] = 0;
961 $datarray['network'] = NETWORK_DIASPORA;
962 $datarray['guid'] = $guid;
963 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
964 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
965 $datarray['private'] = $private;
966 $datarray['parent'] = 0;
967 $datarray['plink'] = diaspora_plink($author, $guid);
968 $datarray['author-name'] = $person['name'];
969 $datarray['author-link'] = $person['url'];
970 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
971 $datarray['owner-name'] = $datarray['author-name'];
972 $datarray['owner-link'] = $datarray['author-link'];
973 $datarray['owner-avatar'] = $datarray['author-avatar'];
974 $datarray['body'] = $body;
975 $datarray['tag'] = $str_tags;
976 $datarray['app'] = $app;
977 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
978 $datarray['object'] = $object;
979 $datarray['object-type'] = $objecttype;
981 if ($datarray['contact-id'] == 0)
984 DiasporaFetchGuid($datarray);
985 $message_id = item_store($datarray);
988 // Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
993 function diaspora_fetch_message($guid, $server, $level = 0) {
1000 // This will not work if the server is not a Diaspora server
1001 $source_url = $server.'/p/'.$guid.'.xml';
1002 $x = fetch_url($source_url);
1006 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1007 $source_xml = parse_xml_string($x,false);
1010 $item["app"] = 'Diaspora';
1011 $item["guid"] = $guid;
1014 if ($source_xml->post->status_message->created_at)
1015 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1017 if ($source_xml->post->status_message->provider_display_name)
1018 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1020 if ($source_xml->post->status_message->diaspora_handle)
1021 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1023 if ($source_xml->post->status_message->guid)
1024 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1026 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1027 $item["object"] = json_encode($source_xml->post);
1029 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1030 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1031 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1032 $body = scale_external_images($body,false);
1033 } elseif($source_xml->post->asphoto->image_url) {
1034 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1035 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1036 $body = scale_external_images($body);
1037 } elseif($source_xml->post->status_message) {
1038 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1040 // Checking for embedded pictures
1041 if($source_xml->post->status_message->photo->remote_photo_path AND
1042 $source_xml->post->status_message->photo->remote_photo_name) {
1044 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1046 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1047 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1049 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1051 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1053 $item["object-type"] = ACTIVITY_OBJ_NOTE;
1055 $body = scale_external_images($body);
1057 // Add OEmbed and other information to the body
1058 // To-Do: It could be a repeated redmatrix item
1059 // Then we shouldn't add further data to it
1060 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1061 $body = add_page_info_to_body($body, false, true);
1063 } elseif($source_xml->post->reshare) {
1064 // Reshare of a reshare
1065 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1067 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1068 logger('no content found: '.print_r($source_xml,true));
1072 if (trim($body) == "")
1076 $item["body"] = $body;
1081 function diaspora_reshare($importer,$xml,$msg) {
1083 logger('diaspora_reshare: init: ' . print_r($xml,true));
1086 $guid = notags(unxmlify($xml->guid));
1087 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1090 if($diaspora_handle != $msg['author']) {
1091 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1095 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1099 if(! diaspora_post_allow($importer,$contact)) {
1100 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1104 $message_id = $diaspora_handle . ':' . $guid;
1105 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1106 intval($importer['uid']),
1111 logger('diaspora_reshare: message exists: ' . $guid);
1115 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1116 $orig_guid = notags(unxmlify($xml->root_guid));
1117 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1119 $create_original_post = false;
1121 // Do we already have this item?
1122 $r = q("SELECT `body`, `tag`, `app`, `created`, `plink`, `object`, `object-type`, `uri` FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1124 dbesc(NETWORK_DIASPORA)
1127 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1129 // Maybe it is already a reshared item?
1130 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1131 require_once('include/api.php');
1132 if (api_share_as_retweet($r[0]))
1135 $body = $r[0]["body"];
1136 $str_tags = $r[0]["tag"];
1137 $app = $r[0]["app"];
1138 $orig_created = $r[0]["created"];
1139 $orig_plink = $r[0]["plink"];
1140 $orig_uri = $r[0]["uri"];
1141 $object = $r[0]["object"];
1142 $objecttype = $r[0]["object-type"];
1151 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1152 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1153 $item = diaspora_fetch_message($orig_guid, $server);
1156 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1157 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1158 $item = diaspora_fetch_message($orig_guid, $server);
1161 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1162 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1163 $item = diaspora_fetch_message($orig_guid, $server);
1166 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1167 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1168 $item = diaspora_fetch_message($orig_guid, $server);
1172 $body = $item["body"];
1173 $str_tags = $item["tag"];
1174 $app = $item["app"];
1175 $orig_created = $item["created"];
1176 $orig_author = $item["author"];
1177 $orig_guid = $item["guid"];
1178 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1179 $orig_uri = $orig_author.':'.$orig_guid;
1180 $create_original_post = ($body != "");
1181 $object = $item["object"];
1182 $objecttype = $item["object-type"];
1186 $plink = diaspora_plink($diaspora_handle, $guid);
1188 $person = find_diaspora_person_by_handle($orig_author);
1190 $created = unxmlify($xml->created_at);
1191 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1193 $datarray = array();
1195 $datarray['uid'] = $importer['uid'];
1196 $datarray['contact-id'] = $contact['id'];
1197 $datarray['wall'] = 0;
1198 $datarray['network'] = NETWORK_DIASPORA;
1199 $datarray['guid'] = $guid;
1200 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1201 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1202 $datarray['private'] = $private;
1203 $datarray['parent'] = 0;
1204 $datarray['plink'] = $plink;
1205 $datarray['owner-name'] = $contact['name'];
1206 $datarray['owner-link'] = $contact['url'];
1207 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1208 if (!intval(get_config('system','wall-to-wall_share'))) {
1209 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1211 $datarray['author-name'] = $contact['name'];
1212 $datarray['author-link'] = $contact['url'];
1213 $datarray['author-avatar'] = $contact['thumb'];
1214 $datarray['body'] = $prefix.$body."[/share]";
1216 // Let reshared messages look like wall-to-wall posts
1217 $datarray['author-name'] = $person['name'];
1218 $datarray['author-link'] = $person['url'];
1219 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1220 $datarray['body'] = $body;
1223 $datarray["object"] = json_encode($xml);
1224 $datarray['object-type'] = $objecttype;
1226 $datarray['tag'] = $str_tags;
1227 $datarray['app'] = $app;
1229 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1230 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1232 // Store the original item of a reshare
1233 if ($create_original_post) {
1234 require_once("include/Contact.php");
1236 $datarray2 = $datarray;
1238 $datarray2['uid'] = 0;
1239 $datarray2['contact-id'] = get_contact($person['url'], 0);
1240 $datarray2['guid'] = $orig_guid;
1241 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1242 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1243 $datarray2['parent'] = 0;
1244 $datarray2['plink'] = $orig_plink;
1246 $datarray2['author-name'] = $person['name'];
1247 $datarray2['author-link'] = $person['url'];
1248 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1249 $datarray2['owner-name'] = $datarray2['author-name'];
1250 $datarray2['owner-link'] = $datarray2['author-link'];
1251 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1252 $datarray2['body'] = $body;
1253 $datarray2["object"] = $object;
1255 DiasporaFetchGuid($datarray2);
1256 $message_id = item_store($datarray2);
1258 logger("Store original item ".$orig_guid." under message id ".$message_id);
1261 DiasporaFetchGuid($datarray);
1262 $message_id = item_store($datarray);
1269 function diaspora_asphoto($importer,$xml,$msg) {
1270 logger('diaspora_asphoto called');
1273 $guid = notags(unxmlify($xml->guid));
1274 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1276 if($diaspora_handle != $msg['author']) {
1277 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1281 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1285 if(! diaspora_post_allow($importer,$contact)) {
1286 logger('diaspora_asphoto: Ignoring this author.');
1290 $message_id = $diaspora_handle . ':' . $guid;
1291 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1292 intval($importer['uid']),
1297 logger('diaspora_asphoto: message exists: ' . $guid);
1301 $created = unxmlify($xml->created_at);
1302 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1304 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1305 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1306 $body = scale_external_images($body,false);
1308 elseif($xml->image_url) {
1309 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1310 $body = scale_external_images($body);
1313 logger('diaspora_asphoto: no photo url found.');
1317 $plink = diaspora_plink($diaspora_handle, $guid);
1319 $datarray = array();
1321 $datarray['uid'] = $importer['uid'];
1322 $datarray['contact-id'] = $contact['id'];
1323 $datarray['wall'] = 0;
1324 $datarray['network'] = NETWORK_DIASPORA;
1325 $datarray['guid'] = $guid;
1326 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1327 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1328 $datarray['private'] = $private;
1329 $datarray['parent'] = 0;
1330 $datarray['plink'] = $plink;
1331 $datarray['owner-name'] = $contact['name'];
1332 $datarray['owner-link'] = $contact['url'];
1333 //$datarray['owner-avatar'] = $contact['thumb'];
1334 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1335 $datarray['author-name'] = $contact['name'];
1336 $datarray['author-link'] = $contact['url'];
1337 $datarray['author-avatar'] = $contact['thumb'];
1338 $datarray['body'] = $body;
1339 $datarray["object"] = json_encode($xml);
1340 $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1342 $datarray['app'] = 'Diaspora/Cubbi.es';
1344 DiasporaFetchGuid($datarray);
1345 $message_id = item_store($datarray);
1348 // q("update item set plink = '%s' where id = %d",
1349 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1350 // intval($message_id)
1363 function diaspora_comment($importer,$xml,$msg) {
1366 $guid = notags(unxmlify($xml->guid));
1367 $parent_guid = notags(unxmlify($xml->parent_guid));
1368 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1369 $target_type = notags(unxmlify($xml->target_type));
1370 $text = unxmlify($xml->text);
1371 $author_signature = notags(unxmlify($xml->author_signature));
1373 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1375 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1377 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1381 if(! diaspora_post_allow($importer,$contact)) {
1382 logger('diaspora_comment: Ignoring this author.');
1386 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1387 intval($importer['uid']),
1391 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1395 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1396 intval($importer['uid']),
1401 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1404 $person = find_diaspora_person_by_handle($diaspora_handle);
1405 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1409 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1411 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1412 intval($importer['uid']),
1419 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1422 $parent_item = $r[0];
1425 /* How Diaspora performs comment signature checking:
1427 - If an item has been sent by the comment author to the top-level post owner to relay on
1428 to the rest of the contacts on the top-level post, the top-level post owner should check
1429 the author_signature, then create a parent_author_signature before relaying the comment on
1430 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1431 check only the parent_author_signature. Basically, they trust that the top-level post
1432 owner has already verified the authenticity of anything he/she sends out
1433 - In either case, the signature that get checked is the signature created by the person
1437 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1440 if($parent_author_signature) {
1441 // If a parent_author_signature exists, then we've received the comment
1442 // relayed from the top-level post owner. There's no need to check the
1443 // author_signature if the parent_author_signature is valid
1445 $parent_author_signature = base64_decode($parent_author_signature);
1447 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1448 logger('diaspora_comment: top-level owner verification failed.');
1453 // If there's no parent_author_signature, then we've received the comment
1454 // from the comment creator. In that case, the person is commenting on
1455 // our post, so he/she must be a contact of ours and his/her public key
1456 // should be in $msg['key']
1458 $author_signature = base64_decode($author_signature);
1460 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1461 logger('diaspora_comment: comment author verification failed.');
1466 // Phew! Everything checks out. Now create an item.
1468 // Find the original comment author information.
1469 // We need this to make sure we display the comment author
1470 // information (name and avatar) correctly.
1471 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1474 $person = find_diaspora_person_by_handle($diaspora_handle);
1476 if(! is_array($person)) {
1477 logger('diaspora_comment: unable to find author details');
1482 $body = diaspora2bb($text);
1483 $message_id = $diaspora_handle . ':' . $guid;
1485 $datarray = array();
1487 $datarray['uid'] = $importer['uid'];
1488 $datarray['contact-id'] = $contact['id'];
1489 $datarray['type'] = 'remote-comment';
1490 $datarray['wall'] = $parent_item['wall'];
1491 $datarray['network'] = NETWORK_DIASPORA;
1492 $datarray['verb'] = ACTIVITY_POST;
1493 $datarray['gravity'] = GRAVITY_COMMENT;
1494 $datarray['guid'] = $guid;
1495 $datarray['uri'] = $message_id;
1496 $datarray['parent-uri'] = $parent_item['uri'];
1498 // No timestamps for comments? OK, we'll the use current time.
1499 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1500 $datarray['private'] = $parent_item['private'];
1502 $datarray['owner-name'] = $parent_item['owner-name'];
1503 $datarray['owner-link'] = $parent_item['owner-link'];
1504 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1506 $datarray['author-name'] = $person['name'];
1507 $datarray['author-link'] = $person['url'];
1508 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1509 $datarray['body'] = $body;
1510 $datarray["object"] = json_encode($xml);
1511 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1513 // We can't be certain what the original app is if the message is relayed.
1514 if(($parent_item['origin']) && (! $parent_author_signature))
1515 $datarray['app'] = 'Diaspora';
1517 DiasporaFetchGuid($datarray);
1518 $message_id = item_store($datarray);
1520 $datarray['id'] = $message_id;
1523 //q("update item set plink = '%s' where id = %d",
1524 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1525 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1526 // intval($message_id)
1530 if(($parent_item['origin']) && (! $parent_author_signature)) {
1531 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1532 intval($message_id),
1533 dbesc($signed_data),
1534 dbesc(base64_encode($author_signature)),
1535 dbesc($diaspora_handle)
1538 // if the message isn't already being relayed, notify others
1539 // the existence of parent_author_signature means the parent_author or owner
1540 // is already relaying.
1542 proc_run('php','include/notifier.php','comment-import',$message_id);
1545 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1546 dbesc($parent_item['uri']),
1547 intval($importer['uid'])
1550 if(count($myconv)) {
1551 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1553 foreach($myconv as $conv) {
1555 // now if we find a match, it means we're in this conversation
1557 if(! link_compare($conv['author-link'],$importer_url))
1560 require_once('include/enotify.php');
1562 $conv_parent = $conv['parent'];
1565 'type' => NOTIFY_COMMENT,
1566 'notify_flags' => $importer['notify-flags'],
1567 'language' => $importer['language'],
1568 'to_name' => $importer['username'],
1569 'to_email' => $importer['email'],
1570 'uid' => $importer['uid'],
1571 'item' => $datarray,
1572 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1573 'source_name' => $datarray['author-name'],
1574 'source_link' => $datarray['author-link'],
1575 'source_photo' => $datarray['author-avatar'],
1576 'verb' => ACTIVITY_POST,
1578 'parent' => $conv_parent,
1579 'parent_uri' => $parent_uri
1582 // only send one notification
1592 function diaspora_conversation($importer,$xml,$msg) {
1596 $guid = notags(unxmlify($xml->guid));
1597 $subject = notags(unxmlify($xml->subject));
1598 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1599 $participant_handles = notags(unxmlify($xml->participant_handles));
1600 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1602 $parent_uri = $diaspora_handle . ':' . $guid;
1604 $messages = $xml->message;
1606 if(! count($messages)) {
1607 logger('diaspora_conversation: empty conversation');
1611 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1613 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1617 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1618 logger('diaspora_conversation: Ignoring this author.');
1622 $conversation = null;
1624 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1625 intval($importer['uid']),
1629 $conversation = $c[0];
1631 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1632 intval($importer['uid']),
1634 dbesc($diaspora_handle),
1635 dbesc(datetime_convert('UTC','UTC',$created_at)),
1636 dbesc(datetime_convert()),
1638 dbesc($participant_handles)
1641 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1642 intval($importer['uid']),
1646 $conversation = $c[0];
1648 if(! $conversation) {
1649 logger('diaspora_conversation: unable to create conversation.');
1653 foreach($messages as $mesg) {
1657 $msg_guid = notags(unxmlify($mesg->guid));
1658 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1659 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1660 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1661 $msg_text = unxmlify($mesg->text);
1662 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1663 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1664 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1665 if($msg_conversation_guid != $guid) {
1666 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1670 $body = diaspora2bb($msg_text);
1671 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1673 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1675 $author_signature = base64_decode($msg_author_signature);
1677 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1682 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1684 if(is_array($person) && x($person,'pubkey'))
1685 $key = $person['pubkey'];
1687 logger('diaspora_conversation: unable to find author details');
1692 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1693 logger('diaspora_conversation: verification failed.');
1697 if($msg_parent_author_signature) {
1698 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1700 $parent_author_signature = base64_decode($msg_parent_author_signature);
1704 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1705 logger('diaspora_conversation: owner verification failed.');
1710 $r = q("select id from mail where `uri` = '%s' limit 1",
1714 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1718 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')",
1719 intval($importer['uid']),
1721 intval($conversation['id']),
1722 dbesc($person['name']),
1723 dbesc($person['photo']),
1724 dbesc($person['url']),
1725 intval($contact['id']),
1732 dbesc($msg_created_at)
1735 q("update conv set updated = '%s' where id = %d",
1736 dbesc(datetime_convert()),
1737 intval($conversation['id'])
1740 require_once('include/enotify.php');
1742 'type' => NOTIFY_MAIL,
1743 'notify_flags' => $importer['notify-flags'],
1744 'language' => $importer['language'],
1745 'to_name' => $importer['username'],
1746 'to_email' => $importer['email'],
1747 'uid' =>$importer['uid'],
1748 'item' => array('subject' => $subject, 'body' => $body),
1749 'source_name' => $person['name'],
1750 'source_link' => $person['url'],
1751 'source_photo' => $person['thumb'],
1752 'verb' => ACTIVITY_POST,
1760 function diaspora_message($importer,$xml,$msg) {
1764 $msg_guid = notags(unxmlify($xml->guid));
1765 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1766 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1767 $msg_author_signature = notags(unxmlify($xml->author_signature));
1768 $msg_text = unxmlify($xml->text);
1769 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1770 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1771 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1773 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1775 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1777 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1781 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1782 logger('diaspora_message: Ignoring this author.');
1786 $conversation = null;
1788 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1789 intval($importer['uid']),
1790 dbesc($msg_conversation_guid)
1793 $conversation = $c[0];
1795 logger('diaspora_message: conversation not available.');
1801 $body = diaspora2bb($msg_text);
1802 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1804 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1807 $author_signature = base64_decode($msg_author_signature);
1809 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1810 if(is_array($person) && x($person,'pubkey'))
1811 $key = $person['pubkey'];
1813 logger('diaspora_message: unable to find author details');
1817 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1818 logger('diaspora_message: verification failed.');
1822 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1824 intval($importer['uid'])
1827 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1831 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')",
1832 intval($importer['uid']),
1834 intval($conversation['id']),
1835 dbesc($person['name']),
1836 dbesc($person['photo']),
1837 dbesc($person['url']),
1838 intval($contact['id']),
1839 dbesc($conversation['subject']),
1845 dbesc($msg_created_at)
1848 q("update conv set updated = '%s' where id = %d",
1849 dbesc(datetime_convert()),
1850 intval($conversation['id'])
1857 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1861 logger('diaspora_photo: init',LOGGER_DEBUG);
1863 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1865 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1867 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1869 $guid = notags(unxmlify($xml->guid));
1871 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1873 $public = notags(unxmlify($xml->public));
1875 $created_at = notags(unxmlify($xml_created_at));
1877 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1879 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1881 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1885 if(! diaspora_post_allow($importer,$contact)) {
1886 logger('diaspora_photo: Ignoring this author.');
1890 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1891 intval($importer['uid']),
1892 dbesc($status_message_guid)
1895 /* deactivated by now since it can lead to multiplicated pictures in posts.
1897 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1900 $person = find_diaspora_person_by_handle($diaspora_handle);
1901 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1905 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1907 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1908 intval($importer['uid']),
1909 dbesc($status_message_guid)
1916 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1917 intval($importer['uid']),
1918 dbesc(serialize($msg)),
1919 intval($attempt + 1)
1923 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1927 $parent_item = $r[0];
1929 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1931 $link_text = scale_external_images($link_text, true,
1932 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1934 if(strpos($parent_item['body'],$link_text) === false) {
1935 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1936 dbesc($link_text . $parent_item['body']),
1937 intval($parent_item['id']),
1938 intval($parent_item['uid'])
1940 update_thread($parent_item['id']);
1949 function diaspora_like($importer,$xml,$msg) {
1952 $guid = notags(unxmlify($xml->guid));
1953 $parent_guid = notags(unxmlify($xml->parent_guid));
1954 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1955 $target_type = notags(unxmlify($xml->target_type));
1956 $positive = notags(unxmlify($xml->positive));
1957 $author_signature = notags(unxmlify($xml->author_signature));
1959 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1961 // likes on comments not supported here and likes on photos not supported by Diaspora
1963 // if($target_type !== 'Post')
1966 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1968 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1972 if(! diaspora_post_allow($importer,$contact)) {
1973 logger('diaspora_like: Ignoring this author.');
1977 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1978 intval($importer['uid']),
1983 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1986 $person = find_diaspora_person_by_handle($diaspora_handle);
1987 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1991 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1993 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1994 intval($importer['uid']),
2001 logger('diaspora_like: parent item not found: ' . $guid);
2005 $parent_item = $r[0];
2007 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2008 intval($importer['uid']),
2012 if($positive === 'true') {
2013 logger('diaspora_like: duplicate like: ' . $guid);
2016 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2017 // It looks like "RelayableRetractions" are used for "unlike" instead
2018 if($positive === 'false') {
2019 logger('diaspora_like: received a like with positive set to "false"...ignoring');
2020 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2021 intval($r[0]['id']),
2022 intval($importer['uid'])
2024 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2025 // send notification via proc_run()
2029 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2030 // It looks like "RelayableRetractions" are used for "unlike" instead
2031 if($positive === 'false') {
2032 logger('diaspora_like: received a like with positive set to "false"');
2033 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2038 /* How Diaspora performs "like" signature checking:
2040 - If an item has been sent by the like author to the top-level post owner to relay on
2041 to the rest of the contacts on the top-level post, the top-level post owner should check
2042 the author_signature, then create a parent_author_signature before relaying the like on
2043 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2044 check only the parent_author_signature. Basically, they trust that the top-level post
2045 owner has already verified the authenticity of anything he/she sends out
2046 - In either case, the signature that get checked is the signature created by the person
2050 // Diaspora has changed the way they are signing the likes.
2051 // Just to make sure that we don't miss any likes we will check the old and the current way.
2052 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2054 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2058 if ($parent_author_signature) {
2059 // If a parent_author_signature exists, then we've received the like
2060 // relayed from the top-level post owner. There's no need to check the
2061 // author_signature if the parent_author_signature is valid
2063 $parent_author_signature = base64_decode($parent_author_signature);
2065 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2066 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2068 logger('diaspora_like: top-level owner verification failed.');
2072 // If there's no parent_author_signature, then we've received the like
2073 // from the like creator. In that case, the person is "like"ing
2074 // our post, so he/she must be a contact of ours and his/her public key
2075 // should be in $msg['key']
2077 $author_signature = base64_decode($author_signature);
2079 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2080 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2082 logger('diaspora_like: like creator verification failed.');
2087 // Phew! Everything checks out. Now create an item.
2089 // Find the original comment author information.
2090 // We need this to make sure we display the comment author
2091 // information (name and avatar) correctly.
2092 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2095 $person = find_diaspora_person_by_handle($diaspora_handle);
2097 if(! is_array($person)) {
2098 logger('diaspora_like: unable to find author details');
2103 $uri = $diaspora_handle . ':' . $guid;
2105 $activity = ACTIVITY_LIKE;
2106 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2107 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2108 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2109 $body = $parent_item['body'];
2114 <type>$objtype</type>
2116 <id>{$parent_item['uri']}</id>
2119 <content>$body</content>
2122 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2127 $arr['uid'] = $importer['uid'];
2128 $arr['guid'] = $guid;
2129 $arr['network'] = NETWORK_DIASPORA;
2130 $arr['contact-id'] = $contact['id'];
2131 $arr['type'] = 'activity';
2132 $arr['wall'] = $parent_item['wall'];
2133 $arr['gravity'] = GRAVITY_LIKE;
2134 $arr['parent'] = $parent_item['id'];
2135 $arr['parent-uri'] = $parent_item['uri'];
2137 $arr['owner-name'] = $parent_item['name'];
2138 $arr['owner-link'] = $parent_item['url'];
2139 //$arr['owner-avatar'] = $parent_item['thumb'];
2140 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2142 $arr['author-name'] = $person['name'];
2143 $arr['author-link'] = $person['url'];
2144 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2146 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2147 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2148 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2149 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2150 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2152 $arr['app'] = 'Diaspora';
2154 $arr['private'] = $parent_item['private'];
2155 $arr['verb'] = $activity;
2156 $arr['object-type'] = $objtype;
2157 $arr['object'] = $obj;
2158 $arr['visible'] = 1;
2160 $arr['last-child'] = 0;
2162 $message_id = item_store($arr);
2166 // q("update item set plink = '%s' where id = %d",
2167 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2168 // dbesc($a->get_baseurl().'/display/'.$guid),
2169 // intval($message_id)
2173 if(! $parent_author_signature) {
2174 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2175 intval($message_id),
2176 dbesc($signed_data),
2177 dbesc(base64_encode($author_signature)),
2178 dbesc($diaspora_handle)
2182 // if the message isn't already being relayed, notify others
2183 // the existence of parent_author_signature means the parent_author or owner
2184 // is already relaying. The parent_item['origin'] indicates the message was created on our system
2186 if(($parent_item['origin']) && (! $parent_author_signature))
2187 proc_run('php','include/notifier.php','comment-import',$message_id);
2192 function diaspora_retraction($importer,$xml) {
2195 $guid = notags(unxmlify($xml->guid));
2196 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2197 $type = notags(unxmlify($xml->type));
2199 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2203 if($type === 'Person') {
2204 require_once('include/Contact.php');
2205 contact_remove($contact['id']);
2207 elseif($type === 'Post') {
2208 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2210 intval($importer['uid'])
2213 if(link_compare($r[0]['author-link'],$contact['url'])) {
2214 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2215 dbesc(datetime_convert()),
2218 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2227 function diaspora_signed_retraction($importer,$xml,$msg) {
2230 $guid = notags(unxmlify($xml->target_guid));
2231 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2232 $type = notags(unxmlify($xml->target_type));
2233 $sig = notags(unxmlify($xml->target_author_signature));
2235 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2237 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2239 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2244 $signed_data = $guid . ';' . $type ;
2247 /* How Diaspora performs relayable_retraction signature checking:
2249 - If an item has been sent by the item author to the top-level post owner to relay on
2250 to the rest of the contacts on the top-level post, the top-level post owner checks
2251 the author_signature, then creates a parent_author_signature before relaying the item on
2252 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2253 check only the parent_author_signature. Basically, they trust that the top-level post
2254 owner has already verified the authenticity of anything he/she sends out
2255 - In either case, the signature that get checked is the signature created by the person
2259 if($parent_author_signature) {
2261 $parent_author_signature = base64_decode($parent_author_signature);
2263 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2264 logger('diaspora_signed_retraction: top-level post owner verification failed');
2271 $sig_decode = base64_decode($sig);
2273 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2274 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2279 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2280 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2282 intval($importer['uid'])
2285 if(link_compare($r[0]['author-link'],$contact['url'])) {
2286 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2287 dbesc(datetime_convert()),
2288 dbesc(datetime_convert()),
2291 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2293 // Now check if the retraction needs to be relayed by us
2295 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2296 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2297 // The only item with `parent` and `id` as the parent id is the parent item.
2298 $p = q("select origin from item where parent = %d and id = %d limit 1",
2303 if(($p[0]['origin']) && (! $parent_author_signature)) {
2304 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2306 dbesc($signed_data),
2308 dbesc($diaspora_handle)
2311 // the existence of parent_author_signature would have meant the parent_author or owner
2312 // is already relaying.
2313 logger('diaspora_signed_retraction: relaying relayable_retraction');
2315 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2322 logger('diaspora_signed_retraction: unknown type: ' . $type);
2328 function diaspora_profile($importer,$xml,$msg) {
2331 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2334 if($diaspora_handle != $msg['author']) {
2335 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2339 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2343 if($contact['blocked']) {
2344 logger('diaspora_post: Ignoring this author.');
2348 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2349 $image_url = unxmlify($xml->image_url);
2350 $birthday = unxmlify($xml->birthday);
2351 $location = diaspora2bb(unxmlify($xml->location));
2352 $about = diaspora2bb(unxmlify($xml->bio));
2353 $gender = unxmlify($xml->gender);
2354 $tags = unxmlify($xml->tag_string);
2356 $tags = explode("#", $tags);
2358 $keywords = array();
2359 foreach ($tags as $tag) {
2360 $tag = trim(strtolower($tag));
2365 $keywords = implode(", ", $keywords);
2367 $handle_parts = explode("@", $diaspora_handle);
2369 $name = $handle_parts[0];
2372 if( preg_match("|^https?://|", $image_url) === 0) {
2373 $image_url = "http://" . $handle_parts[1] . $image_url;
2376 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2377 intval($importer['uid']),
2378 intval($contact['id'])
2380 $oldphotos = ((count($r)) ? $r : null);*/
2382 require_once('include/Photo.php');
2384 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2386 // Generic birthday. We don't know the timezone. The year is irrelevant.
2388 $birthday = str_replace('1000','1901',$birthday);
2390 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2392 // this is to prevent multiple birthday notifications in a single year
2393 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2395 if(substr($birthday,5) === substr($contact['bd'],5))
2396 $birthday = $contact['bd'];
2398 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2399 // Not doing this currently because D* protocol is scheduled for revision soon.
2401 $r = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2403 dbesc(datetime_convert()),
2407 dbesc(datetime_convert()),
2413 intval($contact['id']),
2414 intval($importer['uid'])
2417 if (unxmlify($xml->searchable) == "true") {
2418 require_once('include/socgraph.php');
2419 poco_check($contact['url'], $name, NETWORK_DIASPORA, $images[0], $about, $location, $gender, $keywords, "",
2420 datetime_convert(), 2, $contact['id'], $importer['uid']);
2424 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
2425 dbesc(normalise_link($contact['url'])));
2427 if (count($author) == 0) {
2428 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`, `location`, `about`) VALUES ('%s', '%s', '%s', '%s', '%s')",
2429 dbesc(normalise_link($contact['url'])), dbesc($name), dbesc($location), dbesc($about), dbesc($images[0]));
2431 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
2432 dbesc(normalise_link($contact['url'])));
2433 } else if (normalise_link($contact['url']).$name.$location.$about != normalise_link($author[0]["url"]).$author[0]["name"].$author[0]["location"].$author[0]["about"]) {
2434 q("UPDATE unique_contacts SET name = '%s', avatar = '%s', `location` = '%s', `about` = '%s' WHERE url = '%s'",
2435 dbesc($name), dbesc($images[0]), dbesc($location), dbesc($about), dbesc(normalise_link($contact['url'])));
2440 foreach($oldphotos as $ph) {
2441 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2442 intval($importer['uid']),
2443 intval($contact['id']),
2444 dbesc($ph['resource-id'])
2454 function diaspora_share($me,$contact) {
2456 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2457 $theiraddr = $contact['addr'];
2459 $tpl = get_markup_template('diaspora_share.tpl');
2460 $msg = replace_macros($tpl, array(
2461 '$sender' => $myaddr,
2462 '$recipient' => $theiraddr
2465 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2466 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2468 return(diaspora_transmit($owner,$contact,$slap, false));
2471 function diaspora_unshare($me,$contact) {
2474 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2476 $tpl = get_markup_template('diaspora_retract.tpl');
2477 $msg = replace_macros($tpl, array(
2478 '$guid' => $me['guid'],
2479 '$type' => 'Person',
2480 '$handle' => $myaddr
2483 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2484 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2486 return(diaspora_transmit($owner,$contact,$slap, false));
2491 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2494 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2495 $theiraddr = $contact['addr'];
2499 $title = $item['title'];
2500 $body = $item['body'];
2503 // We're trying to match Diaspora's split message/photo protocol but
2504 // all the photos are displayed on D* as links and not img's - even
2505 // though we're sending pretty much precisely what they send us when
2506 // doing the same operation.
2507 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2508 // which seems to get through intact.
2510 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2512 foreach($matches as $mtch) {
2514 $detail['str'] = $mtch[0];
2515 $detail['path'] = dirname($mtch[1]) . '/';
2516 $detail['file'] = basename($mtch[1]);
2517 $detail['guid'] = $item['guid'];
2518 $detail['handle'] = $myaddr;
2519 $images[] = $detail;
2520 $body = str_replace($detail['str'],$mtch[1],$body);
2525 //if(strlen($title))
2526 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2528 // convert to markdown
2529 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2530 //$body = bb2diaspora($body);
2534 $body = "## ".html_entity_decode($title)."\n\n".$body;
2536 if($item['attach']) {
2537 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2539 $body .= "\n" . t('Attachments:') . "\n";
2540 foreach($matches as $mtch) {
2541 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2547 $public = (($item['private']) ? 'false' : 'true');
2549 require_once('include/datetime.php');
2550 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2552 // Detect a share element and do a reshare
2553 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2554 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2555 $tpl = get_markup_template('diaspora_reshare.tpl');
2556 $msg = replace_macros($tpl, array(
2557 '$root_handle' => xmlify($ret['root_handle']),
2558 '$root_guid' => $ret['root_guid'],
2559 '$guid' => $item['guid'],
2560 '$handle' => xmlify($myaddr),
2561 '$public' => $public,
2562 '$created' => $created,
2563 '$provider' => $item["app"]
2566 $tpl = get_markup_template('diaspora_post.tpl');
2567 $msg = replace_macros($tpl, array(
2569 '$guid' => $item['guid'],
2570 '$handle' => xmlify($myaddr),
2571 '$public' => $public,
2572 '$created' => $created,
2573 '$provider' => $item["app"]
2577 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2579 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2580 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2582 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2584 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2586 if(count($images)) {
2587 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2590 return $return_code;
2593 function diaspora_is_reshare($body) {
2594 $body = trim($body);
2596 // Skip if it isn't a pure repeated messages
2597 // Does it start with a share?
2598 if (strpos($body, "[share") > 0)
2601 // Does it end with a share?
2602 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2605 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2606 // Skip if there is no shared message in there
2607 if ($body == $attributes)
2611 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2612 if ($matches[1] != "")
2613 $guid = $matches[1];
2615 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2616 if ($matches[1] != "")
2617 $guid = $matches[1];
2620 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2621 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2624 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2625 $ret["root_guid"] = $guid;
2631 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2632 if ($matches[1] != "")
2633 $profile = $matches[1];
2635 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2636 if ($matches[1] != "")
2637 $profile = $matches[1];
2641 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2642 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2646 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2647 if ($matches[1] != "")
2648 $link = $matches[1];
2650 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2651 if ($matches[1] != "")
2652 $link = $matches[1];
2654 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2655 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2661 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2663 if(! count($images))
2665 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2667 $tpl = get_markup_template('diaspora_photo.tpl');
2668 foreach($images as $image) {
2669 if(! stristr($image['path'],$mysite))
2671 $resource = str_replace('.jpg','',$image['file']);
2672 $resource = substr($resource,0,strpos($resource,'-'));
2674 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2676 intval($owner['uid'])
2680 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2681 $msg = replace_macros($tpl,array(
2682 '$path' => xmlify($image['path']),
2683 '$filename' => xmlify($image['file']),
2684 '$msg_guid' => xmlify($image['guid']),
2685 '$guid' => xmlify($r[0]['guid']),
2686 '$handle' => xmlify($image['handle']),
2687 '$public' => xmlify($public),
2688 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2692 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2693 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2694 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2696 diaspora_transmit($owner,$contact,$slap,$public_batch);
2701 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2704 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2705 // $theiraddr = $contact['addr'];
2707 // Diaspora doesn't support threaded comments, but some
2708 // versions of Diaspora (i.e. Diaspora-pistos) support
2709 // likes on comments
2710 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2711 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2712 dbesc($item['thr-parent'])
2716 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2717 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2718 // The only item with `parent` and `id` as the parent id is the parent item.
2719 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2720 intval($item['parent']),
2721 intval($item['parent'])
2729 if($item['verb'] === ACTIVITY_LIKE) {
2730 $tpl = get_markup_template('diaspora_like.tpl');
2732 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2733 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2734 // $positive = (($item['deleted']) ? 'false' : 'true');
2737 if(($item['deleted']))
2738 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2741 $tpl = get_markup_template('diaspora_comment.tpl');
2745 $text = html_entity_decode(bb2diaspora($item['body']));
2750 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2752 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2754 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2756 $msg = replace_macros($tpl,array(
2757 '$guid' => xmlify($item['guid']),
2758 '$parent_guid' => xmlify($parent['guid']),
2759 '$target_type' =>xmlify($target_type),
2760 '$authorsig' => xmlify($authorsig),
2761 '$body' => xmlify($text),
2762 '$positive' => xmlify($positive),
2763 '$handle' => xmlify($myaddr)
2766 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2768 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2769 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2771 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2775 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2779 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2780 // $theiraddr = $contact['addr'];
2782 $body = $item['body'];
2783 $text = html_entity_decode(bb2diaspora($body));
2785 // Diaspora doesn't support threaded comments, but some
2786 // versions of Diaspora (i.e. Diaspora-pistos) support
2787 // likes on comments
2788 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2789 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2790 dbesc($item['thr-parent'])
2794 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2795 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2796 // The only item with `parent` and `id` as the parent id is the parent item.
2797 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2798 intval($item['parent']),
2799 intval($item['parent'])
2808 $relay_retract = false;
2809 $sql_sign_id = 'iid';
2810 if( $item['deleted']) {
2811 $relay_retract = true;
2813 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2815 $sql_sign_id = 'retract_iid';
2816 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2818 elseif($item['verb'] === ACTIVITY_LIKE) {
2821 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2822 // $positive = (($item['deleted']) ? 'false' : 'true');
2825 $tpl = get_markup_template('diaspora_like_relay.tpl');
2827 else { // item is a comment
2828 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2832 // fetch the original signature if the relayable was created by a Diaspora
2833 // or DFRN user. Relayables for other networks are not supported.
2835 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2840 $signed_text = $orig_sign['signed_text'];
2841 $authorsig = $orig_sign['signature'];
2842 $handle = $orig_sign['signer'];
2846 // Author signature information (for likes, comments, and retractions of likes or comments,
2847 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2848 // function is called
2849 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2853 /* Since the author signature is only checked by the parent, not by the relay recipients,
2854 * I think it may not be necessary for us to do so much work to preserve all the original
2855 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2856 * Let's just generate that and forget about all the original author signature stuff.
2858 * Note: this might be more of an problem if we want to support likes on comments for older
2859 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2860 * doing that, let's ignore it for now.
2862 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2866 $handle = diaspora_handle_from_contact($item['contact-id']);
2872 $sender_signed_text = $item['guid'] . ';' . $target_type;
2874 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2876 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2878 // Sign the relayable with the top-level owner's signature
2880 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2881 // stored in the database, because that provides the best chance that Diaspora will
2882 // be able to reconstruct the signed text the same way we did. This is particularly a
2883 // concern for the comment, whose signed text includes the text of the comment. The
2884 // smallest change in the text of the comment, including removing whitespace, will
2885 // make the signature verification fail. Since we translate from BB code to Diaspora's
2886 // markup at the top of this function, which is AFTER we placed the original $signed_text
2887 // in the database, it's hazardous to trust the original $signed_text.
2889 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2891 $msg = replace_macros($tpl,array(
2892 '$guid' => xmlify($item['guid']),
2893 '$parent_guid' => xmlify($parent['guid']),
2894 '$target_type' =>xmlify($target_type),
2895 '$authorsig' => xmlify($authorsig),
2896 '$parentsig' => xmlify($parentauthorsig),
2897 '$body' => xmlify($text),
2898 '$positive' => xmlify($positive),
2899 '$handle' => xmlify($handle)
2902 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2905 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2906 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2908 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2914 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2917 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2919 // Check whether the retraction is for a top-level post or whether it's a relayable
2920 if( $item['uri'] !== $item['parent-uri'] ) {
2922 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2923 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2927 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2928 $target_type = 'StatusMessage';
2931 $signed_text = $item['guid'] . ';' . $target_type;
2933 $msg = replace_macros($tpl, array(
2934 '$guid' => xmlify($item['guid']),
2935 '$type' => xmlify($target_type),
2936 '$handle' => xmlify($myaddr),
2937 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2940 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2941 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2943 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2946 function diaspora_send_mail($item,$owner,$contact) {
2949 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2951 $r = q("select * from conv where id = %d and uid = %d limit 1",
2952 intval($item['convid']),
2953 intval($item['uid'])
2957 logger('diaspora_send_mail: conversation not found.');
2963 'guid' => xmlify($cnv['guid']),
2964 'subject' => xmlify($cnv['subject']),
2965 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2966 'diaspora_handle' => xmlify($cnv['creator']),
2967 'participant_handles' => xmlify($cnv['recips'])
2970 $body = bb2diaspora($item['body']);
2971 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2973 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2974 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2976 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2979 'guid' => xmlify($item['guid']),
2980 'parent_guid' => xmlify($cnv['guid']),
2981 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2982 'author_signature' => xmlify($sig),
2983 'text' => xmlify($body),
2984 'created_at' => xmlify($created),
2985 'diaspora_handle' => xmlify($myaddr),
2986 'conversation_guid' => xmlify($cnv['guid'])
2989 if($item['reply']) {
2990 $tpl = get_markup_template('diaspora_message.tpl');
2991 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2994 $conv['messages'] = array($msg);
2995 $tpl = get_markup_template('diaspora_conversation.tpl');
2996 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2999 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3001 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3002 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3004 return(diaspora_transmit($owner,$contact,$slap,false));
3009 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
3011 $enabled = intval(get_config('system','diaspora_enabled'));
3017 $logid = random_string(4);
3018 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3020 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3024 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
3026 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3030 if (!intval(get_config('system','diaspora_test'))) {
3031 post_url($dest_url . '/', $slap);
3032 $return_code = $a->get_curl_code();
3034 logger('diaspora_transmit: test_mode');
3039 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
3041 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3042 logger('diaspora_transmit: queue message');
3044 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3045 intval($contact['id']),
3046 dbesc(NETWORK_DIASPORA),
3048 intval($public_batch)
3051 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3054 // queue message for redelivery
3055 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3060 return(($return_code) ? $return_code : (-1));