4 * @file include/diaspora.php
6 * @todo GET /people/9aed8882b9f64896/stream
9 require_once('include/crypto.php');
10 require_once('include/items.php');
11 require_once('include/bb2diaspora.php');
12 require_once('include/contact_selectors.php');
13 require_once('include/queue_fn.php');
14 require_once('include/lock.php');
15 require_once('include/threads.php');
16 require_once('mod/share.php');
18 function diaspora_dispatch_public($msg) {
20 $enabled = intval(get_config('system','diaspora_enabled'));
22 logger('mod-diaspora: disabled');
26 // Use a dummy importer to import the data for the public copy
27 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
28 $result = diaspora_dispatch($importer,$msg);
29 logger("Dispatcher reported ".$result, LOGGER_DEBUG);
31 // Now distribute it to the followers
32 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
33 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
34 AND `account_expired` = 0 AND `account_removed` = 0 ",
35 dbesc(NETWORK_DIASPORA),
40 logger('diaspora_public: delivering to: ' . $rr['username']);
41 diaspora_dispatch($rr,$msg);
45 logger('diaspora_public: no subscribers for '.$msg["author"].' '.print_r($msg, true));
50 function diaspora_dispatch($importer,$msg,$attempt=1) {
54 $enabled = intval(get_config('system','diaspora_enabled'));
56 logger('mod-diaspora: disabled');
60 // php doesn't like dashes in variable names
62 $msg['message'] = str_replace(
63 array('<activity_streams-photo>','</activity_streams-photo>'),
64 array('<asphoto>','</asphoto>'),
68 $parsed_xml = parse_xml_string($msg['message'],false);
70 $xmlbase = $parsed_xml->post;
72 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
75 if($xmlbase->request) {
76 $ret = diaspora_request($importer,$xmlbase->request);
78 elseif($xmlbase->status_message) {
79 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
81 elseif($xmlbase->profile) {
82 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
84 elseif($xmlbase->comment) {
85 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
87 elseif($xmlbase->like) {
88 $ret = diaspora_like($importer,$xmlbase->like,$msg);
90 elseif($xmlbase->asphoto) {
91 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
93 elseif($xmlbase->reshare) {
94 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
96 elseif($xmlbase->retraction) {
97 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
99 elseif($xmlbase->signed_retraction) {
100 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
102 elseif($xmlbase->relayable_retraction) {
103 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
105 elseif($xmlbase->photo) {
106 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
108 elseif($xmlbase->conversation) {
109 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
111 elseif($xmlbase->message) {
112 $ret = diaspora_message($importer,$xmlbase->message,$msg);
114 elseif($xmlbase->participation) {
115 $ret = diaspora_participation($importer,$xmlbase->participation);
118 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
123 function diaspora_handle_from_contact($contact_id) {
126 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
128 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
134 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
136 if($contact['network'] === NETWORK_DIASPORA) {
137 $handle = $contact['addr'];
139 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
141 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
142 $baseurl_start = strpos($contact['url'],'://') + 3;
143 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
144 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
145 $handle = $contact['nick'] . '@' . $baseurl;
147 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
154 function diaspora_get_contact_by_handle($uid,$handle) {
155 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
156 dbesc(NETWORK_DIASPORA),
163 $handle_parts = explode("@", $handle);
164 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
165 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
176 function find_diaspora_person_by_handle($handle) {
186 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
187 dbesc(NETWORK_DIASPORA),
192 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
194 // update record occasionally so it doesn't get stale
195 $d = strtotime($person['updated'] . ' +00:00');
196 if($d < strtotime('now - 14 days'))
201 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
203 // If the person isn't in our 'fcontact' table, or if he/she is but
204 // his/her information hasn't been updated for more than 14 days, then
205 // we want to fetch the person's information from the remote server.
207 // Note that $person isn't changed by this block of code unless the
208 // person's information has been successfully fetched from the remote
209 // server. So if $person was 'false' to begin with (because he/she wasn't
210 // in the local cache), it'll stay false, and if $person held the local
211 // cache information to begin with, it'll keep that information. That way
212 // if there's a problem with the remote fetch, we can at least use our
213 // cached information--it's better than nothing.
215 if((! $person) || ($update)) {
216 // Lock the function to prevent race conditions if multiple items
217 // come in at the same time from a person who doesn't exist in
220 // Don't loop forever. On the last loop, try to create the contact
221 // whether the function is locked or not. Maybe the locking thread
222 // has died or something. At any rate, a duplicate in 'fcontact'
223 // is a much smaller problem than a deadlocked thread
224 $got_lock = lock_function('find_diaspora_person_by_handle', false);
225 if(($endlessloop + 1) >= $maxloops)
229 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
230 require_once('include/Scrape.php');
231 $r = probe_url($handle, PROBE_DIASPORA);
233 // Note that Friendica contacts can return a "Diaspora person"
234 // if Diaspora connectivity is enabled on their server
235 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
236 add_fcontact($r,$update);
240 unlock_function('find_diaspora_person_by_handle');
243 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
245 block_on_function_lock('find_diaspora_person_by_handle');
248 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
249 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
250 // The fact that the function was locked may mean that another process was creating the
251 // person's record. It could also mean another process was creating or updating an unrelated
254 // At any rate, we need to keep trying until we've either got the person or had a chance to
255 // try to fetch his/her remote information. But we don't want to block on locking the
256 // function, because if the other process is creating the record, then when we acquire the lock
257 // we'll dive right into creating another, duplicate record. We DO want to at least wait
258 // until the lock is released, so we don't flood the database with requests.
260 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
261 // we do have some information for the person
267 function get_diaspora_key($uri) {
268 logger('Fetching diaspora key for: ' . $uri);
270 $r = find_diaspora_person_by_handle($uri);
277 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
280 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
283 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
285 // $b64_data = base64_encode($msg);
286 // $b64url_data = base64url_encode($b64_data);
288 $b64url_data = base64url_encode($msg);
290 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
292 $type = 'application/xml';
293 $encoding = 'base64url';
296 $signable_data = $data . '.' . base64url_encode($type) . '.'
297 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
299 $signature = rsa_sign($signable_data,$prvkey);
300 $sig = base64url_encode($signature);
303 <?xml version='1.0' encoding='UTF-8'?>
304 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
306 <author_id>$handle</author_id>
309 <me:encoding>base64url</me:encoding>
310 <me:alg>RSA-SHA256</me:alg>
311 <me:data type="application/xml">$data</me:data>
312 <me:sig>$sig</me:sig>
317 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
325 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
329 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
331 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
333 // without a public key nothing will work
336 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
340 $inner_aes_key = random_string(32);
341 $b_inner_aes_key = base64_encode($inner_aes_key);
342 $inner_iv = random_string(16);
343 $b_inner_iv = base64_encode($inner_iv);
345 $outer_aes_key = random_string(32);
346 $b_outer_aes_key = base64_encode($outer_aes_key);
347 $outer_iv = random_string(16);
348 $b_outer_iv = base64_encode($outer_iv);
350 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
352 $padded_data = pkcs5_pad($msg,16);
353 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
355 $b64_data = base64_encode($inner_encrypted);
358 $b64url_data = base64url_encode($b64_data);
359 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
361 $type = 'application/xml';
362 $encoding = 'base64url';
365 $signable_data = $data . '.' . base64url_encode($type) . '.'
366 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
368 $signature = rsa_sign($signable_data,$prvkey);
369 $sig = base64url_encode($signature);
371 $decrypted_header = <<< EOT
374 <aes_key>$b_inner_aes_key</aes_key>
375 <author_id>$handle</author_id>
379 $decrypted_header = pkcs5_pad($decrypted_header,16);
381 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
383 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
385 $encrypted_outer_key_bundle = '';
386 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
388 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
390 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
392 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
393 'ciphertext' => base64_encode($ciphertext)));
394 $cipher_json = base64_encode($encrypted_header_json_object);
396 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
399 <?xml version='1.0' encoding='UTF-8'?>
400 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
403 <me:encoding>base64url</me:encoding>
404 <me:alg>RSA-SHA256</me:alg>
405 <me:data type="application/xml">$data</me:data>
406 <me:sig>$sig</me:sig>
411 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
418 * diaspora_decode($importer,$xml)
419 * array $importer -> from user table
420 * string $xml -> urldecoded Diaspora salmon
423 * 'message' -> decoded Diaspora XML message
424 * 'author' -> author diaspora handle
425 * 'key' -> author public key (converted to pkcs#8)
427 * Author and key are used elsewhere to save a lookup for verifying replies and likes
431 function diaspora_decode($importer,$xml) {
434 $basedom = parse_xml_string($xml);
436 $children = $basedom->children('https://joindiaspora.com/protocol');
438 if($children->header) {
440 $author_link = str_replace('acct:','',$children->header->author_id);
444 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
446 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
447 $ciphertext = base64_decode($encrypted_header->ciphertext);
449 $outer_key_bundle = '';
450 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
452 $j_outer_key_bundle = json_decode($outer_key_bundle);
454 $outer_iv = base64_decode($j_outer_key_bundle->iv);
455 $outer_key = base64_decode($j_outer_key_bundle->key);
457 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
460 $decrypted = pkcs5_unpad($decrypted);
463 * $decrypted now contains something like
466 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
467 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
472 * <name>Ryan Hughes</name>
473 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
478 * <author_id>galaxor@diaspora.priateship.org</author_id>
482 * </decrypted_header>
485 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
486 $idom = parse_xml_string($decrypted,false);
488 $inner_iv = base64_decode($idom->iv);
489 $inner_aes_key = base64_decode($idom->aes_key);
491 $author_link = str_replace('acct:','',$idom->author_id);
495 $dom = $basedom->children(NAMESPACE_SALMON_ME);
497 // figure out where in the DOM tree our data is hiding
499 if($dom->provenance->data)
500 $base = $dom->provenance;
501 elseif($dom->env->data)
507 logger('mod-diaspora: unable to locate salmon data in xml ');
508 http_status_exit(400);
512 // Stash the signature away for now. We have to find their key or it won't be good for anything.
513 $signature = base64url_decode($base->sig);
517 // strip whitespace so our data element will return to one big base64 blob
518 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
521 // stash away some other stuff for later
523 $type = $base->data[0]->attributes()->type[0];
524 $keyhash = $base->sig[0]->attributes()->keyhash[0];
525 $encoding = $base->encoding;
529 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
533 $data = base64url_decode($data);
537 $inner_decrypted = $data;
541 // Decode the encrypted blob
543 $inner_encrypted = base64_decode($data);
544 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
545 $inner_decrypted = pkcs5_unpad($inner_decrypted);
549 logger('mod-diaspora: Could not retrieve author URI.');
550 http_status_exit(400);
553 // Once we have the author URI, go to the web and try to find their public key
554 // (first this will look it up locally if it is in the fcontact cache)
555 // This will also convert diaspora public key from pkcs#1 to pkcs#8
557 logger('mod-diaspora: Fetching key for ' . $author_link );
558 $key = get_diaspora_key($author_link);
561 logger('mod-diaspora: Could not retrieve author key.');
562 http_status_exit(400);
565 $verify = rsa_verify($signed_data,$signature,$key);
568 logger('mod-diaspora: Message did not verify. Discarding.');
569 http_status_exit(400);
572 logger('mod-diaspora: Message verified.');
574 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
579 function diaspora_request($importer,$xml) {
583 $sender_handle = unxmlify($xml->sender_handle);
584 $recipient_handle = unxmlify($xml->recipient_handle);
586 if(! $sender_handle || ! $recipient_handle)
589 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
593 // perhaps we were already sharing with this person. Now they're sharing with us.
594 // That makes us friends.
596 if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
597 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
598 intval(CONTACT_IS_FRIEND),
599 intval($contact['id']),
600 intval($importer['uid'])
605 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
606 intval($importer['uid'])
609 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
610 require_once('include/items.php');
612 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
613 intval($importer['uid'])
616 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
618 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
621 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
622 $arr['uid'] = $importer['uid'];
623 $arr['contact-id'] = $self[0]['id'];
625 $arr['type'] = 'wall';
628 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
629 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
630 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
631 $arr['verb'] = ACTIVITY_FRIEND;
632 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
634 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
635 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
636 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
637 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
639 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
640 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
641 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
642 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
643 $arr['object'] .= '</link></object>' . "\n";
644 $arr['last-child'] = 1;
646 $arr['allow_cid'] = $user[0]['allow_cid'];
647 $arr['allow_gid'] = $user[0]['allow_gid'];
648 $arr['deny_cid'] = $user[0]['deny_cid'];
649 $arr['deny_gid'] = $user[0]['deny_gid'];
651 $i = item_store($arr);
653 proc_run('php',"include/notifier.php","activity","$i");
662 $ret = find_diaspora_person_by_handle($sender_handle);
665 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
666 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
670 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
674 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
675 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
676 intval($importer['uid']),
677 dbesc($ret['network']),
681 dbesc(normalise_link($ret['url'])),
685 dbesc($ret['photo']),
686 dbesc($ret['pubkey']),
687 dbesc($ret['notify']),
693 // find the contact record we just created
695 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
697 if(! $contact_record) {
698 logger('diaspora_request: unable to locate newly created contact record.');
702 $g = q("select def_gid from user where uid = %d limit 1",
703 intval($importer['uid'])
705 if($g && intval($g[0]['def_gid'])) {
706 require_once('include/group.php');
707 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
710 if($importer['page-flags'] == PAGE_NORMAL) {
712 $hash = random_string() . (string) time(); // Generate a confirm_key
714 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
715 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
716 intval($importer['uid']),
717 intval($contact_record['id']),
720 dbesc( t('Sharing notification from Diaspora network')),
722 dbesc(datetime_convert())
727 // automatic friend approval
729 require_once('include/Photo.php');
731 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
733 // technically they are sharing with us (CONTACT_IS_SHARING),
734 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
735 // we are going to change the relationship and make them a follower.
737 if($importer['page-flags'] == PAGE_FREELOVE)
738 $new_relation = CONTACT_IS_FRIEND;
740 $new_relation = CONTACT_IS_FOLLOWER;
742 $r = q("UPDATE `contact` SET
749 `avatar-date` = '%s',
758 intval($new_relation),
759 dbesc(datetime_convert()),
760 dbesc(datetime_convert()),
761 dbesc(datetime_convert()),
762 intval($contact_record['id'])
765 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
767 $ret = diaspora_share($u[0],$contact_record);
773 function diaspora_post_allow($importer,$contact, $is_comment = false) {
775 // perhaps we were already sharing with this person. Now they're sharing with us.
776 // That makes us friends.
777 // Normally this should have handled by getting a request - but this could get lost
778 if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
779 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
780 intval(CONTACT_IS_FRIEND),
781 intval($contact['id']),
782 intval($importer['uid'])
784 $contact['rel'] = CONTACT_IS_FRIEND;
785 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
788 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
790 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
792 if($contact['rel'] == CONTACT_IS_FOLLOWER)
793 if(($importer['page-flags'] == PAGE_COMMUNITY) OR $is_comment)
796 // Messages for the global users are always accepted
797 if ($importer['uid'] == 0)
803 function diaspora_is_redmatrix($url) {
804 return(strstr($url, "/channel/"));
807 function diaspora_plink($addr, $guid) {
808 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
812 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
814 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
815 // So we try another way as well.
816 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
818 $r[0]["network"] = $s[0]["network"];
820 if ($r[0]["network"] == NETWORK_DFRN)
821 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
823 if (diaspora_is_redmatrix($r[0]["url"]))
824 return $r[0]["url"]."/?f=&mid=".$guid;
826 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
829 function diaspora_repair_signature($signature, $handle = "", $level = 1) {
830 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
831 $signature = base64_decode($signature);
832 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
834 // Do a recursive call to be able to fix even multiple levels
836 $signature = diaspora_repair_signature($signature, $handle, ++$level);
842 function diaspora_post($importer,$xml,$msg) {
845 $guid = notags(unxmlify($xml->guid));
846 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
848 if($diaspora_handle != $msg['author']) {
849 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
853 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
855 logger('diaspora_post: A Contact for handle '.$diaspora_handle.' and user '.$importer['uid'].' was not found');
859 if(! diaspora_post_allow($importer,$contact, false)) {
860 logger('diaspora_post: Ignoring this author.');
864 $message_id = $diaspora_handle . ':' . $guid;
865 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
866 intval($importer['uid']),
870 logger('diaspora_post: message exists: ' . $guid);
874 $created = unxmlify($xml->created_at);
875 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
877 $body = diaspora2bb($xml->raw_message);
881 $datarray["object"] = json_encode($xml);
883 if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
884 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
886 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
887 // Add OEmbed and other information to the body
888 if (!diaspora_is_redmatrix($contact['url']))
889 $body = add_page_info_to_body($body, false, true);
894 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
896 foreach($matches as $mtch) {
897 if(strlen($str_tags))
899 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
903 $plink = diaspora_plink($diaspora_handle, $guid);
905 $datarray['uid'] = $importer['uid'];
906 $datarray['contact-id'] = $contact['id'];
907 $datarray['wall'] = 0;
908 $datarray['network'] = NETWORK_DIASPORA;
909 $datarray['verb'] = ACTIVITY_POST;
910 $datarray['guid'] = $guid;
911 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
912 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
913 $datarray['private'] = $private;
914 $datarray['parent'] = 0;
915 $datarray['plink'] = $plink;
916 $datarray['owner-name'] = $contact['name'];
917 $datarray['owner-link'] = $contact['url'];
918 //$datarray['owner-avatar'] = $contact['thumb'];
919 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
920 $datarray['author-name'] = $contact['name'];
921 $datarray['author-link'] = $contact['url'];
922 $datarray['author-avatar'] = $contact['thumb'];
923 $datarray['body'] = $body;
924 $datarray['tag'] = $str_tags;
925 if ($xml->provider_display_name)
926 $datarray["app"] = unxmlify($xml->provider_display_name);
928 $datarray['app'] = 'Diaspora';
930 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
932 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
934 DiasporaFetchGuid($datarray);
935 $message_id = item_store($datarray);
937 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
943 function DiasporaFetchGuid($item) {
944 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
945 function ($match) use ($item){
946 return(DiasporaFetchGuidSub($match, $item));
950 function DiasporaFetchGuidSub($match, $item) {
953 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
954 diaspora_store_by_guid($match[1], $item["owner-link"]);
957 function diaspora_store_by_guid($guid, $server, $uid = 0) {
958 require_once("include/Contact.php");
960 $serverparts = parse_url($server);
961 $server = $serverparts["scheme"]."://".$serverparts["host"];
963 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
965 $item = diaspora_fetch_message($guid, $server);
970 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
972 $body = $item["body"];
973 $str_tags = $item["tag"];
975 $created = $item["created"];
976 $author = $item["author"];
977 $guid = $item["guid"];
978 $private = $item["private"];
979 $object = $item["object"];
980 $objecttype = $item["object-type"];
982 $message_id = $author.':'.$guid;
983 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
990 $person = find_diaspora_person_by_handle($author);
992 $contact_id = get_contact($person['url'], $uid);
994 $contacts = q("SELECT * FROM `contact` WHERE `id` = %d", intval($contact_id));
995 $importers = q("SELECT * FROM `user` WHERE `uid` = %d", intval($uid));
997 if ($contacts AND $importers)
998 if(!diaspora_post_allow($importers[0],$contacts[0], false)) {
999 logger('Ignoring author '.$person['url'].' for uid '.$uid);
1002 logger('Author '.$person['url'].' is allowed for uid '.$uid);
1004 $datarray = array();
1005 $datarray['uid'] = $uid;
1006 $datarray['contact-id'] = $contact_id;
1007 $datarray['wall'] = 0;
1008 $datarray['network'] = NETWORK_DIASPORA;
1009 $datarray['guid'] = $guid;
1010 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1011 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1012 $datarray['private'] = $private;
1013 $datarray['parent'] = 0;
1014 $datarray['plink'] = diaspora_plink($author, $guid);
1015 $datarray['author-name'] = $person['name'];
1016 $datarray['author-link'] = $person['url'];
1017 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1018 $datarray['owner-name'] = $datarray['author-name'];
1019 $datarray['owner-link'] = $datarray['author-link'];
1020 $datarray['owner-avatar'] = $datarray['author-avatar'];
1021 $datarray['body'] = $body;
1022 $datarray['tag'] = $str_tags;
1023 $datarray['app'] = $app;
1024 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1025 $datarray['object'] = $object;
1026 $datarray['object-type'] = $objecttype;
1028 if ($datarray['contact-id'] == 0)
1031 DiasporaFetchGuid($datarray);
1032 $message_id = item_store($datarray);
1035 /// Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
1040 function diaspora_fetch_message($guid, $server, $level = 0) {
1047 // This will not work if the server is not a Diaspora server
1048 $source_url = $server.'/p/'.$guid.'.xml';
1049 $x = fetch_url($source_url);
1053 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1054 $source_xml = parse_xml_string($x,false);
1057 $item["app"] = 'Diaspora';
1058 $item["guid"] = $guid;
1061 if ($source_xml->post->status_message->created_at)
1062 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1064 if ($source_xml->post->status_message->provider_display_name)
1065 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1067 if ($source_xml->post->status_message->diaspora_handle)
1068 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1070 if ($source_xml->post->status_message->guid)
1071 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1073 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1074 $item["object"] = json_encode($source_xml->post);
1076 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1077 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1078 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1079 $body = scale_external_images($body,false);
1080 } elseif($source_xml->post->asphoto->image_url) {
1081 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1082 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1083 $body = scale_external_images($body);
1084 } elseif($source_xml->post->status_message) {
1085 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1087 // Checking for embedded pictures
1088 if($source_xml->post->status_message->photo->remote_photo_path AND
1089 $source_xml->post->status_message->photo->remote_photo_name) {
1091 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1093 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1094 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1096 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1098 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1100 $item["object-type"] = ACTIVITY_OBJ_NOTE;
1102 $body = scale_external_images($body);
1104 // Add OEmbed and other information to the body
1105 /// @TODO It could be a repeated redmatrix item
1106 /// Then we shouldn't add further data to it
1107 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1108 $body = add_page_info_to_body($body, false, true);
1110 } elseif($source_xml->post->reshare) {
1111 // Reshare of a reshare
1112 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1114 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1115 logger('no content found: '.print_r($source_xml,true));
1119 if (trim($body) == "")
1123 $item["body"] = $body;
1128 function diaspora_reshare($importer,$xml,$msg) {
1130 logger('diaspora_reshare: init: ' . print_r($xml,true));
1133 $guid = notags(unxmlify($xml->guid));
1134 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1137 if($diaspora_handle != $msg['author']) {
1138 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1142 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1146 if(! diaspora_post_allow($importer,$contact, false)) {
1147 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1151 $message_id = $diaspora_handle . ':' . $guid;
1152 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1153 intval($importer['uid']),
1157 logger('diaspora_reshare: message exists: ' . $guid);
1161 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1162 $orig_guid = notags(unxmlify($xml->root_guid));
1163 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1165 $create_original_post = false;
1167 // Do we already have this item?
1168 $r = q("SELECT `body`, `tag`, `app`, `created`, `plink`, `object`, `object-type`, `uri` FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1170 dbesc(NETWORK_DIASPORA)
1173 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1175 // Maybe it is already a reshared item?
1176 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1177 require_once('include/api.php');
1178 if (api_share_as_retweet($r[0]))
1181 $body = $r[0]["body"];
1182 $str_tags = $r[0]["tag"];
1183 $app = $r[0]["app"];
1184 $orig_created = $r[0]["created"];
1185 $orig_plink = $r[0]["plink"];
1186 $orig_uri = $r[0]["uri"];
1187 $object = $r[0]["object"];
1188 $objecttype = $r[0]["object-type"];
1197 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1198 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1199 $item = diaspora_fetch_message($orig_guid, $server);
1202 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1203 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1204 $item = diaspora_fetch_message($orig_guid, $server);
1207 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1208 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1209 $item = diaspora_fetch_message($orig_guid, $server);
1212 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1213 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1214 $item = diaspora_fetch_message($orig_guid, $server);
1218 $body = $item["body"];
1219 $str_tags = $item["tag"];
1220 $app = $item["app"];
1221 $orig_created = $item["created"];
1222 $orig_author = $item["author"];
1223 $orig_guid = $item["guid"];
1224 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1225 $orig_uri = $orig_author.':'.$orig_guid;
1226 $create_original_post = ($body != "");
1227 $object = $item["object"];
1228 $objecttype = $item["object-type"];
1232 $plink = diaspora_plink($diaspora_handle, $guid);
1234 $person = find_diaspora_person_by_handle($orig_author);
1236 $created = unxmlify($xml->created_at);
1237 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1239 $datarray = array();
1241 $datarray['uid'] = $importer['uid'];
1242 $datarray['contact-id'] = $contact['id'];
1243 $datarray['wall'] = 0;
1244 $datarray['network'] = NETWORK_DIASPORA;
1245 $datarray['guid'] = $guid;
1246 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1247 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1248 $datarray['private'] = $private;
1249 $datarray['parent'] = 0;
1250 $datarray['plink'] = $plink;
1251 $datarray['owner-name'] = $contact['name'];
1252 $datarray['owner-link'] = $contact['url'];
1253 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1254 if (!intval(get_config('system','wall-to-wall_share'))) {
1255 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1257 $datarray['author-name'] = $contact['name'];
1258 $datarray['author-link'] = $contact['url'];
1259 $datarray['author-avatar'] = $contact['thumb'];
1260 $datarray['body'] = $prefix.$body."[/share]";
1262 // Let reshared messages look like wall-to-wall posts
1263 $datarray['author-name'] = $person['name'];
1264 $datarray['author-link'] = $person['url'];
1265 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1266 $datarray['body'] = $body;
1269 $datarray["object"] = json_encode($xml);
1270 $datarray['object-type'] = $objecttype;
1272 $datarray['tag'] = $str_tags;
1273 $datarray['app'] = $app;
1275 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1276 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1278 // Store the original item of a reshare
1279 if ($create_original_post) {
1280 require_once("include/Contact.php");
1282 $datarray2 = $datarray;
1284 $datarray2['uid'] = 0;
1285 $datarray2['contact-id'] = get_contact($person['url'], 0);
1286 $datarray2['guid'] = $orig_guid;
1287 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1288 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1289 $datarray2['parent'] = 0;
1290 $datarray2['plink'] = $orig_plink;
1292 $datarray2['author-name'] = $person['name'];
1293 $datarray2['author-link'] = $person['url'];
1294 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1295 $datarray2['owner-name'] = $datarray2['author-name'];
1296 $datarray2['owner-link'] = $datarray2['author-link'];
1297 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1298 $datarray2['body'] = $body;
1299 $datarray2["object"] = $object;
1301 DiasporaFetchGuid($datarray2);
1302 $message_id = item_store($datarray2);
1304 logger("Store original item ".$orig_guid." under message id ".$message_id);
1307 DiasporaFetchGuid($datarray);
1308 $message_id = item_store($datarray);
1315 function diaspora_asphoto($importer,$xml,$msg) {
1316 logger('diaspora_asphoto called');
1319 $guid = notags(unxmlify($xml->guid));
1320 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1322 if($diaspora_handle != $msg['author']) {
1323 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1327 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1331 if(! diaspora_post_allow($importer,$contact, false)) {
1332 logger('diaspora_asphoto: Ignoring this author.');
1336 $message_id = $diaspora_handle . ':' . $guid;
1337 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1338 intval($importer['uid']),
1342 logger('diaspora_asphoto: message exists: ' . $guid);
1346 $created = unxmlify($xml->created_at);
1347 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1349 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1350 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1351 $body = scale_external_images($body,false);
1353 elseif($xml->image_url) {
1354 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1355 $body = scale_external_images($body);
1358 logger('diaspora_asphoto: no photo url found.');
1362 $plink = diaspora_plink($diaspora_handle, $guid);
1364 $datarray = array();
1366 $datarray['uid'] = $importer['uid'];
1367 $datarray['contact-id'] = $contact['id'];
1368 $datarray['wall'] = 0;
1369 $datarray['network'] = NETWORK_DIASPORA;
1370 $datarray['guid'] = $guid;
1371 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1372 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1373 $datarray['private'] = $private;
1374 $datarray['parent'] = 0;
1375 $datarray['plink'] = $plink;
1376 $datarray['owner-name'] = $contact['name'];
1377 $datarray['owner-link'] = $contact['url'];
1378 //$datarray['owner-avatar'] = $contact['thumb'];
1379 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1380 $datarray['author-name'] = $contact['name'];
1381 $datarray['author-link'] = $contact['url'];
1382 $datarray['author-avatar'] = $contact['thumb'];
1383 $datarray['body'] = $body;
1384 $datarray["object"] = json_encode($xml);
1385 $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1387 $datarray['app'] = 'Diaspora/Cubbi.es';
1389 DiasporaFetchGuid($datarray);
1390 $message_id = item_store($datarray);
1393 // q("update item set plink = '%s' where id = %d",
1394 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1395 // intval($message_id)
1403 function diaspora_comment($importer,$xml,$msg) {
1406 $guid = notags(unxmlify($xml->guid));
1407 $parent_guid = notags(unxmlify($xml->parent_guid));
1408 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1409 $target_type = notags(unxmlify($xml->target_type));
1410 $text = unxmlify($xml->text);
1411 $author_signature = notags(unxmlify($xml->author_signature));
1413 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1415 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1417 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1421 if(! diaspora_post_allow($importer,$contact, true)) {
1422 logger('diaspora_comment: Ignoring this author.');
1426 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1427 intval($importer['uid']),
1431 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1435 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1436 intval($importer['uid']),
1441 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1444 $person = find_diaspora_person_by_handle($diaspora_handle);
1445 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1449 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1451 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1452 intval($importer['uid']),
1459 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1462 $parent_item = $r[0];
1465 /* How Diaspora performs comment signature checking:
1467 - If an item has been sent by the comment author to the top-level post owner to relay on
1468 to the rest of the contacts on the top-level post, the top-level post owner should check
1469 the author_signature, then create a parent_author_signature before relaying the comment on
1470 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1471 check only the parent_author_signature. Basically, they trust that the top-level post
1472 owner has already verified the authenticity of anything he/she sends out
1473 - In either case, the signature that get checked is the signature created by the person
1477 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1480 if($parent_author_signature) {
1481 // If a parent_author_signature exists, then we've received the comment
1482 // relayed from the top-level post owner. There's no need to check the
1483 // author_signature if the parent_author_signature is valid
1485 $parent_author_signature = base64_decode($parent_author_signature);
1487 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1488 logger('diaspora_comment: top-level owner verification failed.');
1493 // If there's no parent_author_signature, then we've received the comment
1494 // from the comment creator. In that case, the person is commenting on
1495 // our post, so he/she must be a contact of ours and his/her public key
1496 // should be in $msg['key']
1498 $author_signature = base64_decode($author_signature);
1500 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1501 logger('diaspora_comment: comment author verification failed.');
1506 // Phew! Everything checks out. Now create an item.
1508 // Find the original comment author information.
1509 // We need this to make sure we display the comment author
1510 // information (name and avatar) correctly.
1511 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1514 $person = find_diaspora_person_by_handle($diaspora_handle);
1516 if(! is_array($person)) {
1517 logger('diaspora_comment: unable to find author details');
1522 // Fetch the contact id - if we know this contact
1523 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1524 dbesc(normalise_link($person['url'])), intval($importer['uid']));
1527 $network = $r[0]['network'];
1529 $cid = $contact['id'];
1530 $network = NETWORK_DIASPORA;
1533 $body = diaspora2bb($text);
1534 $message_id = $diaspora_handle . ':' . $guid;
1536 $datarray = array();
1538 $datarray['uid'] = $importer['uid'];
1539 $datarray['contact-id'] = $cid;
1540 $datarray['type'] = 'remote-comment';
1541 $datarray['wall'] = $parent_item['wall'];
1542 $datarray['network'] = $network;
1543 $datarray['verb'] = ACTIVITY_POST;
1544 $datarray['gravity'] = GRAVITY_COMMENT;
1545 $datarray['guid'] = $guid;
1546 $datarray['uri'] = $message_id;
1547 $datarray['parent-uri'] = $parent_item['uri'];
1549 // No timestamps for comments? OK, we'll the use current time.
1550 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1551 $datarray['private'] = $parent_item['private'];
1553 $datarray['owner-name'] = $parent_item['owner-name'];
1554 $datarray['owner-link'] = $parent_item['owner-link'];
1555 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1557 $datarray['author-name'] = $person['name'];
1558 $datarray['author-link'] = $person['url'];
1559 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1560 $datarray['body'] = $body;
1561 $datarray["object"] = json_encode($xml);
1562 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1564 // We can't be certain what the original app is if the message is relayed.
1565 if(($parent_item['origin']) && (! $parent_author_signature))
1566 $datarray['app'] = 'Diaspora';
1568 DiasporaFetchGuid($datarray);
1569 $message_id = item_store($datarray);
1571 $datarray['id'] = $message_id;
1574 //q("update item set plink = '%s' where id = %d",
1575 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1576 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1577 // intval($message_id)
1581 // If we are the origin of the parent we store the original signature and notify our followers
1582 if($parent_item['origin']) {
1583 $author_signature_base64 = base64_encode($author_signature);
1584 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
1586 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1587 intval($message_id),
1588 dbesc($signed_data),
1589 dbesc($author_signature_base64),
1590 dbesc($diaspora_handle)
1594 proc_run('php','include/notifier.php','comment-import',$message_id);
1597 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1598 dbesc($parent_item['uri']),
1599 intval($importer['uid'])
1602 if(count($myconv)) {
1603 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1605 foreach($myconv as $conv) {
1607 // now if we find a match, it means we're in this conversation
1609 if(! link_compare($conv['author-link'],$importer_url))
1612 require_once('include/enotify.php');
1614 $conv_parent = $conv['parent'];
1617 'type' => NOTIFY_COMMENT,
1618 'notify_flags' => $importer['notify-flags'],
1619 'language' => $importer['language'],
1620 'to_name' => $importer['username'],
1621 'to_email' => $importer['email'],
1622 'uid' => $importer['uid'],
1623 'item' => $datarray,
1624 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1625 'source_name' => $datarray['author-name'],
1626 'source_link' => $datarray['author-link'],
1627 'source_photo' => $datarray['author-avatar'],
1628 'verb' => ACTIVITY_POST,
1630 'parent' => $conv_parent,
1631 'parent_uri' => $parent_uri
1634 // only send one notification
1644 function diaspora_conversation($importer,$xml,$msg) {
1648 $guid = notags(unxmlify($xml->guid));
1649 $subject = notags(unxmlify($xml->subject));
1650 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1651 $participant_handles = notags(unxmlify($xml->participant_handles));
1652 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1654 $parent_uri = $diaspora_handle . ':' . $guid;
1656 $messages = $xml->message;
1658 if(! count($messages)) {
1659 logger('diaspora_conversation: empty conversation');
1663 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1665 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1669 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1670 logger('diaspora_conversation: Ignoring this author.');
1674 $conversation = null;
1676 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1677 intval($importer['uid']),
1681 $conversation = $c[0];
1683 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1684 intval($importer['uid']),
1686 dbesc($diaspora_handle),
1687 dbesc(datetime_convert('UTC','UTC',$created_at)),
1688 dbesc(datetime_convert()),
1690 dbesc($participant_handles)
1693 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1694 intval($importer['uid']),
1698 $conversation = $c[0];
1700 if(! $conversation) {
1701 logger('diaspora_conversation: unable to create conversation.');
1705 foreach($messages as $mesg) {
1709 $msg_guid = notags(unxmlify($mesg->guid));
1710 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1711 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1712 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1713 $msg_text = unxmlify($mesg->text);
1714 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1715 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1716 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1717 if($msg_conversation_guid != $guid) {
1718 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1722 $body = diaspora2bb($msg_text);
1723 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1725 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1727 $author_signature = base64_decode($msg_author_signature);
1729 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1734 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1736 if(is_array($person) && x($person,'pubkey'))
1737 $key = $person['pubkey'];
1739 logger('diaspora_conversation: unable to find author details');
1744 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1745 logger('diaspora_conversation: verification failed.');
1749 if($msg_parent_author_signature) {
1750 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1752 $parent_author_signature = base64_decode($msg_parent_author_signature);
1756 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1757 logger('diaspora_conversation: owner verification failed.');
1762 $r = q("select id from mail where `uri` = '%s' limit 1",
1766 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1770 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')",
1771 intval($importer['uid']),
1773 intval($conversation['id']),
1774 dbesc($person['name']),
1775 dbesc($person['photo']),
1776 dbesc($person['url']),
1777 intval($contact['id']),
1784 dbesc($msg_created_at)
1787 q("update conv set updated = '%s' where id = %d",
1788 dbesc(datetime_convert()),
1789 intval($conversation['id'])
1792 require_once('include/enotify.php');
1794 'type' => NOTIFY_MAIL,
1795 'notify_flags' => $importer['notify-flags'],
1796 'language' => $importer['language'],
1797 'to_name' => $importer['username'],
1798 'to_email' => $importer['email'],
1799 'uid' =>$importer['uid'],
1800 'item' => array('subject' => $subject, 'body' => $body),
1801 'source_name' => $person['name'],
1802 'source_link' => $person['url'],
1803 'source_photo' => $person['thumb'],
1804 'verb' => ACTIVITY_POST,
1812 function diaspora_message($importer,$xml,$msg) {
1816 $msg_guid = notags(unxmlify($xml->guid));
1817 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1818 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1819 $msg_author_signature = notags(unxmlify($xml->author_signature));
1820 $msg_text = unxmlify($xml->text);
1821 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1822 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1823 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1825 $parent_uri = $msg_diaspora_handle . ':' . $msg_parent_guid;
1827 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1829 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1833 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1834 logger('diaspora_message: Ignoring this author.');
1838 $conversation = null;
1840 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1841 intval($importer['uid']),
1842 dbesc($msg_conversation_guid)
1845 $conversation = $c[0];
1847 logger('diaspora_message: conversation not available.');
1853 $body = diaspora2bb($msg_text);
1854 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1856 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1859 $author_signature = base64_decode($msg_author_signature);
1861 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1862 if(is_array($person) && x($person,'pubkey'))
1863 $key = $person['pubkey'];
1865 logger('diaspora_message: unable to find author details');
1869 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1870 logger('diaspora_message: verification failed.');
1874 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1876 intval($importer['uid'])
1879 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1883 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')",
1884 intval($importer['uid']),
1886 intval($conversation['id']),
1887 dbesc($person['name']),
1888 dbesc($person['photo']),
1889 dbesc($person['url']),
1890 intval($contact['id']),
1891 dbesc($conversation['subject']),
1897 dbesc($msg_created_at)
1900 q("update conv set updated = '%s' where id = %d",
1901 dbesc(datetime_convert()),
1902 intval($conversation['id'])
1908 function diaspora_participation($importer,$xml) {
1909 logger("Unsupported message type 'participation' ".print_r($xml, true));
1912 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1916 logger('diaspora_photo: init',LOGGER_DEBUG);
1918 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1920 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1922 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1924 $guid = notags(unxmlify($xml->guid));
1926 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1928 $public = notags(unxmlify($xml->public));
1930 $created_at = notags(unxmlify($xml_created_at));
1932 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1934 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1936 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1940 if(! diaspora_post_allow($importer,$contact, false)) {
1941 logger('diaspora_photo: Ignoring this author.');
1945 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1946 intval($importer['uid']),
1947 dbesc($status_message_guid)
1950 /* deactivated by now since it can lead to multiplicated pictures in posts.
1952 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1955 $person = find_diaspora_person_by_handle($diaspora_handle);
1956 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1960 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1962 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1963 intval($importer['uid']),
1964 dbesc($status_message_guid)
1971 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1972 intval($importer['uid']),
1973 dbesc(serialize($msg)),
1974 intval($attempt + 1)
1978 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1982 $parent_item = $r[0];
1984 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1986 $link_text = scale_external_images($link_text, true,
1987 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1989 if(strpos($parent_item['body'],$link_text) === false) {
1991 $parent_item['body'] = $link_text . $parent_item['body'];
1993 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1994 dbesc($parent_item['body']),
1995 intval($parent_item['id']),
1996 intval($parent_item['uid'])
1998 put_item_in_cache($parent_item, true);
1999 update_thread($parent_item['id']);
2008 function diaspora_like($importer,$xml,$msg) {
2011 $guid = notags(unxmlify($xml->guid));
2012 $parent_guid = notags(unxmlify($xml->parent_guid));
2013 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2014 $target_type = notags(unxmlify($xml->target_type));
2015 $positive = notags(unxmlify($xml->positive));
2016 $author_signature = notags(unxmlify($xml->author_signature));
2018 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2020 // likes on comments not supported here and likes on photos not supported by Diaspora
2022 // if($target_type !== 'Post')
2025 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
2027 logger('diaspora_like: cannot find contact: ' . $msg['author']);
2031 if(! diaspora_post_allow($importer,$contact, false)) {
2032 logger('diaspora_like: Ignoring this author.');
2036 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2037 intval($importer['uid']),
2042 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
2045 $person = find_diaspora_person_by_handle($diaspora_handle);
2046 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
2050 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
2052 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2053 intval($importer['uid']),
2060 logger('diaspora_like: parent item not found: ' . $guid);
2064 $parent_item = $r[0];
2066 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2067 intval($importer['uid']),
2071 if($positive === 'true') {
2072 logger('diaspora_like: duplicate like: ' . $guid);
2075 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2076 // It looks like "RelayableRetractions" are used for "unlike" instead
2077 if($positive === 'false') {
2078 logger('diaspora_like: received a like with positive set to "false"...ignoring');
2079 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2080 intval($r[0]['id']),
2081 intval($importer['uid'])
2083 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2084 // send notification via proc_run()
2088 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2089 // It looks like "RelayableRetractions" are used for "unlike" instead
2090 if($positive === 'false') {
2091 logger('diaspora_like: received a like with positive set to "false"');
2092 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2097 /* How Diaspora performs "like" signature checking:
2099 - If an item has been sent by the like author to the top-level post owner to relay on
2100 to the rest of the contacts on the top-level post, the top-level post owner should check
2101 the author_signature, then create a parent_author_signature before relaying the like on
2102 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2103 check only the parent_author_signature. Basically, they trust that the top-level post
2104 owner has already verified the authenticity of anything he/she sends out
2105 - In either case, the signature that get checked is the signature created by the person
2109 // Diaspora has changed the way they are signing the likes.
2110 // Just to make sure that we don't miss any likes we will check the old and the current way.
2111 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2113 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2117 if ($parent_author_signature) {
2118 // If a parent_author_signature exists, then we've received the like
2119 // relayed from the top-level post owner. There's no need to check the
2120 // author_signature if the parent_author_signature is valid
2122 $parent_author_signature = base64_decode($parent_author_signature);
2124 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2125 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2127 logger('diaspora_like: top-level owner verification failed.');
2131 // If there's no parent_author_signature, then we've received the like
2132 // from the like creator. In that case, the person is "like"ing
2133 // our post, so he/she must be a contact of ours and his/her public key
2134 // should be in $msg['key']
2136 $author_signature = base64_decode($author_signature);
2138 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2139 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2141 logger('diaspora_like: like creator verification failed.');
2146 // Phew! Everything checks out. Now create an item.
2148 // Find the original comment author information.
2149 // We need this to make sure we display the comment author
2150 // information (name and avatar) correctly.
2151 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2154 $person = find_diaspora_person_by_handle($diaspora_handle);
2156 if(! is_array($person)) {
2157 logger('diaspora_like: unable to find author details');
2162 $uri = $diaspora_handle . ':' . $guid;
2164 $activity = ACTIVITY_LIKE;
2165 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2166 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2167 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2168 $body = $parent_item['body'];
2173 <type>$objtype</type>
2175 <id>{$parent_item['uri']}</id>
2178 <content>$body</content>
2181 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2183 // Fetch the contact id - if we know this contact
2184 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
2185 dbesc(normalise_link($person['url'])), intval($importer['uid']));
2188 $network = $r[0]['network'];
2190 $cid = $contact['id'];
2191 $network = NETWORK_DIASPORA;
2197 $arr['uid'] = $importer['uid'];
2198 $arr['guid'] = $guid;
2199 $arr['network'] = $network;
2200 $arr['contact-id'] = $cid;
2201 $arr['type'] = 'activity';
2202 $arr['wall'] = $parent_item['wall'];
2203 $arr['gravity'] = GRAVITY_LIKE;
2204 $arr['parent'] = $parent_item['id'];
2205 $arr['parent-uri'] = $parent_item['uri'];
2207 $arr['owner-name'] = $parent_item['name'];
2208 $arr['owner-link'] = $parent_item['url'];
2209 //$arr['owner-avatar'] = $parent_item['thumb'];
2210 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2212 $arr['author-name'] = $person['name'];
2213 $arr['author-link'] = $person['url'];
2214 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2216 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2217 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2218 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2219 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2220 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2222 $arr['app'] = 'Diaspora';
2224 $arr['private'] = $parent_item['private'];
2225 $arr['verb'] = $activity;
2226 $arr['object-type'] = $objtype;
2227 $arr['object'] = $obj;
2228 $arr['visible'] = 1;
2230 $arr['last-child'] = 0;
2232 $message_id = item_store($arr);
2236 // q("update item set plink = '%s' where id = %d",
2237 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2238 // dbesc($a->get_baseurl().'/display/'.$guid),
2239 // intval($message_id)
2243 // If we are the origin of the parent we store the original signature and notify our followers
2244 if($parent_item['origin']) {
2245 $author_signature_base64 = base64_encode($author_signature);
2246 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
2248 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2249 intval($message_id),
2250 dbesc($signed_data),
2251 dbesc($author_signature_base64),
2252 dbesc($diaspora_handle)
2256 proc_run('php','include/notifier.php','comment-import',$message_id);
2262 function diaspora_retraction($importer,$xml) {
2265 $guid = notags(unxmlify($xml->guid));
2266 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2267 $type = notags(unxmlify($xml->type));
2269 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2273 if($type === 'Person') {
2274 require_once('include/Contact.php');
2275 contact_remove($contact['id']);
2276 } elseif($type === 'StatusMessage') {
2277 $guid = notags(unxmlify($xml->post_guid));
2279 $r = q("SELECT * FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2281 intval($importer['uid'])
2284 if(link_compare($r[0]['author-link'],$contact['url'])) {
2285 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
2286 dbesc(datetime_convert()),
2289 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2292 } elseif($type === 'Post') {
2293 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2295 intval($importer['uid'])
2298 if(link_compare($r[0]['author-link'],$contact['url'])) {
2299 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2300 dbesc(datetime_convert()),
2303 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2312 function diaspora_signed_retraction($importer,$xml,$msg) {
2315 $guid = notags(unxmlify($xml->target_guid));
2316 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2317 $type = notags(unxmlify($xml->target_type));
2318 $sig = notags(unxmlify($xml->target_author_signature));
2320 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2322 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2324 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2329 $signed_data = $guid . ';' . $type ;
2332 /* How Diaspora performs relayable_retraction signature checking:
2334 - If an item has been sent by the item author to the top-level post owner to relay on
2335 to the rest of the contacts on the top-level post, the top-level post owner checks
2336 the author_signature, then creates a parent_author_signature before relaying the item on
2337 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2338 check only the parent_author_signature. Basically, they trust that the top-level post
2339 owner has already verified the authenticity of anything he/she sends out
2340 - In either case, the signature that get checked is the signature created by the person
2344 if($parent_author_signature) {
2346 $parent_author_signature = base64_decode($parent_author_signature);
2348 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2349 logger('diaspora_signed_retraction: top-level post owner verification failed');
2355 $sig_decode = base64_decode($sig);
2357 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2358 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2363 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2364 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2366 intval($importer['uid'])
2369 if(link_compare($r[0]['author-link'],$contact['url'])) {
2370 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2371 dbesc(datetime_convert()),
2372 dbesc(datetime_convert()),
2375 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2377 // Now check if the retraction needs to be relayed by us
2379 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2380 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2381 // The only item with `parent` and `id` as the parent id is the parent item.
2382 $p = q("SELECT `origin` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2383 intval($r[0]['parent']),
2384 intval($r[0]['parent'])
2387 if($p[0]['origin']) {
2388 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2390 dbesc($signed_data),
2392 dbesc($diaspora_handle)
2395 // the existence of parent_author_signature would have meant the parent_author or owner
2396 // is already relaying.
2397 logger('diaspora_signed_retraction: relaying relayable_retraction');
2399 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2406 logger('diaspora_signed_retraction: unknown type: ' . $type);
2412 function diaspora_profile($importer,$xml,$msg) {
2415 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2418 if($diaspora_handle != $msg['author']) {
2419 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2423 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2427 //if($contact['blocked']) {
2428 // logger('diaspora_post: Ignoring this author.');
2432 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2433 $image_url = unxmlify($xml->image_url);
2434 $birthday = unxmlify($xml->birthday);
2435 $location = diaspora2bb(unxmlify($xml->location));
2436 $about = diaspora2bb(unxmlify($xml->bio));
2437 $gender = unxmlify($xml->gender);
2438 $searchable = (unxmlify($xml->searchable) == "true");
2439 $nsfw = (unxmlify($xml->nsfw) == "true");
2440 $tags = unxmlify($xml->tag_string);
2442 $tags = explode("#", $tags);
2444 $keywords = array();
2445 foreach ($tags as $tag) {
2446 $tag = trim(strtolower($tag));
2451 $keywords = implode(", ", $keywords);
2453 $handle_parts = explode("@", $diaspora_handle);
2454 $nick = $handle_parts[0];
2457 $name = $handle_parts[0];
2460 if( preg_match("|^https?://|", $image_url) === 0) {
2461 $image_url = "http://" . $handle_parts[1] . $image_url;
2464 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2465 intval($importer['uid']),
2466 intval($contact['id'])
2468 $oldphotos = ((count($r)) ? $r : null);*/
2470 require_once('include/Photo.php');
2472 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2474 // Generic birthday. We don't know the timezone. The year is irrelevant.
2476 $birthday = str_replace('1000','1901',$birthday);
2478 if ($birthday != "")
2479 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2481 // this is to prevent multiple birthday notifications in a single year
2482 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2484 if(substr($birthday,5) === substr($contact['bd'],5))
2485 $birthday = $contact['bd'];
2487 /// @TODO Update name on item['author-name'] if the name changed. See consume_feed()
2488 /// (Not doing this currently because D* protocol is scheduled for revision soon).
2490 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%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",
2493 dbesc($diaspora_handle),
2494 dbesc(datetime_convert()),
2498 dbesc(datetime_convert()),
2504 intval($contact['id']),
2505 intval($importer['uid'])
2509 require_once('include/socgraph.php');
2510 poco_check($contact['url'], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
2511 datetime_convert(), 2, $contact['id'], $importer['uid']);
2514 update_gcontact(array("url" => $contact['url'], "network" => NETWORK_DIASPORA, "generation" => 2,
2515 "photo" => $image_url, "name" => $name, "location" => $location,
2516 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2517 "addr" => $diaspora_handle, "nick" => $nick, "keywords" => $keywords,
2518 "hide" => !$searchable, "nsfw" => $nsfw));
2522 foreach($oldphotos as $ph) {
2523 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2524 intval($importer['uid']),
2525 intval($contact['id']),
2526 dbesc($ph['resource-id'])
2536 function diaspora_share($me,$contact) {
2538 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2539 $theiraddr = $contact['addr'];
2541 $tpl = get_markup_template('diaspora_share.tpl');
2542 $msg = replace_macros($tpl, array(
2543 '$sender' => $myaddr,
2544 '$recipient' => $theiraddr
2547 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2548 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2550 return(diaspora_transmit($owner,$contact,$slap, false));
2553 function diaspora_unshare($me,$contact) {
2556 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2558 $tpl = get_markup_template('diaspora_retract.tpl');
2559 $msg = replace_macros($tpl, array(
2560 '$guid' => $me['guid'],
2561 '$type' => 'Person',
2562 '$handle' => $myaddr
2565 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2566 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2568 return(diaspora_transmit($owner,$contact,$slap, false));
2573 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2576 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2577 $theiraddr = $contact['addr'];
2581 $title = $item['title'];
2582 $body = $item['body'];
2585 // We're trying to match Diaspora's split message/photo protocol but
2586 // all the photos are displayed on D* as links and not img's - even
2587 // though we're sending pretty much precisely what they send us when
2588 // doing the same operation.
2589 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2590 // which seems to get through intact.
2592 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2594 foreach($matches as $mtch) {
2596 $detail['str'] = $mtch[0];
2597 $detail['path'] = dirname($mtch[1]) . '/';
2598 $detail['file'] = basename($mtch[1]);
2599 $detail['guid'] = $item['guid'];
2600 $detail['handle'] = $myaddr;
2601 $images[] = $detail;
2602 $body = str_replace($detail['str'],$mtch[1],$body);
2607 //if(strlen($title))
2608 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2610 // convert to markdown
2611 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2612 //$body = bb2diaspora($body);
2616 $body = "## ".html_entity_decode($title)."\n\n".$body;
2618 if($item['attach']) {
2619 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2621 $body .= "\n" . t('Attachments:') . "\n";
2622 foreach($matches as $mtch) {
2623 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2629 $public = (($item['private']) ? 'false' : 'true');
2631 require_once('include/datetime.php');
2632 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2634 // Detect a share element and do a reshare
2635 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2636 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2637 $tpl = get_markup_template('diaspora_reshare.tpl');
2638 $msg = replace_macros($tpl, array(
2639 '$root_handle' => xmlify($ret['root_handle']),
2640 '$root_guid' => $ret['root_guid'],
2641 '$guid' => $item['guid'],
2642 '$handle' => xmlify($myaddr),
2643 '$public' => $public,
2644 '$created' => $created,
2645 '$provider' => $item["app"]
2648 $tpl = get_markup_template('diaspora_post.tpl');
2649 $msg = replace_macros($tpl, array(
2651 '$guid' => $item['guid'],
2652 '$handle' => xmlify($myaddr),
2653 '$public' => $public,
2654 '$created' => $created,
2655 '$provider' => $item["app"]
2659 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2660 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2662 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2663 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2665 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']);
2667 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2669 if(count($images)) {
2670 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2673 return $return_code;
2676 function diaspora_is_reshare($body) {
2677 $body = trim($body);
2679 // Skip if it isn't a pure repeated messages
2680 // Does it start with a share?
2681 if (strpos($body, "[share") > 0)
2684 // Does it end with a share?
2685 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2688 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2689 // Skip if there is no shared message in there
2690 if ($body == $attributes)
2694 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2695 if ($matches[1] != "")
2696 $guid = $matches[1];
2698 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2699 if ($matches[1] != "")
2700 $guid = $matches[1];
2703 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2704 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2707 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2708 $ret["root_guid"] = $guid;
2714 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2715 if ($matches[1] != "")
2716 $profile = $matches[1];
2718 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2719 if ($matches[1] != "")
2720 $profile = $matches[1];
2724 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2725 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2729 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2730 if ($matches[1] != "")
2731 $link = $matches[1];
2733 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2734 if ($matches[1] != "")
2735 $link = $matches[1];
2737 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2738 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2744 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2746 if(! count($images))
2748 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2750 $tpl = get_markup_template('diaspora_photo.tpl');
2751 foreach($images as $image) {
2752 if(! stristr($image['path'],$mysite))
2754 $resource = str_replace('.jpg','',$image['file']);
2755 $resource = substr($resource,0,strpos($resource,'-'));
2757 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2759 intval($owner['uid'])
2763 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2764 $msg = replace_macros($tpl,array(
2765 '$path' => xmlify($image['path']),
2766 '$filename' => xmlify($image['file']),
2767 '$msg_guid' => xmlify($image['guid']),
2768 '$guid' => xmlify($r[0]['guid']),
2769 '$handle' => xmlify($image['handle']),
2770 '$public' => xmlify($public),
2771 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2775 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2776 logger('send guid '.$r[0]['guid'], LOGGER_DEBUG);
2778 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2779 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2781 diaspora_transmit($owner,$contact,$slap,$public_batch,false,$r[0]['guid']);
2786 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2789 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2790 // $theiraddr = $contact['addr'];
2792 // Diaspora doesn't support threaded comments, but some
2793 // versions of Diaspora (i.e. Diaspora-pistos) support
2794 // likes on comments
2795 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2796 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2797 dbesc($item['thr-parent'])
2801 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2802 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2803 // The only item with `parent` and `id` as the parent id is the parent item.
2804 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2805 intval($item['parent']),
2806 intval($item['parent'])
2814 if($item['verb'] === ACTIVITY_LIKE) {
2815 $tpl = get_markup_template('diaspora_like.tpl');
2817 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2818 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2819 // $positive = (($item['deleted']) ? 'false' : 'true');
2822 if(($item['deleted']))
2823 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2826 $tpl = get_markup_template('diaspora_comment.tpl');
2830 $text = html_entity_decode(bb2diaspora($item['body']));
2835 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2837 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2839 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2841 $msg = replace_macros($tpl,array(
2842 '$guid' => xmlify($item['guid']),
2843 '$parent_guid' => xmlify($parent['guid']),
2844 '$target_type' =>xmlify($target_type),
2845 '$authorsig' => xmlify($authorsig),
2846 '$body' => xmlify($text),
2847 '$positive' => xmlify($positive),
2848 '$handle' => xmlify($myaddr)
2851 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2852 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2854 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2855 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2857 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2861 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2865 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2866 // $theiraddr = $contact['addr'];
2868 // Diaspora doesn't support threaded comments, but some
2869 // versions of Diaspora (i.e. Diaspora-pistos) support
2870 // likes on comments
2871 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2872 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2873 dbesc($item['thr-parent'])
2877 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2878 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2879 // The only item with `parent` and `id` as the parent id is the parent item.
2880 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2881 intval($item['parent']),
2882 intval($item['parent'])
2891 $relay_retract = false;
2892 $sql_sign_id = 'iid';
2893 if( $item['deleted']) {
2894 $relay_retract = true;
2896 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2898 $sql_sign_id = 'retract_iid';
2899 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2901 elseif($item['verb'] === ACTIVITY_LIKE) {
2904 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2905 // $positive = (($item['deleted']) ? 'false' : 'true');
2908 $tpl = get_markup_template('diaspora_like_relay.tpl');
2910 else { // item is a comment
2911 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2915 // fetch the original signature if the relayable was created by a Diaspora
2916 // or DFRN user. Relayables for other networks are not supported.
2918 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE " . $sql_sign_id . " = %d LIMIT 1",
2923 $signed_text = $orig_sign['signed_text'];
2924 $authorsig = $orig_sign['signature'];
2925 $handle = $orig_sign['signer'];
2927 // Split the signed text
2928 $signed_parts = explode(";", $signed_text);
2930 // Remove the parent guid
2931 array_shift($signed_parts);
2933 // Remove the comment guid
2934 array_shift($signed_parts);
2936 // Remove the handle
2937 array_pop($signed_parts);
2939 // Glue the parts together
2940 $text = implode(";", $signed_parts);
2943 // This part is meant for cases where we don't have the signatur. (Which shouldn't happen with posts from Diaspora and Friendica)
2944 // This means that the comment won't be accepted by newer Diaspora servers
2946 $body = $item['body'];
2947 $text = html_entity_decode(bb2diaspora($body));
2949 $handle = diaspora_handle_from_contact($item['contact-id']);
2954 $signed_text = $item['guid'] . ';' . $target_type;
2956 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2958 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2960 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2963 // Sign the relayable with the top-level owner's signature
2964 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2966 $msg = replace_macros($tpl,array(
2967 '$guid' => xmlify($item['guid']),
2968 '$parent_guid' => xmlify($parent['guid']),
2969 '$target_type' =>xmlify($target_type),
2970 '$authorsig' => xmlify($authorsig),
2971 '$parentsig' => xmlify($parentauthorsig),
2972 '$body' => xmlify($text),
2973 '$positive' => xmlify($positive),
2974 '$handle' => xmlify($handle)
2977 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DEBUG);
2978 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2980 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2981 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2983 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2989 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2992 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2994 // Check whether the retraction is for a top-level post or whether it's a relayable
2995 if( $item['uri'] !== $item['parent-uri'] ) {
2997 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2998 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
3002 $tpl = get_markup_template('diaspora_signed_retract.tpl');
3003 $target_type = 'StatusMessage';
3006 $signed_text = $item['guid'] . ';' . $target_type;
3008 $msg = replace_macros($tpl, array(
3009 '$guid' => xmlify($item['guid']),
3010 '$type' => xmlify($target_type),
3011 '$handle' => xmlify($myaddr),
3012 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
3015 logger('send guid '.$item['guid'], LOGGER_DEBUG);
3017 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
3018 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
3020 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
3023 function diaspora_send_mail($item,$owner,$contact) {
3026 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
3028 $r = q("select * from conv where id = %d and uid = %d limit 1",
3029 intval($item['convid']),
3030 intval($item['uid'])
3034 logger('diaspora_send_mail: conversation not found.');
3040 'guid' => xmlify($cnv['guid']),
3041 'subject' => xmlify($cnv['subject']),
3042 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
3043 'diaspora_handle' => xmlify($cnv['creator']),
3044 'participant_handles' => xmlify($cnv['recips'])
3047 $body = bb2diaspora($item['body']);
3048 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
3050 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
3051 . $created . ';' . $myaddr . ';' . $cnv['guid'];
3053 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
3056 'guid' => xmlify($item['guid']),
3057 'parent_guid' => xmlify($cnv['guid']),
3058 'parent_author_signature' => xmlify($sig),
3059 'author_signature' => xmlify($sig),
3060 'text' => xmlify($body),
3061 'created_at' => xmlify($created),
3062 'diaspora_handle' => xmlify($myaddr),
3063 'conversation_guid' => xmlify($cnv['guid'])
3066 if($item['reply']) {
3067 $tpl = get_markup_template('diaspora_message.tpl');
3068 $xmsg = replace_macros($tpl, array('$msg' => $msg));
3071 $conv['messages'] = array($msg);
3072 $tpl = get_markup_template('diaspora_conversation.tpl');
3073 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3076 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3077 logger('send guid '.$item['guid'], LOGGER_DEBUG);
3079 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3080 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3082 return(diaspora_transmit($owner,$contact,$slap,false,false,$item['guid']));
3087 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false,$guid = "") {
3089 $enabled = intval(get_config('system','diaspora_enabled'));
3095 $logid = random_string(4);
3096 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3098 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3102 logger('diaspora_transmit: '.$logid.'-'.$guid.' '.$dest_url);
3104 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3108 if (!intval(get_config('system','diaspora_test'))) {
3109 post_url($dest_url . '/', $slap);
3110 $return_code = $a->get_curl_code();
3112 logger('diaspora_transmit: test_mode');
3117 logger('diaspora_transmit: '.$logid.'-'.$guid.' returns: '.$return_code);
3119 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3120 logger('diaspora_transmit: queue message');
3122 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3123 intval($contact['id']),
3124 dbesc(NETWORK_DIASPORA),
3126 intval($public_batch)
3129 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3132 // queue message for redelivery
3133 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3138 return(($return_code) ? $return_code : (-1));
3141 function diaspora_fetch_relay() {
3143 $serverdata = get_config("system", "relay_server");
3144 if ($serverdata == "")
3149 $servers = explode(",", $serverdata);
3151 foreach($servers AS $server) {
3152 $server = trim($server);
3153 $batch = $server."/receive/public";
3155 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3158 $addr = "relay@".str_replace("http://", "", normalise_link($server));
3160 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
3161 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
3166 dbesc(normalise_link($server)),
3168 dbesc(NETWORK_DIASPORA),
3169 intval(CONTACT_IS_FOLLOWER),
3170 dbesc(datetime_convert()),
3171 dbesc(datetime_convert()),
3172 dbesc(datetime_convert())
3175 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3177 $relay[] = $relais[0];
3179 $relay[] = $relais[0];