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_post($importer,$xml,$msg) {
832 $guid = notags(unxmlify($xml->guid));
833 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
835 if($diaspora_handle != $msg['author']) {
836 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
840 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
842 logger('diaspora_post: A Contact for handle '.$diaspora_handle.' and user '.$importer['uid'].' was not found');
846 if(! diaspora_post_allow($importer,$contact, false)) {
847 logger('diaspora_post: Ignoring this author.');
851 $message_id = $diaspora_handle . ':' . $guid;
852 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
853 intval($importer['uid']),
857 logger('diaspora_post: message exists: ' . $guid);
861 $created = unxmlify($xml->created_at);
862 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
864 $body = diaspora2bb($xml->raw_message);
868 $datarray["object"] = json_encode($xml);
870 if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
871 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
873 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
874 // Add OEmbed and other information to the body
875 if (!diaspora_is_redmatrix($contact['url']))
876 $body = add_page_info_to_body($body, false, true);
881 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
883 foreach($matches as $mtch) {
884 if(strlen($str_tags))
886 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
890 $plink = diaspora_plink($diaspora_handle, $guid);
892 $datarray['uid'] = $importer['uid'];
893 $datarray['contact-id'] = $contact['id'];
894 $datarray['wall'] = 0;
895 $datarray['network'] = NETWORK_DIASPORA;
896 $datarray['verb'] = ACTIVITY_POST;
897 $datarray['guid'] = $guid;
898 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
899 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
900 $datarray['private'] = $private;
901 $datarray['parent'] = 0;
902 $datarray['plink'] = $plink;
903 $datarray['owner-name'] = $contact['name'];
904 $datarray['owner-link'] = $contact['url'];
905 //$datarray['owner-avatar'] = $contact['thumb'];
906 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
907 $datarray['author-name'] = $contact['name'];
908 $datarray['author-link'] = $contact['url'];
909 $datarray['author-avatar'] = $contact['thumb'];
910 $datarray['body'] = $body;
911 $datarray['tag'] = $str_tags;
912 if ($xml->provider_display_name)
913 $datarray["app"] = unxmlify($xml->provider_display_name);
915 $datarray['app'] = 'Diaspora';
917 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
919 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
921 DiasporaFetchGuid($datarray);
922 $message_id = item_store($datarray);
924 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
930 function DiasporaFetchGuid($item) {
931 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
932 function ($match) use ($item){
933 return(DiasporaFetchGuidSub($match, $item));
937 function DiasporaFetchGuidSub($match, $item) {
940 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
941 diaspora_store_by_guid($match[1], $item["owner-link"]);
944 function diaspora_store_by_guid($guid, $server, $uid = 0) {
945 require_once("include/Contact.php");
947 $serverparts = parse_url($server);
948 $server = $serverparts["scheme"]."://".$serverparts["host"];
950 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
952 $item = diaspora_fetch_message($guid, $server);
957 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
959 $body = $item["body"];
960 $str_tags = $item["tag"];
962 $created = $item["created"];
963 $author = $item["author"];
964 $guid = $item["guid"];
965 $private = $item["private"];
966 $object = $item["object"];
967 $objecttype = $item["object-type"];
969 $message_id = $author.':'.$guid;
970 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
977 $person = find_diaspora_person_by_handle($author);
979 $contact_id = get_contact($person['url'], $uid);
981 $contacts = q("SELECT * FROM `contact` WHERE `id` = %d", intval($contact_id));
982 $importers = q("SELECT * FROM `user` WHERE `uid` = %d", intval($uid));
984 if ($contacts AND $importers)
985 if(!diaspora_post_allow($importers[0],$contacts[0], false)) {
986 logger('Ignoring author '.$person['url'].' for uid '.$uid);
989 logger('Author '.$person['url'].' is allowed for uid '.$uid);
992 $datarray['uid'] = $uid;
993 $datarray['contact-id'] = $contact_id;
994 $datarray['wall'] = 0;
995 $datarray['network'] = NETWORK_DIASPORA;
996 $datarray['guid'] = $guid;
997 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
998 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
999 $datarray['private'] = $private;
1000 $datarray['parent'] = 0;
1001 $datarray['plink'] = diaspora_plink($author, $guid);
1002 $datarray['author-name'] = $person['name'];
1003 $datarray['author-link'] = $person['url'];
1004 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1005 $datarray['owner-name'] = $datarray['author-name'];
1006 $datarray['owner-link'] = $datarray['author-link'];
1007 $datarray['owner-avatar'] = $datarray['author-avatar'];
1008 $datarray['body'] = $body;
1009 $datarray['tag'] = $str_tags;
1010 $datarray['app'] = $app;
1011 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1012 $datarray['object'] = $object;
1013 $datarray['object-type'] = $objecttype;
1015 if ($datarray['contact-id'] == 0)
1018 DiasporaFetchGuid($datarray);
1019 $message_id = item_store($datarray);
1022 /// Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
1027 function diaspora_fetch_message($guid, $server, $level = 0) {
1034 // This will not work if the server is not a Diaspora server
1035 $source_url = $server.'/p/'.$guid.'.xml';
1036 $x = fetch_url($source_url);
1040 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1041 $source_xml = parse_xml_string($x,false);
1044 $item["app"] = 'Diaspora';
1045 $item["guid"] = $guid;
1048 if ($source_xml->post->status_message->created_at)
1049 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1051 if ($source_xml->post->status_message->provider_display_name)
1052 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1054 if ($source_xml->post->status_message->diaspora_handle)
1055 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1057 if ($source_xml->post->status_message->guid)
1058 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1060 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1061 $item["object"] = json_encode($source_xml->post);
1063 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1064 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1065 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1066 $body = scale_external_images($body,false);
1067 } elseif($source_xml->post->asphoto->image_url) {
1068 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1069 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1070 $body = scale_external_images($body);
1071 } elseif($source_xml->post->status_message) {
1072 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1074 // Checking for embedded pictures
1075 if($source_xml->post->status_message->photo->remote_photo_path AND
1076 $source_xml->post->status_message->photo->remote_photo_name) {
1078 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1080 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1081 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1083 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1085 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1087 $item["object-type"] = ACTIVITY_OBJ_NOTE;
1089 $body = scale_external_images($body);
1091 // Add OEmbed and other information to the body
1092 /// @TODO It could be a repeated redmatrix item
1093 /// Then we shouldn't add further data to it
1094 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1095 $body = add_page_info_to_body($body, false, true);
1097 } elseif($source_xml->post->reshare) {
1098 // Reshare of a reshare
1099 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1101 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1102 logger('no content found: '.print_r($source_xml,true));
1106 if (trim($body) == "")
1110 $item["body"] = $body;
1115 function diaspora_reshare($importer,$xml,$msg) {
1117 logger('diaspora_reshare: init: ' . print_r($xml,true));
1120 $guid = notags(unxmlify($xml->guid));
1121 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1124 if($diaspora_handle != $msg['author']) {
1125 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1129 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1133 if(! diaspora_post_allow($importer,$contact, false)) {
1134 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1138 $message_id = $diaspora_handle . ':' . $guid;
1139 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1140 intval($importer['uid']),
1144 logger('diaspora_reshare: message exists: ' . $guid);
1148 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1149 $orig_guid = notags(unxmlify($xml->root_guid));
1150 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1152 $create_original_post = false;
1154 // Do we already have this item?
1155 $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",
1157 dbesc(NETWORK_DIASPORA)
1160 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1162 // Maybe it is already a reshared item?
1163 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1164 require_once('include/api.php');
1165 if (api_share_as_retweet($r[0]))
1168 $body = $r[0]["body"];
1169 $str_tags = $r[0]["tag"];
1170 $app = $r[0]["app"];
1171 $orig_created = $r[0]["created"];
1172 $orig_plink = $r[0]["plink"];
1173 $orig_uri = $r[0]["uri"];
1174 $object = $r[0]["object"];
1175 $objecttype = $r[0]["object-type"];
1184 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1185 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1186 $item = diaspora_fetch_message($orig_guid, $server);
1189 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1190 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1191 $item = diaspora_fetch_message($orig_guid, $server);
1194 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1195 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1196 $item = diaspora_fetch_message($orig_guid, $server);
1199 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1200 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1201 $item = diaspora_fetch_message($orig_guid, $server);
1205 $body = $item["body"];
1206 $str_tags = $item["tag"];
1207 $app = $item["app"];
1208 $orig_created = $item["created"];
1209 $orig_author = $item["author"];
1210 $orig_guid = $item["guid"];
1211 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1212 $orig_uri = $orig_author.':'.$orig_guid;
1213 $create_original_post = ($body != "");
1214 $object = $item["object"];
1215 $objecttype = $item["object-type"];
1219 $plink = diaspora_plink($diaspora_handle, $guid);
1221 $person = find_diaspora_person_by_handle($orig_author);
1223 $created = unxmlify($xml->created_at);
1224 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1226 $datarray = array();
1228 $datarray['uid'] = $importer['uid'];
1229 $datarray['contact-id'] = $contact['id'];
1230 $datarray['wall'] = 0;
1231 $datarray['network'] = NETWORK_DIASPORA;
1232 $datarray['guid'] = $guid;
1233 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1234 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1235 $datarray['private'] = $private;
1236 $datarray['parent'] = 0;
1237 $datarray['plink'] = $plink;
1238 $datarray['owner-name'] = $contact['name'];
1239 $datarray['owner-link'] = $contact['url'];
1240 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1241 if (!intval(get_config('system','wall-to-wall_share'))) {
1242 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1244 $datarray['author-name'] = $contact['name'];
1245 $datarray['author-link'] = $contact['url'];
1246 $datarray['author-avatar'] = $contact['thumb'];
1247 $datarray['body'] = $prefix.$body."[/share]";
1249 // Let reshared messages look like wall-to-wall posts
1250 $datarray['author-name'] = $person['name'];
1251 $datarray['author-link'] = $person['url'];
1252 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1253 $datarray['body'] = $body;
1256 $datarray["object"] = json_encode($xml);
1257 $datarray['object-type'] = $objecttype;
1259 $datarray['tag'] = $str_tags;
1260 $datarray['app'] = $app;
1262 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1263 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1265 // Store the original item of a reshare
1266 if ($create_original_post) {
1267 require_once("include/Contact.php");
1269 $datarray2 = $datarray;
1271 $datarray2['uid'] = 0;
1272 $datarray2['contact-id'] = get_contact($person['url'], 0);
1273 $datarray2['guid'] = $orig_guid;
1274 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1275 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1276 $datarray2['parent'] = 0;
1277 $datarray2['plink'] = $orig_plink;
1279 $datarray2['author-name'] = $person['name'];
1280 $datarray2['author-link'] = $person['url'];
1281 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1282 $datarray2['owner-name'] = $datarray2['author-name'];
1283 $datarray2['owner-link'] = $datarray2['author-link'];
1284 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1285 $datarray2['body'] = $body;
1286 $datarray2["object"] = $object;
1288 DiasporaFetchGuid($datarray2);
1289 $message_id = item_store($datarray2);
1291 logger("Store original item ".$orig_guid." under message id ".$message_id);
1294 DiasporaFetchGuid($datarray);
1295 $message_id = item_store($datarray);
1302 function diaspora_asphoto($importer,$xml,$msg) {
1303 logger('diaspora_asphoto called');
1306 $guid = notags(unxmlify($xml->guid));
1307 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1309 if($diaspora_handle != $msg['author']) {
1310 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1314 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1318 if(! diaspora_post_allow($importer,$contact, false)) {
1319 logger('diaspora_asphoto: Ignoring this author.');
1323 $message_id = $diaspora_handle . ':' . $guid;
1324 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1325 intval($importer['uid']),
1329 logger('diaspora_asphoto: message exists: ' . $guid);
1333 $created = unxmlify($xml->created_at);
1334 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1336 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1337 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1338 $body = scale_external_images($body,false);
1340 elseif($xml->image_url) {
1341 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1342 $body = scale_external_images($body);
1345 logger('diaspora_asphoto: no photo url found.');
1349 $plink = diaspora_plink($diaspora_handle, $guid);
1351 $datarray = array();
1353 $datarray['uid'] = $importer['uid'];
1354 $datarray['contact-id'] = $contact['id'];
1355 $datarray['wall'] = 0;
1356 $datarray['network'] = NETWORK_DIASPORA;
1357 $datarray['guid'] = $guid;
1358 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1359 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1360 $datarray['private'] = $private;
1361 $datarray['parent'] = 0;
1362 $datarray['plink'] = $plink;
1363 $datarray['owner-name'] = $contact['name'];
1364 $datarray['owner-link'] = $contact['url'];
1365 //$datarray['owner-avatar'] = $contact['thumb'];
1366 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1367 $datarray['author-name'] = $contact['name'];
1368 $datarray['author-link'] = $contact['url'];
1369 $datarray['author-avatar'] = $contact['thumb'];
1370 $datarray['body'] = $body;
1371 $datarray["object"] = json_encode($xml);
1372 $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1374 $datarray['app'] = 'Diaspora/Cubbi.es';
1376 DiasporaFetchGuid($datarray);
1377 $message_id = item_store($datarray);
1380 // q("update item set plink = '%s' where id = %d",
1381 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1382 // intval($message_id)
1390 function diaspora_comment($importer,$xml,$msg) {
1393 $guid = notags(unxmlify($xml->guid));
1394 $parent_guid = notags(unxmlify($xml->parent_guid));
1395 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1396 $target_type = notags(unxmlify($xml->target_type));
1397 $text = unxmlify($xml->text);
1398 $author_signature = notags(unxmlify($xml->author_signature));
1400 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1402 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1404 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1408 if(! diaspora_post_allow($importer,$contact, true)) {
1409 logger('diaspora_comment: Ignoring this author.');
1413 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1414 intval($importer['uid']),
1418 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1422 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1423 intval($importer['uid']),
1428 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1431 $person = find_diaspora_person_by_handle($diaspora_handle);
1432 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1436 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1438 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1439 intval($importer['uid']),
1446 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1449 $parent_item = $r[0];
1452 /* How Diaspora performs comment signature checking:
1454 - If an item has been sent by the comment author to the top-level post owner to relay on
1455 to the rest of the contacts on the top-level post, the top-level post owner should check
1456 the author_signature, then create a parent_author_signature before relaying the comment on
1457 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1458 check only the parent_author_signature. Basically, they trust that the top-level post
1459 owner has already verified the authenticity of anything he/she sends out
1460 - In either case, the signature that get checked is the signature created by the person
1464 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1467 if($parent_author_signature) {
1468 // If a parent_author_signature exists, then we've received the comment
1469 // relayed from the top-level post owner. There's no need to check the
1470 // author_signature if the parent_author_signature is valid
1472 $parent_author_signature = base64_decode($parent_author_signature);
1474 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1475 logger('diaspora_comment: top-level owner verification failed.');
1480 // If there's no parent_author_signature, then we've received the comment
1481 // from the comment creator. In that case, the person is commenting on
1482 // our post, so he/she must be a contact of ours and his/her public key
1483 // should be in $msg['key']
1485 $author_signature = base64_decode($author_signature);
1487 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1488 logger('diaspora_comment: comment author verification failed.');
1493 // Phew! Everything checks out. Now create an item.
1495 // Find the original comment author information.
1496 // We need this to make sure we display the comment author
1497 // information (name and avatar) correctly.
1498 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1501 $person = find_diaspora_person_by_handle($diaspora_handle);
1503 if(! is_array($person)) {
1504 logger('diaspora_comment: unable to find author details');
1509 // Fetch the contact id - if we know this contact
1510 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1511 dbesc(normalise_link($person['url'])), intval($importer['uid']));
1514 $network = $r[0]['network'];
1516 $cid = $contact['id'];
1517 $network = NETWORK_DIASPORA;
1520 $body = diaspora2bb($text);
1521 $message_id = $diaspora_handle . ':' . $guid;
1523 $datarray = array();
1525 $datarray['uid'] = $importer['uid'];
1526 $datarray['contact-id'] = $cid;
1527 $datarray['type'] = 'remote-comment';
1528 $datarray['wall'] = $parent_item['wall'];
1529 $datarray['network'] = $network;
1530 $datarray['verb'] = ACTIVITY_POST;
1531 $datarray['gravity'] = GRAVITY_COMMENT;
1532 $datarray['guid'] = $guid;
1533 $datarray['uri'] = $message_id;
1534 $datarray['parent-uri'] = $parent_item['uri'];
1536 // No timestamps for comments? OK, we'll the use current time.
1537 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1538 $datarray['private'] = $parent_item['private'];
1540 $datarray['owner-name'] = $parent_item['owner-name'];
1541 $datarray['owner-link'] = $parent_item['owner-link'];
1542 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1544 $datarray['author-name'] = $person['name'];
1545 $datarray['author-link'] = $person['url'];
1546 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1547 $datarray['body'] = $body;
1548 $datarray["object"] = json_encode($xml);
1549 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1551 // We can't be certain what the original app is if the message is relayed.
1552 if(($parent_item['origin']) && (! $parent_author_signature))
1553 $datarray['app'] = 'Diaspora';
1555 DiasporaFetchGuid($datarray);
1556 $message_id = item_store($datarray);
1558 $datarray['id'] = $message_id;
1561 //q("update item set plink = '%s' where id = %d",
1562 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1563 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1564 // intval($message_id)
1568 if(($parent_item['origin']) && (! $parent_author_signature)) {
1569 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1570 intval($message_id),
1571 dbesc($signed_data),
1572 dbesc(base64_encode($author_signature)),
1573 dbesc($diaspora_handle)
1576 // if the message isn't already being relayed, notify others
1577 // the existence of parent_author_signature means the parent_author or owner
1578 // is already relaying.
1580 proc_run('php','include/notifier.php','comment-import',$message_id);
1583 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1584 dbesc($parent_item['uri']),
1585 intval($importer['uid'])
1588 if(count($myconv)) {
1589 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1591 foreach($myconv as $conv) {
1593 // now if we find a match, it means we're in this conversation
1595 if(! link_compare($conv['author-link'],$importer_url))
1598 require_once('include/enotify.php');
1600 $conv_parent = $conv['parent'];
1603 'type' => NOTIFY_COMMENT,
1604 'notify_flags' => $importer['notify-flags'],
1605 'language' => $importer['language'],
1606 'to_name' => $importer['username'],
1607 'to_email' => $importer['email'],
1608 'uid' => $importer['uid'],
1609 'item' => $datarray,
1610 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1611 'source_name' => $datarray['author-name'],
1612 'source_link' => $datarray['author-link'],
1613 'source_photo' => $datarray['author-avatar'],
1614 'verb' => ACTIVITY_POST,
1616 'parent' => $conv_parent,
1617 'parent_uri' => $parent_uri
1620 // only send one notification
1630 function diaspora_conversation($importer,$xml,$msg) {
1634 $guid = notags(unxmlify($xml->guid));
1635 $subject = notags(unxmlify($xml->subject));
1636 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1637 $participant_handles = notags(unxmlify($xml->participant_handles));
1638 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1640 $parent_uri = $diaspora_handle . ':' . $guid;
1642 $messages = $xml->message;
1644 if(! count($messages)) {
1645 logger('diaspora_conversation: empty conversation');
1649 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1651 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1655 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1656 logger('diaspora_conversation: Ignoring this author.');
1660 $conversation = null;
1662 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1663 intval($importer['uid']),
1667 $conversation = $c[0];
1669 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1670 intval($importer['uid']),
1672 dbesc($diaspora_handle),
1673 dbesc(datetime_convert('UTC','UTC',$created_at)),
1674 dbesc(datetime_convert()),
1676 dbesc($participant_handles)
1679 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1680 intval($importer['uid']),
1684 $conversation = $c[0];
1686 if(! $conversation) {
1687 logger('diaspora_conversation: unable to create conversation.');
1691 foreach($messages as $mesg) {
1695 $msg_guid = notags(unxmlify($mesg->guid));
1696 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1697 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1698 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1699 $msg_text = unxmlify($mesg->text);
1700 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1701 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1702 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1703 if($msg_conversation_guid != $guid) {
1704 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1708 $body = diaspora2bb($msg_text);
1709 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1711 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1713 $author_signature = base64_decode($msg_author_signature);
1715 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1720 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1722 if(is_array($person) && x($person,'pubkey'))
1723 $key = $person['pubkey'];
1725 logger('diaspora_conversation: unable to find author details');
1730 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1731 logger('diaspora_conversation: verification failed.');
1735 if($msg_parent_author_signature) {
1736 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1738 $parent_author_signature = base64_decode($msg_parent_author_signature);
1742 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1743 logger('diaspora_conversation: owner verification failed.');
1748 $r = q("select id from mail where `uri` = '%s' limit 1",
1752 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1756 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')",
1757 intval($importer['uid']),
1759 intval($conversation['id']),
1760 dbesc($person['name']),
1761 dbesc($person['photo']),
1762 dbesc($person['url']),
1763 intval($contact['id']),
1770 dbesc($msg_created_at)
1773 q("update conv set updated = '%s' where id = %d",
1774 dbesc(datetime_convert()),
1775 intval($conversation['id'])
1778 require_once('include/enotify.php');
1780 'type' => NOTIFY_MAIL,
1781 'notify_flags' => $importer['notify-flags'],
1782 'language' => $importer['language'],
1783 'to_name' => $importer['username'],
1784 'to_email' => $importer['email'],
1785 'uid' =>$importer['uid'],
1786 'item' => array('subject' => $subject, 'body' => $body),
1787 'source_name' => $person['name'],
1788 'source_link' => $person['url'],
1789 'source_photo' => $person['thumb'],
1790 'verb' => ACTIVITY_POST,
1798 function diaspora_message($importer,$xml,$msg) {
1802 $msg_guid = notags(unxmlify($xml->guid));
1803 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1804 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1805 $msg_author_signature = notags(unxmlify($xml->author_signature));
1806 $msg_text = unxmlify($xml->text);
1807 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1808 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1809 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1811 $parent_uri = $msg_diaspora_handle . ':' . $msg_parent_guid;
1813 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1815 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1819 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1820 logger('diaspora_message: Ignoring this author.');
1824 $conversation = null;
1826 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1827 intval($importer['uid']),
1828 dbesc($msg_conversation_guid)
1831 $conversation = $c[0];
1833 logger('diaspora_message: conversation not available.');
1839 $body = diaspora2bb($msg_text);
1840 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1842 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1845 $author_signature = base64_decode($msg_author_signature);
1847 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1848 if(is_array($person) && x($person,'pubkey'))
1849 $key = $person['pubkey'];
1851 logger('diaspora_message: unable to find author details');
1855 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1856 logger('diaspora_message: verification failed.');
1860 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1862 intval($importer['uid'])
1865 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1869 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')",
1870 intval($importer['uid']),
1872 intval($conversation['id']),
1873 dbesc($person['name']),
1874 dbesc($person['photo']),
1875 dbesc($person['url']),
1876 intval($contact['id']),
1877 dbesc($conversation['subject']),
1883 dbesc($msg_created_at)
1886 q("update conv set updated = '%s' where id = %d",
1887 dbesc(datetime_convert()),
1888 intval($conversation['id'])
1894 function diaspora_participation($importer,$xml) {
1895 logger("Unsupported message type 'participation' ".print_r($xml, true));
1898 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1902 logger('diaspora_photo: init',LOGGER_DEBUG);
1904 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1906 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1908 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1910 $guid = notags(unxmlify($xml->guid));
1912 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1914 $public = notags(unxmlify($xml->public));
1916 $created_at = notags(unxmlify($xml_created_at));
1918 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1920 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1922 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1926 if(! diaspora_post_allow($importer,$contact, false)) {
1927 logger('diaspora_photo: Ignoring this author.');
1931 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1932 intval($importer['uid']),
1933 dbesc($status_message_guid)
1936 /* deactivated by now since it can lead to multiplicated pictures in posts.
1938 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1941 $person = find_diaspora_person_by_handle($diaspora_handle);
1942 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1946 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1948 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1949 intval($importer['uid']),
1950 dbesc($status_message_guid)
1957 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1958 intval($importer['uid']),
1959 dbesc(serialize($msg)),
1960 intval($attempt + 1)
1964 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1968 $parent_item = $r[0];
1970 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1972 $link_text = scale_external_images($link_text, true,
1973 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1975 if(strpos($parent_item['body'],$link_text) === false) {
1976 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1977 dbesc($link_text . $parent_item['body']),
1978 intval($parent_item['id']),
1979 intval($parent_item['uid'])
1981 update_thread($parent_item['id']);
1990 function diaspora_like($importer,$xml,$msg) {
1993 $guid = notags(unxmlify($xml->guid));
1994 $parent_guid = notags(unxmlify($xml->parent_guid));
1995 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1996 $target_type = notags(unxmlify($xml->target_type));
1997 $positive = notags(unxmlify($xml->positive));
1998 $author_signature = notags(unxmlify($xml->author_signature));
2000 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2002 // likes on comments not supported here and likes on photos not supported by Diaspora
2004 // if($target_type !== 'Post')
2007 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
2009 logger('diaspora_like: cannot find contact: ' . $msg['author']);
2013 if(! diaspora_post_allow($importer,$contact, false)) {
2014 logger('diaspora_like: Ignoring this author.');
2018 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2019 intval($importer['uid']),
2024 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
2027 $person = find_diaspora_person_by_handle($diaspora_handle);
2028 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
2032 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
2034 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2035 intval($importer['uid']),
2042 logger('diaspora_like: parent item not found: ' . $guid);
2046 $parent_item = $r[0];
2048 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2049 intval($importer['uid']),
2053 if($positive === 'true') {
2054 logger('diaspora_like: duplicate like: ' . $guid);
2057 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2058 // It looks like "RelayableRetractions" are used for "unlike" instead
2059 if($positive === 'false') {
2060 logger('diaspora_like: received a like with positive set to "false"...ignoring');
2061 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2062 intval($r[0]['id']),
2063 intval($importer['uid'])
2065 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2066 // send notification via proc_run()
2070 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2071 // It looks like "RelayableRetractions" are used for "unlike" instead
2072 if($positive === 'false') {
2073 logger('diaspora_like: received a like with positive set to "false"');
2074 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2079 /* How Diaspora performs "like" signature checking:
2081 - If an item has been sent by the like author to the top-level post owner to relay on
2082 to the rest of the contacts on the top-level post, the top-level post owner should check
2083 the author_signature, then create a parent_author_signature before relaying the like on
2084 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2085 check only the parent_author_signature. Basically, they trust that the top-level post
2086 owner has already verified the authenticity of anything he/she sends out
2087 - In either case, the signature that get checked is the signature created by the person
2091 // Diaspora has changed the way they are signing the likes.
2092 // Just to make sure that we don't miss any likes we will check the old and the current way.
2093 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2095 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2099 if ($parent_author_signature) {
2100 // If a parent_author_signature exists, then we've received the like
2101 // relayed from the top-level post owner. There's no need to check the
2102 // author_signature if the parent_author_signature is valid
2104 $parent_author_signature = base64_decode($parent_author_signature);
2106 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2107 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2109 logger('diaspora_like: top-level owner verification failed.');
2113 // If there's no parent_author_signature, then we've received the like
2114 // from the like creator. In that case, the person is "like"ing
2115 // our post, so he/she must be a contact of ours and his/her public key
2116 // should be in $msg['key']
2118 $author_signature = base64_decode($author_signature);
2120 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2121 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2123 logger('diaspora_like: like creator verification failed.');
2128 // Phew! Everything checks out. Now create an item.
2130 // Find the original comment author information.
2131 // We need this to make sure we display the comment author
2132 // information (name and avatar) correctly.
2133 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2136 $person = find_diaspora_person_by_handle($diaspora_handle);
2138 if(! is_array($person)) {
2139 logger('diaspora_like: unable to find author details');
2144 $uri = $diaspora_handle . ':' . $guid;
2146 $activity = ACTIVITY_LIKE;
2147 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2148 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2149 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2150 $body = $parent_item['body'];
2155 <type>$objtype</type>
2157 <id>{$parent_item['uri']}</id>
2160 <content>$body</content>
2163 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2165 // Fetch the contact id - if we know this contact
2166 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
2167 dbesc(normalise_link($person['url'])), intval($importer['uid']));
2170 $network = $r[0]['network'];
2172 $cid = $contact['id'];
2173 $network = NETWORK_DIASPORA;
2179 $arr['uid'] = $importer['uid'];
2180 $arr['guid'] = $guid;
2181 $arr['network'] = $network;
2182 $arr['contact-id'] = $cid;
2183 $arr['type'] = 'activity';
2184 $arr['wall'] = $parent_item['wall'];
2185 $arr['gravity'] = GRAVITY_LIKE;
2186 $arr['parent'] = $parent_item['id'];
2187 $arr['parent-uri'] = $parent_item['uri'];
2189 $arr['owner-name'] = $parent_item['name'];
2190 $arr['owner-link'] = $parent_item['url'];
2191 //$arr['owner-avatar'] = $parent_item['thumb'];
2192 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2194 $arr['author-name'] = $person['name'];
2195 $arr['author-link'] = $person['url'];
2196 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2198 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2199 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2200 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2201 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2202 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2204 $arr['app'] = 'Diaspora';
2206 $arr['private'] = $parent_item['private'];
2207 $arr['verb'] = $activity;
2208 $arr['object-type'] = $objtype;
2209 $arr['object'] = $obj;
2210 $arr['visible'] = 1;
2212 $arr['last-child'] = 0;
2214 $message_id = item_store($arr);
2218 // q("update item set plink = '%s' where id = %d",
2219 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2220 // dbesc($a->get_baseurl().'/display/'.$guid),
2221 // intval($message_id)
2225 if(! $parent_author_signature) {
2226 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2227 intval($message_id),
2228 dbesc($signed_data),
2229 dbesc(base64_encode($author_signature)),
2230 dbesc($diaspora_handle)
2234 // if the message isn't already being relayed, notify others
2235 // the existence of parent_author_signature means the parent_author or owner
2236 // is already relaying. The parent_item['origin'] indicates the message was created on our system
2238 if(($parent_item['origin']) && (! $parent_author_signature))
2239 proc_run('php','include/notifier.php','comment-import',$message_id);
2244 function diaspora_retraction($importer,$xml) {
2247 $guid = notags(unxmlify($xml->guid));
2248 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2249 $type = notags(unxmlify($xml->type));
2251 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2255 if($type === 'Person') {
2256 require_once('include/Contact.php');
2257 contact_remove($contact['id']);
2258 } elseif($type === 'StatusMessage') {
2259 $guid = notags(unxmlify($xml->post_guid));
2261 $r = q("SELECT * FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2263 intval($importer['uid'])
2266 if(link_compare($r[0]['author-link'],$contact['url'])) {
2267 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
2268 dbesc(datetime_convert()),
2271 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2274 } elseif($type === 'Post') {
2275 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2277 intval($importer['uid'])
2280 if(link_compare($r[0]['author-link'],$contact['url'])) {
2281 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2282 dbesc(datetime_convert()),
2285 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2294 function diaspora_signed_retraction($importer,$xml,$msg) {
2297 $guid = notags(unxmlify($xml->target_guid));
2298 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2299 $type = notags(unxmlify($xml->target_type));
2300 $sig = notags(unxmlify($xml->target_author_signature));
2302 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2304 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2306 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2311 $signed_data = $guid . ';' . $type ;
2314 /* How Diaspora performs relayable_retraction signature checking:
2316 - If an item has been sent by the item author to the top-level post owner to relay on
2317 to the rest of the contacts on the top-level post, the top-level post owner checks
2318 the author_signature, then creates a parent_author_signature before relaying the item on
2319 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2320 check only the parent_author_signature. Basically, they trust that the top-level post
2321 owner has already verified the authenticity of anything he/she sends out
2322 - In either case, the signature that get checked is the signature created by the person
2326 if($parent_author_signature) {
2328 $parent_author_signature = base64_decode($parent_author_signature);
2330 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2331 logger('diaspora_signed_retraction: top-level post owner verification failed');
2338 $sig_decode = base64_decode($sig);
2340 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2341 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2346 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2347 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2349 intval($importer['uid'])
2352 if(link_compare($r[0]['author-link'],$contact['url'])) {
2353 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2354 dbesc(datetime_convert()),
2355 dbesc(datetime_convert()),
2358 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2360 // Now check if the retraction needs to be relayed by us
2362 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2363 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2364 // The only item with `parent` and `id` as the parent id is the parent item.
2365 $p = q("SELECT `origin` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2366 intval($r[0]['parent']),
2367 intval($r[0]['parent'])
2370 if(($p[0]['origin']) && (! $parent_author_signature)) {
2371 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2373 dbesc($signed_data),
2375 dbesc($diaspora_handle)
2378 // the existence of parent_author_signature would have meant the parent_author or owner
2379 // is already relaying.
2380 logger('diaspora_signed_retraction: relaying relayable_retraction');
2382 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2389 logger('diaspora_signed_retraction: unknown type: ' . $type);
2395 function diaspora_profile($importer,$xml,$msg) {
2398 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2401 if($diaspora_handle != $msg['author']) {
2402 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2406 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2410 //if($contact['blocked']) {
2411 // logger('diaspora_post: Ignoring this author.');
2415 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2416 $image_url = unxmlify($xml->image_url);
2417 $birthday = unxmlify($xml->birthday);
2418 $location = diaspora2bb(unxmlify($xml->location));
2419 $about = diaspora2bb(unxmlify($xml->bio));
2420 $gender = unxmlify($xml->gender);
2421 $searchable = (unxmlify($xml->searchable) == "true");
2422 $nsfw = (unxmlify($xml->nsfw) == "true");
2423 $tags = unxmlify($xml->tag_string);
2425 $tags = explode("#", $tags);
2427 $keywords = array();
2428 foreach ($tags as $tag) {
2429 $tag = trim(strtolower($tag));
2434 $keywords = implode(", ", $keywords);
2436 $handle_parts = explode("@", $diaspora_handle);
2437 $nick = $handle_parts[0];
2440 $name = $handle_parts[0];
2443 if( preg_match("|^https?://|", $image_url) === 0) {
2444 $image_url = "http://" . $handle_parts[1] . $image_url;
2447 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2448 intval($importer['uid']),
2449 intval($contact['id'])
2451 $oldphotos = ((count($r)) ? $r : null);*/
2453 require_once('include/Photo.php');
2455 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2457 // Generic birthday. We don't know the timezone. The year is irrelevant.
2459 $birthday = str_replace('1000','1901',$birthday);
2461 if ($birthday != "")
2462 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2464 // this is to prevent multiple birthday notifications in a single year
2465 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2467 if(substr($birthday,5) === substr($contact['bd'],5))
2468 $birthday = $contact['bd'];
2470 /// @TODO Update name on item['author-name'] if the name changed. See consume_feed()
2471 /// (Not doing this currently because D* protocol is scheduled for revision soon).
2473 $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",
2476 dbesc($diaspora_handle),
2477 dbesc(datetime_convert()),
2481 dbesc(datetime_convert()),
2487 intval($contact['id']),
2488 intval($importer['uid'])
2492 require_once('include/socgraph.php');
2493 poco_check($contact['url'], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
2494 datetime_convert(), 2, $contact['id'], $importer['uid']);
2497 update_gcontact(array("url" => $contact['url'], "network" => NETWORK_DIASPORA, "generation" => 2,
2498 "photo" => $image_url, "name" => $name, "location" => $location,
2499 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2500 "addr" => $diaspora_handle, "nick" => $nick, "keywords" => $keywords,
2501 "hide" => !$searchable, "nsfw" => $nsfw));
2505 foreach($oldphotos as $ph) {
2506 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2507 intval($importer['uid']),
2508 intval($contact['id']),
2509 dbesc($ph['resource-id'])
2519 function diaspora_share($me,$contact) {
2521 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2522 $theiraddr = $contact['addr'];
2524 $tpl = get_markup_template('diaspora_share.tpl');
2525 $msg = replace_macros($tpl, array(
2526 '$sender' => $myaddr,
2527 '$recipient' => $theiraddr
2530 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2531 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2533 return(diaspora_transmit($owner,$contact,$slap, false));
2536 function diaspora_unshare($me,$contact) {
2539 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2541 $tpl = get_markup_template('diaspora_retract.tpl');
2542 $msg = replace_macros($tpl, array(
2543 '$guid' => $me['guid'],
2544 '$type' => 'Person',
2545 '$handle' => $myaddr
2548 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2549 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2551 return(diaspora_transmit($owner,$contact,$slap, false));
2556 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2559 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2560 $theiraddr = $contact['addr'];
2564 $title = $item['title'];
2565 $body = $item['body'];
2568 // We're trying to match Diaspora's split message/photo protocol but
2569 // all the photos are displayed on D* as links and not img's - even
2570 // though we're sending pretty much precisely what they send us when
2571 // doing the same operation.
2572 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2573 // which seems to get through intact.
2575 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2577 foreach($matches as $mtch) {
2579 $detail['str'] = $mtch[0];
2580 $detail['path'] = dirname($mtch[1]) . '/';
2581 $detail['file'] = basename($mtch[1]);
2582 $detail['guid'] = $item['guid'];
2583 $detail['handle'] = $myaddr;
2584 $images[] = $detail;
2585 $body = str_replace($detail['str'],$mtch[1],$body);
2590 //if(strlen($title))
2591 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2593 // convert to markdown
2594 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2595 //$body = bb2diaspora($body);
2599 $body = "## ".html_entity_decode($title)."\n\n".$body;
2601 if($item['attach']) {
2602 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2604 $body .= "\n" . t('Attachments:') . "\n";
2605 foreach($matches as $mtch) {
2606 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2612 $public = (($item['private']) ? 'false' : 'true');
2614 require_once('include/datetime.php');
2615 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2617 // Detect a share element and do a reshare
2618 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2619 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2620 $tpl = get_markup_template('diaspora_reshare.tpl');
2621 $msg = replace_macros($tpl, array(
2622 '$root_handle' => xmlify($ret['root_handle']),
2623 '$root_guid' => $ret['root_guid'],
2624 '$guid' => $item['guid'],
2625 '$handle' => xmlify($myaddr),
2626 '$public' => $public,
2627 '$created' => $created,
2628 '$provider' => $item["app"]
2631 $tpl = get_markup_template('diaspora_post.tpl');
2632 $msg = replace_macros($tpl, array(
2634 '$guid' => $item['guid'],
2635 '$handle' => xmlify($myaddr),
2636 '$public' => $public,
2637 '$created' => $created,
2638 '$provider' => $item["app"]
2642 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2644 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2645 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2647 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2649 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2651 if(count($images)) {
2652 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2655 return $return_code;
2658 function diaspora_is_reshare($body) {
2659 $body = trim($body);
2661 // Skip if it isn't a pure repeated messages
2662 // Does it start with a share?
2663 if (strpos($body, "[share") > 0)
2666 // Does it end with a share?
2667 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2670 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2671 // Skip if there is no shared message in there
2672 if ($body == $attributes)
2676 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2677 if ($matches[1] != "")
2678 $guid = $matches[1];
2680 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2681 if ($matches[1] != "")
2682 $guid = $matches[1];
2685 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2686 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2689 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2690 $ret["root_guid"] = $guid;
2696 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2697 if ($matches[1] != "")
2698 $profile = $matches[1];
2700 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2701 if ($matches[1] != "")
2702 $profile = $matches[1];
2706 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2707 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2711 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2712 if ($matches[1] != "")
2713 $link = $matches[1];
2715 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2716 if ($matches[1] != "")
2717 $link = $matches[1];
2719 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2720 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2726 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2728 if(! count($images))
2730 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2732 $tpl = get_markup_template('diaspora_photo.tpl');
2733 foreach($images as $image) {
2734 if(! stristr($image['path'],$mysite))
2736 $resource = str_replace('.jpg','',$image['file']);
2737 $resource = substr($resource,0,strpos($resource,'-'));
2739 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2741 intval($owner['uid'])
2745 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2746 $msg = replace_macros($tpl,array(
2747 '$path' => xmlify($image['path']),
2748 '$filename' => xmlify($image['file']),
2749 '$msg_guid' => xmlify($image['guid']),
2750 '$guid' => xmlify($r[0]['guid']),
2751 '$handle' => xmlify($image['handle']),
2752 '$public' => xmlify($public),
2753 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2757 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2758 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2759 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2761 diaspora_transmit($owner,$contact,$slap,$public_batch);
2766 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2769 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2770 // $theiraddr = $contact['addr'];
2772 // Diaspora doesn't support threaded comments, but some
2773 // versions of Diaspora (i.e. Diaspora-pistos) support
2774 // likes on comments
2775 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2776 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2777 dbesc($item['thr-parent'])
2781 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2782 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2783 // The only item with `parent` and `id` as the parent id is the parent item.
2784 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2785 intval($item['parent']),
2786 intval($item['parent'])
2794 if($item['verb'] === ACTIVITY_LIKE) {
2795 $tpl = get_markup_template('diaspora_like.tpl');
2797 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2798 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2799 // $positive = (($item['deleted']) ? 'false' : 'true');
2802 if(($item['deleted']))
2803 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2806 $tpl = get_markup_template('diaspora_comment.tpl');
2810 $text = html_entity_decode(bb2diaspora($item['body']));
2815 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2817 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2819 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2821 $msg = replace_macros($tpl,array(
2822 '$guid' => xmlify($item['guid']),
2823 '$parent_guid' => xmlify($parent['guid']),
2824 '$target_type' =>xmlify($target_type),
2825 '$authorsig' => xmlify($authorsig),
2826 '$body' => xmlify($text),
2827 '$positive' => xmlify($positive),
2828 '$handle' => xmlify($myaddr)
2831 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2833 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2834 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2836 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2840 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2844 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2845 // $theiraddr = $contact['addr'];
2847 $body = $item['body'];
2848 $text = html_entity_decode(bb2diaspora($body));
2850 // Diaspora doesn't support threaded comments, but some
2851 // versions of Diaspora (i.e. Diaspora-pistos) support
2852 // likes on comments
2853 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2854 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2855 dbesc($item['thr-parent'])
2859 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2860 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2861 // The only item with `parent` and `id` as the parent id is the parent item.
2862 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2863 intval($item['parent']),
2864 intval($item['parent'])
2873 $relay_retract = false;
2874 $sql_sign_id = 'iid';
2875 if( $item['deleted']) {
2876 $relay_retract = true;
2878 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2880 $sql_sign_id = 'retract_iid';
2881 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2883 elseif($item['verb'] === ACTIVITY_LIKE) {
2886 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2887 // $positive = (($item['deleted']) ? 'false' : 'true');
2890 $tpl = get_markup_template('diaspora_like_relay.tpl');
2892 else { // item is a comment
2893 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2897 // fetch the original signature if the relayable was created by a Diaspora
2898 // or DFRN user. Relayables for other networks are not supported.
2900 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2905 $signed_text = $orig_sign['signed_text'];
2906 $authorsig = $orig_sign['signature'];
2907 $handle = $orig_sign['signer'];
2911 // Author signature information (for likes, comments, and retractions of likes or comments,
2912 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2913 // function is called
2914 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2918 /* Since the author signature is only checked by the parent, not by the relay recipients,
2919 * I think it may not be necessary for us to do so much work to preserve all the original
2920 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2921 * Let's just generate that and forget about all the original author signature stuff.
2923 * Note: this might be more of an problem if we want to support likes on comments for older
2924 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2925 * doing that, let's ignore it for now.
2927 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2931 $handle = diaspora_handle_from_contact($item['contact-id']);
2937 $sender_signed_text = $item['guid'] . ';' . $target_type;
2939 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2941 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2943 // Sign the relayable with the top-level owner's signature
2945 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2946 // stored in the database, because that provides the best chance that Diaspora will
2947 // be able to reconstruct the signed text the same way we did. This is particularly a
2948 // concern for the comment, whose signed text includes the text of the comment. The
2949 // smallest change in the text of the comment, including removing whitespace, will
2950 // make the signature verification fail. Since we translate from BB code to Diaspora's
2951 // markup at the top of this function, which is AFTER we placed the original $signed_text
2952 // in the database, it's hazardous to trust the original $signed_text.
2954 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2956 $msg = replace_macros($tpl,array(
2957 '$guid' => xmlify($item['guid']),
2958 '$parent_guid' => xmlify($parent['guid']),
2959 '$target_type' =>xmlify($target_type),
2960 '$authorsig' => xmlify($authorsig),
2961 '$parentsig' => xmlify($parentauthorsig),
2962 '$body' => xmlify($text),
2963 '$positive' => xmlify($positive),
2964 '$handle' => xmlify($handle)
2967 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2970 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2971 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2973 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2979 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2982 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2984 // Check whether the retraction is for a top-level post or whether it's a relayable
2985 if( $item['uri'] !== $item['parent-uri'] ) {
2987 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2988 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2992 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2993 $target_type = 'StatusMessage';
2996 $signed_text = $item['guid'] . ';' . $target_type;
2998 $msg = replace_macros($tpl, array(
2999 '$guid' => xmlify($item['guid']),
3000 '$type' => xmlify($target_type),
3001 '$handle' => xmlify($myaddr),
3002 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
3005 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
3006 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
3008 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
3011 function diaspora_send_mail($item,$owner,$contact) {
3014 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
3016 $r = q("select * from conv where id = %d and uid = %d limit 1",
3017 intval($item['convid']),
3018 intval($item['uid'])
3022 logger('diaspora_send_mail: conversation not found.');
3028 'guid' => xmlify($cnv['guid']),
3029 'subject' => xmlify($cnv['subject']),
3030 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
3031 'diaspora_handle' => xmlify($cnv['creator']),
3032 'participant_handles' => xmlify($cnv['recips'])
3035 $body = bb2diaspora($item['body']);
3036 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
3038 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
3039 . $created . ';' . $myaddr . ';' . $cnv['guid'];
3041 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
3044 'guid' => xmlify($item['guid']),
3045 'parent_guid' => xmlify($cnv['guid']),
3046 'parent_author_signature' => xmlify($sig),
3047 'author_signature' => xmlify($sig),
3048 'text' => xmlify($body),
3049 'created_at' => xmlify($created),
3050 'diaspora_handle' => xmlify($myaddr),
3051 'conversation_guid' => xmlify($cnv['guid'])
3054 if($item['reply']) {
3055 $tpl = get_markup_template('diaspora_message.tpl');
3056 $xmsg = replace_macros($tpl, array('$msg' => $msg));
3059 $conv['messages'] = array($msg);
3060 $tpl = get_markup_template('diaspora_conversation.tpl');
3061 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3064 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3066 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3067 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3069 return(diaspora_transmit($owner,$contact,$slap,false));
3074 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
3076 $enabled = intval(get_config('system','diaspora_enabled'));
3082 $logid = random_string(4);
3083 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3085 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3089 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
3091 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3095 if (!intval(get_config('system','diaspora_test'))) {
3096 post_url($dest_url . '/', $slap);
3097 $return_code = $a->get_curl_code();
3099 logger('diaspora_transmit: test_mode');
3104 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
3106 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3107 logger('diaspora_transmit: queue message');
3109 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3110 intval($contact['id']),
3111 dbesc(NETWORK_DIASPORA),
3113 intval($public_batch)
3116 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3119 // queue message for redelivery
3120 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3125 return(($return_code) ? $return_code : (-1));
3128 function diaspora_fetch_relay() {
3130 $serverdata = get_config("system", "relay_server");
3131 if ($serverdata == "")
3136 $servers = explode(",", $serverdata);
3138 foreach($servers AS $server) {
3139 $server = trim($server);
3140 $batch = $server."/receive/public";
3142 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3145 $addr = "relay@".str_replace("http://", "", normalise_link($server));
3147 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
3148 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
3153 dbesc(normalise_link($server)),
3155 dbesc(NETWORK_DIASPORA),
3156 intval(CONTACT_IS_FOLLOWER),
3157 dbesc(datetime_convert()),
3158 dbesc(datetime_convert()),
3159 dbesc(datetime_convert())
3162 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3164 $relay[] = $relais[0];
3166 $relay[] = $relais[0];