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',
742 intval($new_relation),
743 dbesc(datetime_convert()),
744 dbesc(datetime_convert()),
745 dbesc(datetime_convert()),
746 intval($contact_record['id'])
749 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
751 $ret = diaspora_share($u[0],$contact_record);
757 function diaspora_post_allow($importer,$contact) {
759 // perhaps we were already sharing with this person. Now they're sharing with us.
760 // That makes us friends.
761 // Normally this should have handled by getting a request - but this could get lost
762 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
763 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
764 intval(CONTACT_IS_FRIEND),
765 intval($contact['id']),
766 intval($importer['uid'])
768 $contact['rel'] = CONTACT_IS_FRIEND;
769 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
772 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
774 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
776 if($contact['rel'] == CONTACT_IS_FOLLOWER)
777 if($importer['page-flags'] == PAGE_COMMUNITY)
782 function diaspora_is_redmatrix($url) {
783 return(strstr($url, "/channel/"));
786 function diaspora_plink($addr, $guid) {
787 $r = q("SELECT `url`, `nick` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", $addr);
791 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
793 if (diaspora_is_redmatrix($r[0]["url"]))
794 return $r[0]["url"]."/?f=&mid=".$guid;
796 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
799 function diaspora_post($importer,$xml,$msg) {
802 $guid = notags(unxmlify($xml->guid));
803 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
805 if($diaspora_handle != $msg['author']) {
806 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
810 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
814 if(! diaspora_post_allow($importer,$contact)) {
815 logger('diaspora_post: Ignoring this author.');
819 $message_id = $diaspora_handle . ':' . $guid;
820 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
821 intval($importer['uid']),
826 logger('diaspora_post: message exists: ' . $guid);
830 $created = unxmlify($xml->created_at);
831 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
833 $body = diaspora2bb($xml->raw_message);
835 // Add OEmbed and other information to the body
836 if (!diaspora_is_redmatrix($contact['url']))
837 $body = add_page_info_to_body($body, false, true);
843 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
845 foreach($matches as $mtch) {
846 if(strlen($str_tags))
848 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
852 $plink = diaspora_plink($diaspora_handle, $guid);
854 $datarray['uid'] = $importer['uid'];
855 $datarray['contact-id'] = $contact['id'];
856 $datarray['wall'] = 0;
857 $datarray['network'] = NETWORK_DIASPORA;
858 $datarray['verb'] = ACTIVITY_POST;
859 $datarray['guid'] = $guid;
860 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
861 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
862 $datarray['private'] = $private;
863 $datarray['parent'] = 0;
864 $datarray['plink'] = $plink;
865 $datarray['owner-name'] = $contact['name'];
866 $datarray['owner-link'] = $contact['url'];
867 //$datarray['owner-avatar'] = $contact['thumb'];
868 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
869 $datarray['author-name'] = $contact['name'];
870 $datarray['author-link'] = $contact['url'];
871 $datarray['author-avatar'] = $contact['thumb'];
872 $datarray['body'] = $body;
873 $datarray['tag'] = $str_tags;
874 $datarray['app'] = 'Diaspora';
876 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
878 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
880 DiasporaFetchGuid($datarray);
881 $message_id = item_store($datarray);
887 function DiasporaFetchGuid($item) {
888 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
889 function ($match) use ($item){
890 return(DiasporaFetchGuidSub($match, $item));
894 function DiasporaFetchGuidSub($match, $item) {
897 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
898 diaspora_store_by_guid($match[1], $item["owner-link"]);
901 function diaspora_store_by_guid($guid, $server, $uid = 0) {
902 require_once("include/Contact.php");
904 $serverparts = parse_url($server);
905 $server = $serverparts["scheme"]."://".$serverparts["host"];
907 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
909 $item = diaspora_fetch_message($guid, $server);
914 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
916 $body = $item["body"];
917 $str_tags = $item["tag"];
919 $created = $item["created"];
920 $author = $item["author"];
921 $guid = $item["guid"];
922 $private = $item["private"];
924 $message_id = $author.':'.$guid;
925 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
933 $person = find_diaspora_person_by_handle($author);
936 $datarray['uid'] = $uid;
937 $datarray['contact-id'] = get_contact($person['url'], $uid);
938 $datarray['wall'] = 0;
939 $datarray['network'] = NETWORK_DIASPORA;
940 $datarray['guid'] = $guid;
941 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
942 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
943 $datarray['private'] = $private;
944 $datarray['parent'] = 0;
945 $datarray['plink'] = diaspora_plink($author, $guid);
946 $datarray['author-name'] = $person['name'];
947 $datarray['author-link'] = $person['url'];
948 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
949 $datarray['owner-name'] = $datarray['author-name'];
950 $datarray['owner-link'] = $datarray['author-link'];
951 $datarray['owner-avatar'] = $datarray['author-avatar'];
952 $datarray['body'] = $body;
953 $datarray['tag'] = $str_tags;
954 $datarray['app'] = $app;
955 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
957 if ($datarray['contact-id'] == 0)
960 DiasporaFetchGuid($datarray);
961 $message_id = item_store($datarray);
964 // Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
969 function diaspora_fetch_message($guid, $server, $level = 0) {
976 // This will not work if the server is not a Diaspora server
977 $source_url = $server.'/p/'.$guid.'.xml';
978 $x = fetch_url($source_url);
982 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
983 $source_xml = parse_xml_string($x,false);
986 $item["app"] = 'Diaspora';
987 $item["guid"] = $guid;
990 if ($source_xml->post->status_message->created_at)
991 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
993 if ($source_xml->post->status_message->provider_display_name)
994 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
996 if ($source_xml->post->status_message->diaspora_handle)
997 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
999 if ($source_xml->post->status_message->guid)
1000 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1002 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1004 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1005 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1006 $body = scale_external_images($body,false);
1007 } elseif($source_xml->post->asphoto->image_url) {
1008 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1009 $body = scale_external_images($body);
1010 } elseif($source_xml->post->status_message) {
1011 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1013 // Checking for embedded pictures
1014 if($source_xml->post->status_message->photo->remote_photo_path AND
1015 $source_xml->post->status_message->photo->remote_photo_name) {
1017 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1018 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1020 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1022 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1025 $body = scale_external_images($body);
1027 // Add OEmbed and other information to the body
1028 $body = add_page_info_to_body($body, false, true);
1029 } elseif($source_xml->post->reshare) {
1030 // Reshare of a reshare
1031 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1033 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1034 logger('no content found: '.print_r($source_xml,true));
1038 if (trim($body) == "")
1042 $item["body"] = $body;
1047 function diaspora_reshare($importer,$xml,$msg) {
1049 logger('diaspora_reshare: init: ' . print_r($xml,true));
1052 $guid = notags(unxmlify($xml->guid));
1053 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1056 if($diaspora_handle != $msg['author']) {
1057 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1061 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1065 if(! diaspora_post_allow($importer,$contact)) {
1066 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1070 $message_id = $diaspora_handle . ':' . $guid;
1071 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1072 intval($importer['uid']),
1077 logger('diaspora_reshare: message exists: ' . $guid);
1081 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1082 $orig_guid = notags(unxmlify($xml->root_guid));
1084 $create_original_post = false;
1086 // Do we already have this item?
1087 $r = q("SELECT `body`, `tag`, `app`, `created`, `author-link`, `plink` FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1089 dbesc(NETWORK_DIASPORA)
1092 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system: '.$orig_url);
1094 // Maybe it is already a reshared item?
1095 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1096 require_once('include/api.php');
1097 if (api_share_as_retweet($r[0]))
1100 $body = $r[0]["body"];
1101 $str_tags = $r[0]["tag"];
1102 $app = $r[0]["app"];
1103 $orig_created = $r[0]["created"];
1104 $orig_author = $r[0]["author-link"];
1105 $create_original_post = ($body != "");
1106 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1115 $orig_url = 'https://'.substr($orig_author,strpos($orig_author,'@')+1).'/posts/'.$orig_guid;
1117 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1118 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1119 $item = diaspora_fetch_message($orig_guid, $server);
1122 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1123 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1124 $item = diaspora_fetch_message($orig_guid, $server);
1127 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1128 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1129 $item = diaspora_fetch_message($orig_guid, $server);
1132 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1133 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1134 $item = diaspora_fetch_message($orig_guid, $server);
1138 $body = $item["body"];
1139 $str_tags = $item["tag"];
1140 $app = $item["app"];
1141 $orig_created = $item["created"];
1142 $orig_author = $item["author"];
1143 $orig_guid = $item["guid"];
1144 $create_original_post = ($body != "");
1145 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1149 $person = find_diaspora_person_by_handle($orig_author);
1151 $created = unxmlify($xml->created_at);
1152 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1154 $datarray = array();
1156 $plink = diaspora_plink($diaspora_handle, $guid);
1158 $datarray['uid'] = $importer['uid'];
1159 $datarray['contact-id'] = $contact['id'];
1160 $datarray['wall'] = 0;
1161 $datarray['network'] = NETWORK_DIASPORA;
1162 $datarray['guid'] = $guid;
1163 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1164 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1165 $datarray['private'] = $private;
1166 $datarray['parent'] = 0;
1167 $datarray['plink'] = $plink;
1168 $datarray['owner-name'] = $contact['name'];
1169 $datarray['owner-link'] = $contact['url'];
1170 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1171 if (!intval(get_config('system','wall-to-wall_share'))) {
1172 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1174 $datarray['author-name'] = $contact['name'];
1175 $datarray['author-link'] = $contact['url'];
1176 $datarray['author-avatar'] = $contact['thumb'];
1177 $datarray['body'] = $prefix.$body."[/share]";
1179 // Let reshared messages look like wall-to-wall posts
1180 $datarray['author-name'] = $person['name'];
1181 $datarray['author-link'] = $person['url'];
1182 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1183 $datarray['body'] = $body;
1186 $datarray['tag'] = $str_tags;
1187 $datarray['app'] = $app;
1189 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1190 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1192 // Store the original item of a reshare
1193 if ($create_original_post) {
1194 require_once("include/Contact.php");
1196 $datarray2 = $datarray;
1198 $datarray2['uid'] = 0;
1199 $datarray2['contact-id'] = get_contact($person['url'], 0);
1200 $datarray2['guid'] = $orig_guid;
1201 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_author.':'.$orig_guid;
1202 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1203 $datarray2['plink'] = diaspora_plink($orig_author, $orig_guid);
1205 $datarray2['author-name'] = $person['name'];
1206 $datarray2['author-link'] = $person['url'];
1207 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1208 $datarray2['owner-name'] = $datarray2['author-name'];
1209 $datarray2['owner-link'] = $datarray2['author-link'];
1210 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1211 $datarray2['body'] = $body;
1213 DiasporaFetchGuid($datarray2);
1214 $message_id = item_store($datarray2);
1216 logger("Store original item ".$orig_guid." under message id ".$message_id);
1219 DiasporaFetchGuid($datarray);
1220 $message_id = item_store($datarray);
1227 function diaspora_asphoto($importer,$xml,$msg) {
1228 logger('diaspora_asphoto called');
1231 $guid = notags(unxmlify($xml->guid));
1232 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1234 if($diaspora_handle != $msg['author']) {
1235 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1239 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1243 if(! diaspora_post_allow($importer,$contact)) {
1244 logger('diaspora_asphoto: Ignoring this author.');
1248 $message_id = $diaspora_handle . ':' . $guid;
1249 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1250 intval($importer['uid']),
1255 logger('diaspora_asphoto: message exists: ' . $guid);
1259 $created = unxmlify($xml->created_at);
1260 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1262 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1263 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1264 $body = scale_external_images($body,false);
1266 elseif($xml->image_url) {
1267 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1268 $body = scale_external_images($body);
1271 logger('diaspora_asphoto: no photo url found.');
1275 $plink = diaspora_plink($diaspora_handle, $guid);
1277 $datarray = array();
1279 $datarray['uid'] = $importer['uid'];
1280 $datarray['contact-id'] = $contact['id'];
1281 $datarray['wall'] = 0;
1282 $datarray['network'] = NETWORK_DIASPORA;
1283 $datarray['guid'] = $guid;
1284 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1285 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1286 $datarray['private'] = $private;
1287 $datarray['parent'] = 0;
1288 $datarray['plink'] = $plink;
1289 $datarray['owner-name'] = $contact['name'];
1290 $datarray['owner-link'] = $contact['url'];
1291 //$datarray['owner-avatar'] = $contact['thumb'];
1292 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1293 $datarray['author-name'] = $contact['name'];
1294 $datarray['author-link'] = $contact['url'];
1295 $datarray['author-avatar'] = $contact['thumb'];
1296 $datarray['body'] = $body;
1298 $datarray['app'] = 'Diaspora/Cubbi.es';
1300 DiasporaFetchGuid($datarray);
1301 $message_id = item_store($datarray);
1304 // q("update item set plink = '%s' where id = %d",
1305 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1306 // intval($message_id)
1319 function diaspora_comment($importer,$xml,$msg) {
1322 $guid = notags(unxmlify($xml->guid));
1323 $parent_guid = notags(unxmlify($xml->parent_guid));
1324 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1325 $target_type = notags(unxmlify($xml->target_type));
1326 $text = unxmlify($xml->text);
1327 $author_signature = notags(unxmlify($xml->author_signature));
1329 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1331 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1333 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1337 if(! diaspora_post_allow($importer,$contact)) {
1338 logger('diaspora_comment: Ignoring this author.');
1342 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1343 intval($importer['uid']),
1347 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1351 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1352 intval($importer['uid']),
1357 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1360 $person = find_diaspora_person_by_handle($diaspora_handle);
1361 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1365 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1367 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1368 intval($importer['uid']),
1375 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1378 $parent_item = $r[0];
1381 /* How Diaspora performs comment signature checking:
1383 - If an item has been sent by the comment author to the top-level post owner to relay on
1384 to the rest of the contacts on the top-level post, the top-level post owner should check
1385 the author_signature, then create a parent_author_signature before relaying the comment on
1386 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1387 check only the parent_author_signature. Basically, they trust that the top-level post
1388 owner has already verified the authenticity of anything he/she sends out
1389 - In either case, the signature that get checked is the signature created by the person
1393 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1396 if($parent_author_signature) {
1397 // If a parent_author_signature exists, then we've received the comment
1398 // relayed from the top-level post owner. There's no need to check the
1399 // author_signature if the parent_author_signature is valid
1401 $parent_author_signature = base64_decode($parent_author_signature);
1403 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1404 logger('diaspora_comment: top-level owner verification failed.');
1409 // If there's no parent_author_signature, then we've received the comment
1410 // from the comment creator. In that case, the person is commenting on
1411 // our post, so he/she must be a contact of ours and his/her public key
1412 // should be in $msg['key']
1414 $author_signature = base64_decode($author_signature);
1416 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1417 logger('diaspora_comment: comment author verification failed.');
1422 // Phew! Everything checks out. Now create an item.
1424 // Find the original comment author information.
1425 // We need this to make sure we display the comment author
1426 // information (name and avatar) correctly.
1427 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1430 $person = find_diaspora_person_by_handle($diaspora_handle);
1432 if(! is_array($person)) {
1433 logger('diaspora_comment: unable to find author details');
1438 $body = diaspora2bb($text);
1439 $message_id = $diaspora_handle . ':' . $guid;
1441 $datarray = array();
1443 $datarray['uid'] = $importer['uid'];
1444 $datarray['contact-id'] = $contact['id'];
1445 $datarray['type'] = 'remote-comment';
1446 $datarray['wall'] = $parent_item['wall'];
1447 $datarray['network'] = NETWORK_DIASPORA;
1448 $datarray['verb'] = ACTIVITY_POST;
1449 $datarray['gravity'] = GRAVITY_COMMENT;
1450 $datarray['guid'] = $guid;
1451 $datarray['uri'] = $message_id;
1452 $datarray['parent-uri'] = $parent_item['uri'];
1454 // No timestamps for comments? OK, we'll the use current time.
1455 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1456 $datarray['private'] = $parent_item['private'];
1458 $datarray['owner-name'] = $parent_item['owner-name'];
1459 $datarray['owner-link'] = $parent_item['owner-link'];
1460 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1462 $datarray['author-name'] = $person['name'];
1463 $datarray['author-link'] = $person['url'];
1464 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1465 $datarray['body'] = $body;
1467 // We can't be certain what the original app is if the message is relayed.
1468 if(($parent_item['origin']) && (! $parent_author_signature))
1469 $datarray['app'] = 'Diaspora';
1471 DiasporaFetchGuid($datarray);
1472 $message_id = item_store($datarray);
1474 $datarray['id'] = $message_id;
1477 //q("update item set plink = '%s' where id = %d",
1478 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1479 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1480 // intval($message_id)
1484 if(($parent_item['origin']) && (! $parent_author_signature)) {
1485 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1486 intval($message_id),
1487 dbesc($signed_data),
1488 dbesc(base64_encode($author_signature)),
1489 dbesc($diaspora_handle)
1492 // if the message isn't already being relayed, notify others
1493 // the existence of parent_author_signature means the parent_author or owner
1494 // is already relaying.
1496 proc_run('php','include/notifier.php','comment-import',$message_id);
1499 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1500 dbesc($parent_item['uri']),
1501 intval($importer['uid'])
1504 if(count($myconv)) {
1505 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1507 foreach($myconv as $conv) {
1509 // now if we find a match, it means we're in this conversation
1511 if(! link_compare($conv['author-link'],$importer_url))
1514 require_once('include/enotify.php');
1516 $conv_parent = $conv['parent'];
1519 'type' => NOTIFY_COMMENT,
1520 'notify_flags' => $importer['notify-flags'],
1521 'language' => $importer['language'],
1522 'to_name' => $importer['username'],
1523 'to_email' => $importer['email'],
1524 'uid' => $importer['uid'],
1525 'item' => $datarray,
1526 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1527 'source_name' => $datarray['author-name'],
1528 'source_link' => $datarray['author-link'],
1529 'source_photo' => $datarray['author-avatar'],
1530 'verb' => ACTIVITY_POST,
1532 'parent' => $conv_parent,
1533 'parent_uri' => $parent_uri
1536 // only send one notification
1546 function diaspora_conversation($importer,$xml,$msg) {
1550 $guid = notags(unxmlify($xml->guid));
1551 $subject = notags(unxmlify($xml->subject));
1552 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1553 $participant_handles = notags(unxmlify($xml->participant_handles));
1554 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1556 $parent_uri = $diaspora_handle . ':' . $guid;
1558 $messages = $xml->message;
1560 if(! count($messages)) {
1561 logger('diaspora_conversation: empty conversation');
1565 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1567 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1571 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1572 logger('diaspora_conversation: Ignoring this author.');
1576 $conversation = null;
1578 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1579 intval($importer['uid']),
1583 $conversation = $c[0];
1585 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1586 intval($importer['uid']),
1588 dbesc($diaspora_handle),
1589 dbesc(datetime_convert('UTC','UTC',$created_at)),
1590 dbesc(datetime_convert()),
1592 dbesc($participant_handles)
1595 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1596 intval($importer['uid']),
1600 $conversation = $c[0];
1602 if(! $conversation) {
1603 logger('diaspora_conversation: unable to create conversation.');
1607 foreach($messages as $mesg) {
1611 $msg_guid = notags(unxmlify($mesg->guid));
1612 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1613 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1614 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1615 $msg_text = unxmlify($mesg->text);
1616 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1617 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1618 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1619 if($msg_conversation_guid != $guid) {
1620 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1624 $body = diaspora2bb($msg_text);
1625 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1627 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1629 $author_signature = base64_decode($msg_author_signature);
1631 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1636 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1638 if(is_array($person) && x($person,'pubkey'))
1639 $key = $person['pubkey'];
1641 logger('diaspora_conversation: unable to find author details');
1646 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1647 logger('diaspora_conversation: verification failed.');
1651 if($msg_parent_author_signature) {
1652 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1654 $parent_author_signature = base64_decode($msg_parent_author_signature);
1658 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1659 logger('diaspora_conversation: owner verification failed.');
1664 $r = q("select id from mail where `uri` = '%s' limit 1",
1668 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1672 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')",
1673 intval($importer['uid']),
1675 intval($conversation['id']),
1676 dbesc($person['name']),
1677 dbesc($person['photo']),
1678 dbesc($person['url']),
1679 intval($contact['id']),
1686 dbesc($msg_created_at)
1689 q("update conv set updated = '%s' where id = %d",
1690 dbesc(datetime_convert()),
1691 intval($conversation['id'])
1694 require_once('include/enotify.php');
1696 'type' => NOTIFY_MAIL,
1697 'notify_flags' => $importer['notify-flags'],
1698 'language' => $importer['language'],
1699 'to_name' => $importer['username'],
1700 'to_email' => $importer['email'],
1701 'uid' =>$importer['uid'],
1702 'item' => array('subject' => $subject, 'body' => $body),
1703 'source_name' => $person['name'],
1704 'source_link' => $person['url'],
1705 'source_photo' => $person['thumb'],
1706 'verb' => ACTIVITY_POST,
1714 function diaspora_message($importer,$xml,$msg) {
1718 $msg_guid = notags(unxmlify($xml->guid));
1719 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1720 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1721 $msg_author_signature = notags(unxmlify($xml->author_signature));
1722 $msg_text = unxmlify($xml->text);
1723 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1724 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1725 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1727 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1729 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1731 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1735 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1736 logger('diaspora_message: Ignoring this author.');
1740 $conversation = null;
1742 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1743 intval($importer['uid']),
1744 dbesc($msg_conversation_guid)
1747 $conversation = $c[0];
1749 logger('diaspora_message: conversation not available.');
1755 $body = diaspora2bb($msg_text);
1756 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1758 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1761 $author_signature = base64_decode($msg_author_signature);
1763 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1764 if(is_array($person) && x($person,'pubkey'))
1765 $key = $person['pubkey'];
1767 logger('diaspora_message: unable to find author details');
1771 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1772 logger('diaspora_message: verification failed.');
1776 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1778 intval($importer['uid'])
1781 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1785 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')",
1786 intval($importer['uid']),
1788 intval($conversation['id']),
1789 dbesc($person['name']),
1790 dbesc($person['photo']),
1791 dbesc($person['url']),
1792 intval($contact['id']),
1793 dbesc($conversation['subject']),
1799 dbesc($msg_created_at)
1802 q("update conv set updated = '%s' where id = %d",
1803 dbesc(datetime_convert()),
1804 intval($conversation['id'])
1811 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1815 logger('diaspora_photo: init',LOGGER_DEBUG);
1817 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1819 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1821 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1823 $guid = notags(unxmlify($xml->guid));
1825 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1827 $public = notags(unxmlify($xml->public));
1829 $created_at = notags(unxmlify($xml_created_at));
1831 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1833 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1835 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1839 if(! diaspora_post_allow($importer,$contact)) {
1840 logger('diaspora_photo: Ignoring this author.');
1844 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1845 intval($importer['uid']),
1846 dbesc($status_message_guid)
1849 /* deactivated by now since it can lead to multiplicated pictures in posts.
1851 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1854 $person = find_diaspora_person_by_handle($diaspora_handle);
1855 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1859 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1861 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1862 intval($importer['uid']),
1863 dbesc($status_message_guid)
1870 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1871 intval($importer['uid']),
1872 dbesc(serialize($msg)),
1873 intval($attempt + 1)
1877 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1881 $parent_item = $r[0];
1883 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1885 $link_text = scale_external_images($link_text, true,
1886 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1888 if(strpos($parent_item['body'],$link_text) === false) {
1889 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1890 dbesc($link_text . $parent_item['body']),
1891 intval($parent_item['id']),
1892 intval($parent_item['uid'])
1894 update_thread($parent_item['id']);
1903 function diaspora_like($importer,$xml,$msg) {
1906 $guid = notags(unxmlify($xml->guid));
1907 $parent_guid = notags(unxmlify($xml->parent_guid));
1908 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1909 $target_type = notags(unxmlify($xml->target_type));
1910 $positive = notags(unxmlify($xml->positive));
1911 $author_signature = notags(unxmlify($xml->author_signature));
1913 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1915 // likes on comments not supported here and likes on photos not supported by Diaspora
1917 // if($target_type !== 'Post')
1920 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1922 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1926 if(! diaspora_post_allow($importer,$contact)) {
1927 logger('diaspora_like: Ignoring this author.');
1931 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1932 intval($importer['uid']),
1937 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1940 $person = find_diaspora_person_by_handle($diaspora_handle);
1941 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1945 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1947 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1948 intval($importer['uid']),
1955 logger('diaspora_like: parent item not found: ' . $guid);
1959 $parent_item = $r[0];
1961 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1962 intval($importer['uid']),
1966 if($positive === 'true') {
1967 logger('diaspora_like: duplicate like: ' . $guid);
1970 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1971 // It looks like "RelayableRetractions" are used for "unlike" instead
1972 if($positive === 'false') {
1973 logger('diaspora_like: received a like with positive set to "false"...ignoring');
1974 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
1975 intval($r[0]['id']),
1976 intval($importer['uid'])
1978 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1979 // send notification via proc_run()
1983 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1984 // It looks like "RelayableRetractions" are used for "unlike" instead
1985 if($positive === 'false') {
1986 logger('diaspora_like: received a like with positive set to "false"');
1987 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1992 /* How Diaspora performs "like" signature checking:
1994 - If an item has been sent by the like author to the top-level post owner to relay on
1995 to the rest of the contacts on the top-level post, the top-level post owner should check
1996 the author_signature, then create a parent_author_signature before relaying the like on
1997 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1998 check only the parent_author_signature. Basically, they trust that the top-level post
1999 owner has already verified the authenticity of anything he/she sends out
2000 - In either case, the signature that get checked is the signature created by the person
2004 // Diaspora has changed the way they are signing the likes.
2005 // Just to make sure that we don't miss any likes we will check the old and the current way.
2006 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2008 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2012 if ($parent_author_signature) {
2013 // If a parent_author_signature exists, then we've received the like
2014 // relayed from the top-level post owner. There's no need to check the
2015 // author_signature if the parent_author_signature is valid
2017 $parent_author_signature = base64_decode($parent_author_signature);
2019 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2020 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2022 logger('diaspora_like: top-level owner verification failed.');
2026 // If there's no parent_author_signature, then we've received the like
2027 // from the like creator. In that case, the person is "like"ing
2028 // our post, so he/she must be a contact of ours and his/her public key
2029 // should be in $msg['key']
2031 $author_signature = base64_decode($author_signature);
2033 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2034 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2036 logger('diaspora_like: like creator verification failed.');
2041 // Phew! Everything checks out. Now create an item.
2043 // Find the original comment author information.
2044 // We need this to make sure we display the comment author
2045 // information (name and avatar) correctly.
2046 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2049 $person = find_diaspora_person_by_handle($diaspora_handle);
2051 if(! is_array($person)) {
2052 logger('diaspora_like: unable to find author details');
2057 $uri = $diaspora_handle . ':' . $guid;
2059 $activity = ACTIVITY_LIKE;
2060 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2061 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2062 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2063 $body = $parent_item['body'];
2068 <type>$objtype</type>
2070 <id>{$parent_item['uri']}</id>
2073 <content>$body</content>
2076 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2081 $arr['uid'] = $importer['uid'];
2082 $arr['guid'] = $guid;
2083 $arr['network'] = NETWORK_DIASPORA;
2084 $arr['contact-id'] = $contact['id'];
2085 $arr['type'] = 'activity';
2086 $arr['wall'] = $parent_item['wall'];
2087 $arr['gravity'] = GRAVITY_LIKE;
2088 $arr['parent'] = $parent_item['id'];
2089 $arr['parent-uri'] = $parent_item['uri'];
2091 $arr['owner-name'] = $parent_item['name'];
2092 $arr['owner-link'] = $parent_item['url'];
2093 //$arr['owner-avatar'] = $parent_item['thumb'];
2094 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2096 $arr['author-name'] = $person['name'];
2097 $arr['author-link'] = $person['url'];
2098 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2100 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2101 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2102 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2103 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2104 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2106 $arr['app'] = 'Diaspora';
2108 $arr['private'] = $parent_item['private'];
2109 $arr['verb'] = $activity;
2110 $arr['object-type'] = $objtype;
2111 $arr['object'] = $obj;
2112 $arr['visible'] = 1;
2114 $arr['last-child'] = 0;
2116 $message_id = item_store($arr);
2120 // q("update item set plink = '%s' where id = %d",
2121 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2122 // dbesc($a->get_baseurl().'/display/'.$guid),
2123 // intval($message_id)
2127 if(! $parent_author_signature) {
2128 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2129 intval($message_id),
2130 dbesc($signed_data),
2131 dbesc(base64_encode($author_signature)),
2132 dbesc($diaspora_handle)
2136 // if the message isn't already being relayed, notify others
2137 // the existence of parent_author_signature means the parent_author or owner
2138 // is already relaying. The parent_item['origin'] indicates the message was created on our system
2140 if(($parent_item['origin']) && (! $parent_author_signature))
2141 proc_run('php','include/notifier.php','comment-import',$message_id);
2146 function diaspora_retraction($importer,$xml) {
2149 $guid = notags(unxmlify($xml->guid));
2150 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2151 $type = notags(unxmlify($xml->type));
2153 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2157 if($type === 'Person') {
2158 require_once('include/Contact.php');
2159 contact_remove($contact['id']);
2161 elseif($type === 'Post') {
2162 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2164 intval($importer['uid'])
2167 if(link_compare($r[0]['author-link'],$contact['url'])) {
2168 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2169 dbesc(datetime_convert()),
2172 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2181 function diaspora_signed_retraction($importer,$xml,$msg) {
2184 $guid = notags(unxmlify($xml->target_guid));
2185 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2186 $type = notags(unxmlify($xml->target_type));
2187 $sig = notags(unxmlify($xml->target_author_signature));
2189 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2191 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2193 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2198 $signed_data = $guid . ';' . $type ;
2201 /* How Diaspora performs relayable_retraction signature checking:
2203 - If an item has been sent by the item author to the top-level post owner to relay on
2204 to the rest of the contacts on the top-level post, the top-level post owner checks
2205 the author_signature, then creates a parent_author_signature before relaying the item on
2206 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2207 check only the parent_author_signature. Basically, they trust that the top-level post
2208 owner has already verified the authenticity of anything he/she sends out
2209 - In either case, the signature that get checked is the signature created by the person
2213 if($parent_author_signature) {
2215 $parent_author_signature = base64_decode($parent_author_signature);
2217 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2218 logger('diaspora_signed_retraction: top-level post owner verification failed');
2225 $sig_decode = base64_decode($sig);
2227 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2228 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2233 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2234 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2236 intval($importer['uid'])
2239 if(link_compare($r[0]['author-link'],$contact['url'])) {
2240 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2241 dbesc(datetime_convert()),
2242 dbesc(datetime_convert()),
2245 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2247 // Now check if the retraction needs to be relayed by us
2249 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2250 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2251 // The only item with `parent` and `id` as the parent id is the parent item.
2252 $p = q("select origin from item where parent = %d and id = %d limit 1",
2257 if(($p[0]['origin']) && (! $parent_author_signature)) {
2258 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2260 dbesc($signed_data),
2262 dbesc($diaspora_handle)
2265 // the existence of parent_author_signature would have meant the parent_author or owner
2266 // is already relaying.
2267 logger('diaspora_signed_retraction: relaying relayable_retraction');
2269 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2276 logger('diaspora_signed_retraction: unknown type: ' . $type);
2282 function diaspora_profile($importer,$xml,$msg) {
2285 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2288 if($diaspora_handle != $msg['author']) {
2289 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2293 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2297 if($contact['blocked']) {
2298 logger('diaspora_post: Ignoring this author.');
2302 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2303 $image_url = unxmlify($xml->image_url);
2304 $birthday = unxmlify($xml->birthday);
2305 $location = diaspora2bb(unxmlify($xml->location));
2306 $about = diaspora2bb(unxmlify($xml->bio));
2307 $gender = unxmlify($xml->gender);
2308 $tags = unxmlify($xml->tag_string);
2310 $tags = explode("#", $tags);
2312 $keywords = array();
2313 foreach ($tags as $tag) {
2314 $tag = trim(strtolower($tag));
2319 $keywords = implode(", ", $keywords);
2321 $handle_parts = explode("@", $diaspora_handle);
2323 $name = $handle_parts[0];
2326 if( preg_match("|^https?://|", $image_url) === 0) {
2327 $image_url = "http://" . $handle_parts[1] . $image_url;
2330 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2331 intval($importer['uid']),
2332 intval($contact['id'])
2334 $oldphotos = ((count($r)) ? $r : null);*/
2336 require_once('include/Photo.php');
2338 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2340 // Generic birthday. We don't know the timezone. The year is irrelevant.
2342 $birthday = str_replace('1000','1901',$birthday);
2344 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2346 // this is to prevent multiple birthday notifications in a single year
2347 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2349 if(substr($birthday,5) === substr($contact['bd'],5))
2350 $birthday = $contact['bd'];
2352 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2353 // Not doing this currently because D* protocol is scheduled for revision soon.
2355 $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",
2357 dbesc(datetime_convert()),
2361 dbesc(datetime_convert()),
2367 intval($contact['id']),
2368 intval($importer['uid'])
2371 if (unxmlify($xml->searchable) == "true") {
2372 require_once('include/socgraph.php');
2373 poco_check($contact['url'], $name, NETWORK_DIASPORA, $images[0], $about, $location, $gender, $keywords, "",
2374 datetime_convert(), 2, $contact['id'], $importer['uid']);
2378 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
2379 dbesc(normalise_link($contact['url'])));
2381 if (count($author) == 0) {
2382 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`, `location`, `about`) VALUES ('%s', '%s', '%s', '%s', '%s')",
2383 dbesc(normalise_link($contact['url'])), dbesc($name), dbesc($location), dbesc($about), dbesc($images[0]));
2385 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
2386 dbesc(normalise_link($contact['url'])));
2387 } else if (normalise_link($contact['url']).$name.$location.$about != normalise_link($author[0]["url"]).$author[0]["name"].$author[0]["location"].$author[0]["about"]) {
2388 q("UPDATE unique_contacts SET name = '%s', avatar = '%s', `location` = '%s', `about` = '%s' WHERE url = '%s'",
2389 dbesc($name), dbesc($images[0]), dbesc($location), dbesc($about), dbesc(normalise_link($contact['url'])));
2394 foreach($oldphotos as $ph) {
2395 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2396 intval($importer['uid']),
2397 intval($contact['id']),
2398 dbesc($ph['resource-id'])
2408 function diaspora_share($me,$contact) {
2410 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2411 $theiraddr = $contact['addr'];
2413 $tpl = get_markup_template('diaspora_share.tpl');
2414 $msg = replace_macros($tpl, array(
2415 '$sender' => $myaddr,
2416 '$recipient' => $theiraddr
2419 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2420 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2422 return(diaspora_transmit($owner,$contact,$slap, false));
2425 function diaspora_unshare($me,$contact) {
2428 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2430 $tpl = get_markup_template('diaspora_retract.tpl');
2431 $msg = replace_macros($tpl, array(
2432 '$guid' => $me['guid'],
2433 '$type' => 'Person',
2434 '$handle' => $myaddr
2437 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2438 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2440 return(diaspora_transmit($owner,$contact,$slap, false));
2445 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2448 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2449 $theiraddr = $contact['addr'];
2453 $title = $item['title'];
2454 $body = $item['body'];
2457 // We're trying to match Diaspora's split message/photo protocol but
2458 // all the photos are displayed on D* as links and not img's - even
2459 // though we're sending pretty much precisely what they send us when
2460 // doing the same operation.
2461 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2462 // which seems to get through intact.
2464 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2466 foreach($matches as $mtch) {
2468 $detail['str'] = $mtch[0];
2469 $detail['path'] = dirname($mtch[1]) . '/';
2470 $detail['file'] = basename($mtch[1]);
2471 $detail['guid'] = $item['guid'];
2472 $detail['handle'] = $myaddr;
2473 $images[] = $detail;
2474 $body = str_replace($detail['str'],$mtch[1],$body);
2479 //if(strlen($title))
2480 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2482 // convert to markdown
2483 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2484 //$body = bb2diaspora($body);
2488 $body = "## ".html_entity_decode($title)."\n\n".$body;
2490 if($item['attach']) {
2491 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2493 $body .= "\n" . t('Attachments:') . "\n";
2494 foreach($matches as $mtch) {
2495 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2501 $public = (($item['private']) ? 'false' : 'true');
2503 require_once('include/datetime.php');
2504 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2506 // Detect a share element and do a reshare
2507 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2508 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2509 $tpl = get_markup_template('diaspora_reshare.tpl');
2510 $msg = replace_macros($tpl, array(
2511 '$root_handle' => xmlify($ret['root_handle']),
2512 '$root_guid' => $ret['root_guid'],
2513 '$guid' => $item['guid'],
2514 '$handle' => xmlify($myaddr),
2515 '$public' => $public,
2516 '$created' => $created,
2517 '$provider' => $item["app"]
2520 $tpl = get_markup_template('diaspora_post.tpl');
2521 $msg = replace_macros($tpl, array(
2523 '$guid' => $item['guid'],
2524 '$handle' => xmlify($myaddr),
2525 '$public' => $public,
2526 '$created' => $created,
2527 '$provider' => $item["app"]
2531 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2533 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2534 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2536 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2538 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2540 if(count($images)) {
2541 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2544 return $return_code;
2547 function diaspora_is_reshare($body) {
2548 $body = trim($body);
2550 // Skip if it isn't a pure repeated messages
2551 // Does it start with a share?
2552 if (strpos($body, "[share") > 0)
2555 // Does it end with a share?
2556 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2559 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2560 // Skip if there is no shared message in there
2561 if ($body == $attributes)
2565 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2566 if ($matches[1] != "")
2567 $guid = $matches[1];
2569 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2570 if ($matches[1] != "")
2571 $guid = $matches[1];
2574 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2575 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2578 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2579 $ret["root_guid"] = $guid;
2585 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2586 if ($matches[1] != "")
2587 $profile = $matches[1];
2589 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2590 if ($matches[1] != "")
2591 $profile = $matches[1];
2595 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2596 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2600 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2601 if ($matches[1] != "")
2602 $link = $matches[1];
2604 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2605 if ($matches[1] != "")
2606 $link = $matches[1];
2608 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2609 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2615 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2617 if(! count($images))
2619 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2621 $tpl = get_markup_template('diaspora_photo.tpl');
2622 foreach($images as $image) {
2623 if(! stristr($image['path'],$mysite))
2625 $resource = str_replace('.jpg','',$image['file']);
2626 $resource = substr($resource,0,strpos($resource,'-'));
2628 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2630 intval($owner['uid'])
2634 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2635 $msg = replace_macros($tpl,array(
2636 '$path' => xmlify($image['path']),
2637 '$filename' => xmlify($image['file']),
2638 '$msg_guid' => xmlify($image['guid']),
2639 '$guid' => xmlify($r[0]['guid']),
2640 '$handle' => xmlify($image['handle']),
2641 '$public' => xmlify($public),
2642 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2646 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2647 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2648 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2650 diaspora_transmit($owner,$contact,$slap,$public_batch);
2655 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2658 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2659 // $theiraddr = $contact['addr'];
2661 // Diaspora doesn't support threaded comments, but some
2662 // versions of Diaspora (i.e. Diaspora-pistos) support
2663 // likes on comments
2664 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2665 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2666 dbesc($item['thr-parent'])
2670 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2671 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2672 // The only item with `parent` and `id` as the parent id is the parent item.
2673 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2674 intval($item['parent']),
2675 intval($item['parent'])
2683 if($item['verb'] === ACTIVITY_LIKE) {
2684 $tpl = get_markup_template('diaspora_like.tpl');
2686 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2687 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2688 // $positive = (($item['deleted']) ? 'false' : 'true');
2691 if(($item['deleted']))
2692 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2695 $tpl = get_markup_template('diaspora_comment.tpl');
2699 $text = html_entity_decode(bb2diaspora($item['body']));
2704 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2706 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2708 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2710 $msg = replace_macros($tpl,array(
2711 '$guid' => xmlify($item['guid']),
2712 '$parent_guid' => xmlify($parent['guid']),
2713 '$target_type' =>xmlify($target_type),
2714 '$authorsig' => xmlify($authorsig),
2715 '$body' => xmlify($text),
2716 '$positive' => xmlify($positive),
2717 '$handle' => xmlify($myaddr)
2720 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2722 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2723 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2725 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2729 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2733 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2734 // $theiraddr = $contact['addr'];
2736 $body = $item['body'];
2737 $text = html_entity_decode(bb2diaspora($body));
2739 // Diaspora doesn't support threaded comments, but some
2740 // versions of Diaspora (i.e. Diaspora-pistos) support
2741 // likes on comments
2742 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2743 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2744 dbesc($item['thr-parent'])
2748 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2749 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2750 // The only item with `parent` and `id` as the parent id is the parent item.
2751 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2752 intval($item['parent']),
2753 intval($item['parent'])
2762 $relay_retract = false;
2763 $sql_sign_id = 'iid';
2764 if( $item['deleted']) {
2765 $relay_retract = true;
2767 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2769 $sql_sign_id = 'retract_iid';
2770 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2772 elseif($item['verb'] === ACTIVITY_LIKE) {
2775 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2776 // $positive = (($item['deleted']) ? 'false' : 'true');
2779 $tpl = get_markup_template('diaspora_like_relay.tpl');
2781 else { // item is a comment
2782 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2786 // fetch the original signature if the relayable was created by a Diaspora
2787 // or DFRN user. Relayables for other networks are not supported.
2789 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2794 $signed_text = $orig_sign['signed_text'];
2795 $authorsig = $orig_sign['signature'];
2796 $handle = $orig_sign['signer'];
2800 // Author signature information (for likes, comments, and retractions of likes or comments,
2801 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2802 // function is called
2803 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2807 /* Since the author signature is only checked by the parent, not by the relay recipients,
2808 * I think it may not be necessary for us to do so much work to preserve all the original
2809 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2810 * Let's just generate that and forget about all the original author signature stuff.
2812 * Note: this might be more of an problem if we want to support likes on comments for older
2813 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2814 * doing that, let's ignore it for now.
2816 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2820 $handle = diaspora_handle_from_contact($item['contact-id']);
2826 $sender_signed_text = $item['guid'] . ';' . $target_type;
2828 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2830 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2832 // Sign the relayable with the top-level owner's signature
2834 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2835 // stored in the database, because that provides the best chance that Diaspora will
2836 // be able to reconstruct the signed text the same way we did. This is particularly a
2837 // concern for the comment, whose signed text includes the text of the comment. The
2838 // smallest change in the text of the comment, including removing whitespace, will
2839 // make the signature verification fail. Since we translate from BB code to Diaspora's
2840 // markup at the top of this function, which is AFTER we placed the original $signed_text
2841 // in the database, it's hazardous to trust the original $signed_text.
2843 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2845 $msg = replace_macros($tpl,array(
2846 '$guid' => xmlify($item['guid']),
2847 '$parent_guid' => xmlify($parent['guid']),
2848 '$target_type' =>xmlify($target_type),
2849 '$authorsig' => xmlify($authorsig),
2850 '$parentsig' => xmlify($parentauthorsig),
2851 '$body' => xmlify($text),
2852 '$positive' => xmlify($positive),
2853 '$handle' => xmlify($handle)
2856 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2859 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2860 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2862 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2868 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2871 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2873 // Check whether the retraction is for a top-level post or whether it's a relayable
2874 if( $item['uri'] !== $item['parent-uri'] ) {
2876 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2877 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2881 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2882 $target_type = 'StatusMessage';
2885 $signed_text = $item['guid'] . ';' . $target_type;
2887 $msg = replace_macros($tpl, array(
2888 '$guid' => xmlify($item['guid']),
2889 '$type' => xmlify($target_type),
2890 '$handle' => xmlify($myaddr),
2891 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2894 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2895 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2897 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2900 function diaspora_send_mail($item,$owner,$contact) {
2903 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2905 $r = q("select * from conv where id = %d and uid = %d limit 1",
2906 intval($item['convid']),
2907 intval($item['uid'])
2911 logger('diaspora_send_mail: conversation not found.');
2917 'guid' => xmlify($cnv['guid']),
2918 'subject' => xmlify($cnv['subject']),
2919 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2920 'diaspora_handle' => xmlify($cnv['creator']),
2921 'participant_handles' => xmlify($cnv['recips'])
2924 $body = bb2diaspora($item['body']);
2925 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2927 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2928 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2930 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2933 'guid' => xmlify($item['guid']),
2934 'parent_guid' => xmlify($cnv['guid']),
2935 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2936 'author_signature' => xmlify($sig),
2937 'text' => xmlify($body),
2938 'created_at' => xmlify($created),
2939 'diaspora_handle' => xmlify($myaddr),
2940 'conversation_guid' => xmlify($cnv['guid'])
2943 if($item['reply']) {
2944 $tpl = get_markup_template('diaspora_message.tpl');
2945 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2948 $conv['messages'] = array($msg);
2949 $tpl = get_markup_template('diaspora_conversation.tpl');
2950 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2953 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2955 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2956 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2958 return(diaspora_transmit($owner,$contact,$slap,false));
2963 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2965 $enabled = intval(get_config('system','diaspora_enabled'));
2971 $logid = random_string(4);
2972 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2974 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2978 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2980 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2984 if (!intval(get_config('system','diaspora_test'))) {
2985 post_url($dest_url . '/', $slap);
2986 $return_code = $a->get_curl_code();
2988 logger('diaspora_transmit: test_mode');
2993 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2995 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2996 logger('diaspora_transmit: queue message');
2998 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2999 intval($contact['id']),
3000 dbesc(NETWORK_DIASPORA),
3002 intval($public_batch)
3005 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3008 // queue message for redelivery
3009 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3014 return(($return_code) ? $return_code : (-1));