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');
17 require_once('include/enotify.php');
19 function diaspora_dispatch_public($msg) {
21 $enabled = intval(get_config('system','diaspora_enabled'));
23 logger('mod-diaspora: disabled');
27 // Use a dummy importer to import the data for the public copy
28 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
29 $result = diaspora_dispatch($importer,$msg);
30 logger("Dispatcher reported ".$result, LOGGER_DEBUG);
32 // Now distribute it to the followers
33 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
34 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
35 AND `account_expired` = 0 AND `account_removed` = 0 ",
36 dbesc(NETWORK_DIASPORA),
41 logger('diaspora_public: delivering to: ' . $rr['username']);
42 diaspora_dispatch($rr,$msg);
46 logger('diaspora_public: no subscribers for '.$msg["author"].' '.print_r($msg, true));
51 function diaspora_dispatch($importer,$msg,$attempt=1) {
55 $enabled = intval(get_config('system','diaspora_enabled'));
57 logger('mod-diaspora: disabled');
61 // php doesn't like dashes in variable names
63 $msg['message'] = str_replace(
64 array('<activity_streams-photo>','</activity_streams-photo>'),
65 array('<asphoto>','</asphoto>'),
69 $parsed_xml = parse_xml_string($msg['message'],false);
71 $xmlbase = $parsed_xml->post;
73 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
76 if($xmlbase->request) {
77 $ret = diaspora_request($importer,$xmlbase->request);
79 elseif($xmlbase->status_message) {
80 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
82 elseif($xmlbase->profile) {
83 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
85 elseif($xmlbase->comment) {
86 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
88 elseif($xmlbase->like) {
89 $ret = diaspora_like($importer,$xmlbase->like,$msg);
91 elseif($xmlbase->asphoto) {
92 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
94 elseif($xmlbase->reshare) {
95 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
97 elseif($xmlbase->retraction) {
98 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
100 elseif($xmlbase->signed_retraction) {
101 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
103 elseif($xmlbase->relayable_retraction) {
104 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
106 elseif($xmlbase->photo) {
107 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
109 elseif($xmlbase->conversation) {
110 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
112 elseif($xmlbase->message) {
113 $ret = diaspora_message($importer,$xmlbase->message,$msg);
115 elseif($xmlbase->participation) {
116 $ret = diaspora_participation($importer,$xmlbase->participation);
119 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
124 function diaspora_handle_from_contact($contact_id) {
127 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
129 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
135 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
137 if($contact['network'] === NETWORK_DIASPORA) {
138 $handle = $contact['addr'];
140 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
142 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
143 $baseurl_start = strpos($contact['url'],'://') + 3;
144 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
145 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
146 $handle = $contact['nick'] . '@' . $baseurl;
148 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
155 function diaspora_get_contact_by_handle($uid,$handle) {
156 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
157 dbesc(NETWORK_DIASPORA),
164 $handle_parts = explode("@", $handle);
165 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
166 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
177 function find_diaspora_person_by_handle($handle) {
187 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
188 dbesc(NETWORK_DIASPORA),
193 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
195 // update record occasionally so it doesn't get stale
196 $d = strtotime($person['updated'] . ' +00:00');
197 if($d < strtotime('now - 14 days'))
202 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
204 // If the person isn't in our 'fcontact' table, or if he/she is but
205 // his/her information hasn't been updated for more than 14 days, then
206 // we want to fetch the person's information from the remote server.
208 // Note that $person isn't changed by this block of code unless the
209 // person's information has been successfully fetched from the remote
210 // server. So if $person was 'false' to begin with (because he/she wasn't
211 // in the local cache), it'll stay false, and if $person held the local
212 // cache information to begin with, it'll keep that information. That way
213 // if there's a problem with the remote fetch, we can at least use our
214 // cached information--it's better than nothing.
216 if((! $person) || ($update)) {
217 // Lock the function to prevent race conditions if multiple items
218 // come in at the same time from a person who doesn't exist in
221 // Don't loop forever. On the last loop, try to create the contact
222 // whether the function is locked or not. Maybe the locking thread
223 // has died or something. At any rate, a duplicate in 'fcontact'
224 // is a much smaller problem than a deadlocked thread
225 $got_lock = lock_function('find_diaspora_person_by_handle', false);
226 if(($endlessloop + 1) >= $maxloops)
230 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
231 require_once('include/Scrape.php');
232 $r = probe_url($handle, PROBE_DIASPORA);
234 // Note that Friendica contacts can return a "Diaspora person"
235 // if Diaspora connectivity is enabled on their server
236 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
237 add_fcontact($r,$update);
241 unlock_function('find_diaspora_person_by_handle');
244 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
246 block_on_function_lock('find_diaspora_person_by_handle');
249 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
250 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
251 // The fact that the function was locked may mean that another process was creating the
252 // person's record. It could also mean another process was creating or updating an unrelated
255 // At any rate, we need to keep trying until we've either got the person or had a chance to
256 // try to fetch his/her remote information. But we don't want to block on locking the
257 // function, because if the other process is creating the record, then when we acquire the lock
258 // we'll dive right into creating another, duplicate record. We DO want to at least wait
259 // until the lock is released, so we don't flood the database with requests.
261 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
262 // we do have some information for the person
268 function get_diaspora_key($uri) {
269 logger('Fetching diaspora key for: ' . $uri);
271 $r = find_diaspora_person_by_handle($uri);
278 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
281 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
284 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
286 // $b64_data = base64_encode($msg);
287 // $b64url_data = base64url_encode($b64_data);
289 $b64url_data = base64url_encode($msg);
291 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
293 $type = 'application/xml';
294 $encoding = 'base64url';
297 $signable_data = $data . '.' . base64url_encode($type) . '.'
298 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
300 $signature = rsa_sign($signable_data,$prvkey);
301 $sig = base64url_encode($signature);
304 <?xml version='1.0' encoding='UTF-8'?>
305 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
307 <author_id>$handle</author_id>
310 <me:encoding>base64url</me:encoding>
311 <me:alg>RSA-SHA256</me:alg>
312 <me:data type="application/xml">$data</me:data>
313 <me:sig>$sig</me:sig>
318 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
326 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
330 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
332 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
334 // without a public key nothing will work
337 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
341 $inner_aes_key = random_string(32);
342 $b_inner_aes_key = base64_encode($inner_aes_key);
343 $inner_iv = random_string(16);
344 $b_inner_iv = base64_encode($inner_iv);
346 $outer_aes_key = random_string(32);
347 $b_outer_aes_key = base64_encode($outer_aes_key);
348 $outer_iv = random_string(16);
349 $b_outer_iv = base64_encode($outer_iv);
351 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
353 $padded_data = pkcs5_pad($msg,16);
354 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
356 $b64_data = base64_encode($inner_encrypted);
359 $b64url_data = base64url_encode($b64_data);
360 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
362 $type = 'application/xml';
363 $encoding = 'base64url';
366 $signable_data = $data . '.' . base64url_encode($type) . '.'
367 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
369 $signature = rsa_sign($signable_data,$prvkey);
370 $sig = base64url_encode($signature);
372 $decrypted_header = <<< EOT
375 <aes_key>$b_inner_aes_key</aes_key>
376 <author_id>$handle</author_id>
380 $decrypted_header = pkcs5_pad($decrypted_header,16);
382 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
384 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
386 $encrypted_outer_key_bundle = '';
387 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
389 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
391 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
393 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
394 'ciphertext' => base64_encode($ciphertext)));
395 $cipher_json = base64_encode($encrypted_header_json_object);
397 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
400 <?xml version='1.0' encoding='UTF-8'?>
401 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
404 <me:encoding>base64url</me:encoding>
405 <me:alg>RSA-SHA256</me:alg>
406 <me:data type="application/xml">$data</me:data>
407 <me:sig>$sig</me:sig>
412 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
419 * diaspora_decode($importer,$xml)
420 * array $importer -> from user table
421 * string $xml -> urldecoded Diaspora salmon
424 * 'message' -> decoded Diaspora XML message
425 * 'author' -> author diaspora handle
426 * 'key' -> author public key (converted to pkcs#8)
428 * Author and key are used elsewhere to save a lookup for verifying replies and likes
432 function diaspora_decode($importer,$xml) {
435 $basedom = parse_xml_string($xml);
437 $children = $basedom->children('https://joindiaspora.com/protocol');
439 if($children->header) {
441 $author_link = str_replace('acct:','',$children->header->author_id);
445 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
447 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
448 $ciphertext = base64_decode($encrypted_header->ciphertext);
450 $outer_key_bundle = '';
451 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
453 $j_outer_key_bundle = json_decode($outer_key_bundle);
455 $outer_iv = base64_decode($j_outer_key_bundle->iv);
456 $outer_key = base64_decode($j_outer_key_bundle->key);
458 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
461 $decrypted = pkcs5_unpad($decrypted);
464 * $decrypted now contains something like
467 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
468 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
473 * <name>Ryan Hughes</name>
474 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
479 * <author_id>galaxor@diaspora.priateship.org</author_id>
483 * </decrypted_header>
486 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
487 $idom = parse_xml_string($decrypted,false);
489 $inner_iv = base64_decode($idom->iv);
490 $inner_aes_key = base64_decode($idom->aes_key);
492 $author_link = str_replace('acct:','',$idom->author_id);
496 $dom = $basedom->children(NAMESPACE_SALMON_ME);
498 // figure out where in the DOM tree our data is hiding
500 if($dom->provenance->data)
501 $base = $dom->provenance;
502 elseif($dom->env->data)
508 logger('mod-diaspora: unable to locate salmon data in xml ');
509 http_status_exit(400);
513 // Stash the signature away for now. We have to find their key or it won't be good for anything.
514 $signature = base64url_decode($base->sig);
518 // strip whitespace so our data element will return to one big base64 blob
519 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
522 // stash away some other stuff for later
524 $type = $base->data[0]->attributes()->type[0];
525 $keyhash = $base->sig[0]->attributes()->keyhash[0];
526 $encoding = $base->encoding;
530 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
534 $data = base64url_decode($data);
538 $inner_decrypted = $data;
542 // Decode the encrypted blob
544 $inner_encrypted = base64_decode($data);
545 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
546 $inner_decrypted = pkcs5_unpad($inner_decrypted);
550 logger('mod-diaspora: Could not retrieve author URI.');
551 http_status_exit(400);
554 // Once we have the author URI, go to the web and try to find their public key
555 // (first this will look it up locally if it is in the fcontact cache)
556 // This will also convert diaspora public key from pkcs#1 to pkcs#8
558 logger('mod-diaspora: Fetching key for ' . $author_link );
559 $key = get_diaspora_key($author_link);
562 logger('mod-diaspora: Could not retrieve author key.');
563 http_status_exit(400);
566 $verify = rsa_verify($signed_data,$signature,$key);
569 logger('mod-diaspora: Message did not verify. Discarding.');
570 http_status_exit(400);
573 logger('mod-diaspora: Message verified.');
575 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
580 function diaspora_request($importer,$xml) {
584 $sender_handle = unxmlify($xml->sender_handle);
585 $recipient_handle = unxmlify($xml->recipient_handle);
587 if(! $sender_handle || ! $recipient_handle)
590 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
594 // perhaps we were already sharing with this person. Now they're sharing with us.
595 // That makes us friends.
597 if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
598 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
599 intval(CONTACT_IS_FRIEND),
600 intval($contact['id']),
601 intval($importer['uid'])
606 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
607 intval($importer['uid'])
610 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
611 require_once('include/items.php');
613 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
614 intval($importer['uid'])
617 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
619 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
622 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
623 $arr['uid'] = $importer['uid'];
624 $arr['contact-id'] = $self[0]['id'];
626 $arr['type'] = 'wall';
629 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
630 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
631 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
632 $arr['verb'] = ACTIVITY_FRIEND;
633 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
635 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
636 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
637 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
638 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
640 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
641 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
642 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
643 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
644 $arr['object'] .= '</link></object>' . "\n";
645 $arr['last-child'] = 1;
647 $arr['allow_cid'] = $user[0]['allow_cid'];
648 $arr['allow_gid'] = $user[0]['allow_gid'];
649 $arr['deny_cid'] = $user[0]['deny_cid'];
650 $arr['deny_gid'] = $user[0]['deny_gid'];
652 $i = item_store($arr);
654 proc_run('php',"include/notifier.php","activity","$i");
663 $ret = find_diaspora_person_by_handle($sender_handle);
666 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
667 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
671 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
675 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
676 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
677 intval($importer['uid']),
678 dbesc($ret['network']),
682 dbesc(normalise_link($ret['url'])),
686 dbesc($ret['photo']),
687 dbesc($ret['pubkey']),
688 dbesc($ret['notify']),
694 // find the contact record we just created
696 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
698 if(! $contact_record) {
699 logger('diaspora_request: unable to locate newly created contact record.');
703 $g = q("select def_gid from user where uid = %d limit 1",
704 intval($importer['uid'])
706 if($g && intval($g[0]['def_gid'])) {
707 require_once('include/group.php');
708 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
711 if($importer['page-flags'] == PAGE_NORMAL) {
713 $hash = random_string() . (string) time(); // Generate a confirm_key
715 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
716 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
717 intval($importer['uid']),
718 intval($contact_record['id']),
721 dbesc( t('Sharing notification from Diaspora network')),
723 dbesc(datetime_convert())
728 // automatic friend approval
730 require_once('include/Photo.php');
732 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
734 // technically they are sharing with us (CONTACT_IS_SHARING),
735 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
736 // we are going to change the relationship and make them a follower.
738 if($importer['page-flags'] == PAGE_FREELOVE)
739 $new_relation = CONTACT_IS_FRIEND;
741 $new_relation = CONTACT_IS_FOLLOWER;
743 $r = q("UPDATE `contact` SET
750 `avatar-date` = '%s',
759 intval($new_relation),
760 dbesc(datetime_convert()),
761 dbesc(datetime_convert()),
762 dbesc(datetime_convert()),
763 intval($contact_record['id'])
766 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
768 $ret = diaspora_share($u[0],$contact_record);
774 function diaspora_post_allow($importer,$contact, $is_comment = false) {
776 // perhaps we were already sharing with this person. Now they're sharing with us.
777 // That makes us friends.
778 // Normally this should have handled by getting a request - but this could get lost
779 if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
780 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
781 intval(CONTACT_IS_FRIEND),
782 intval($contact['id']),
783 intval($importer['uid'])
785 $contact['rel'] = CONTACT_IS_FRIEND;
786 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
789 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
791 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
793 if($contact['rel'] == CONTACT_IS_FOLLOWER)
794 if(($importer['page-flags'] == PAGE_COMMUNITY) OR $is_comment)
797 // Messages for the global users are always accepted
798 if ($importer['uid'] == 0)
804 function diaspora_is_redmatrix($url) {
805 return(strstr($url, "/channel/"));
808 function diaspora_plink($addr, $guid) {
809 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
813 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
815 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
816 // So we try another way as well.
817 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
819 $r[0]["network"] = $s[0]["network"];
821 if ($r[0]["network"] == NETWORK_DFRN)
822 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
824 if (diaspora_is_redmatrix($r[0]["url"]))
825 return $r[0]["url"]."/?f=&mid=".$guid;
827 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
830 function diaspora_repair_signature($signature, $handle = "", $level = 1) {
832 if ($signature == "")
835 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
836 $signature = base64_decode($signature);
837 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
839 // Do a recursive call to be able to fix even multiple levels
841 $signature = diaspora_repair_signature($signature, $handle, ++$level);
847 function diaspora_post($importer,$xml,$msg) {
850 $guid = notags(unxmlify($xml->guid));
851 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
853 if($diaspora_handle != $msg['author']) {
854 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
858 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
860 logger('diaspora_post: A Contact for handle '.$diaspora_handle.' and user '.$importer['uid'].' was not found');
864 if(! diaspora_post_allow($importer,$contact, false)) {
865 logger('diaspora_post: Ignoring this author.');
869 $message_id = $diaspora_handle . ':' . $guid;
870 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
871 intval($importer['uid']),
875 logger('diaspora_post: message exists: ' . $guid);
879 $created = unxmlify($xml->created_at);
880 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
882 $body = diaspora2bb($xml->raw_message);
886 $datarray["object"] = json_encode($xml);
888 if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
889 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
891 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
892 // Add OEmbed and other information to the body
893 if (!diaspora_is_redmatrix($contact['url']))
894 $body = add_page_info_to_body($body, false, true);
899 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
901 foreach($matches as $mtch) {
902 if(strlen($str_tags))
904 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
908 $plink = diaspora_plink($diaspora_handle, $guid);
910 $datarray['uid'] = $importer['uid'];
911 $datarray['contact-id'] = $contact['id'];
912 $datarray['wall'] = 0;
913 $datarray['network'] = NETWORK_DIASPORA;
914 $datarray['verb'] = ACTIVITY_POST;
915 $datarray['guid'] = $guid;
916 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
917 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
918 $datarray['private'] = $private;
919 $datarray['parent'] = 0;
920 $datarray['plink'] = $plink;
921 $datarray['owner-name'] = $contact['name'];
922 $datarray['owner-link'] = $contact['url'];
923 //$datarray['owner-avatar'] = $contact['thumb'];
924 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
925 $datarray['author-name'] = $contact['name'];
926 $datarray['author-link'] = $contact['url'];
927 $datarray['author-avatar'] = $contact['thumb'];
928 $datarray['body'] = $body;
929 $datarray['tag'] = $str_tags;
930 if ($xml->provider_display_name)
931 $datarray["app"] = unxmlify($xml->provider_display_name);
933 $datarray['app'] = 'Diaspora';
935 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
937 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
939 DiasporaFetchGuid($datarray);
940 $message_id = item_store($datarray);
942 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
948 function DiasporaFetchGuid($item) {
949 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
950 function ($match) use ($item){
951 return(DiasporaFetchGuidSub($match, $item));
955 function DiasporaFetchGuidSub($match, $item) {
958 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
959 diaspora_store_by_guid($match[1], $item["owner-link"]);
962 function diaspora_store_by_guid($guid, $server, $uid = 0) {
963 require_once("include/Contact.php");
965 $serverparts = parse_url($server);
966 $server = $serverparts["scheme"]."://".$serverparts["host"];
968 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
970 $item = diaspora_fetch_message($guid, $server);
975 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
977 $body = $item["body"];
978 $str_tags = $item["tag"];
980 $created = $item["created"];
981 $author = $item["author"];
982 $guid = $item["guid"];
983 $private = $item["private"];
984 $object = $item["object"];
985 $objecttype = $item["object-type"];
987 $message_id = $author.':'.$guid;
988 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
995 $person = find_diaspora_person_by_handle($author);
997 $contact_id = get_contact($person['url'], $uid);
999 $contacts = q("SELECT * FROM `contact` WHERE `id` = %d", intval($contact_id));
1000 $importers = q("SELECT * FROM `user` WHERE `uid` = %d", intval($uid));
1002 if ($contacts AND $importers)
1003 if(!diaspora_post_allow($importers[0],$contacts[0], false)) {
1004 logger('Ignoring author '.$person['url'].' for uid '.$uid);
1007 logger('Author '.$person['url'].' is allowed for uid '.$uid);
1009 $datarray = array();
1010 $datarray['uid'] = $uid;
1011 $datarray['contact-id'] = $contact_id;
1012 $datarray['wall'] = 0;
1013 $datarray['network'] = NETWORK_DIASPORA;
1014 $datarray['guid'] = $guid;
1015 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1016 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1017 $datarray['private'] = $private;
1018 $datarray['parent'] = 0;
1019 $datarray['plink'] = diaspora_plink($author, $guid);
1020 $datarray['author-name'] = $person['name'];
1021 $datarray['author-link'] = $person['url'];
1022 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1023 $datarray['owner-name'] = $datarray['author-name'];
1024 $datarray['owner-link'] = $datarray['author-link'];
1025 $datarray['owner-avatar'] = $datarray['author-avatar'];
1026 $datarray['body'] = $body;
1027 $datarray['tag'] = $str_tags;
1028 $datarray['app'] = $app;
1029 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1030 $datarray['object'] = $object;
1031 $datarray['object-type'] = $objecttype;
1033 if ($datarray['contact-id'] == 0)
1036 DiasporaFetchGuid($datarray);
1037 $message_id = item_store($datarray);
1040 /// Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
1045 function diaspora_fetch_message($guid, $server, $level = 0) {
1052 // This will not work if the server is not a Diaspora server
1053 $source_url = $server.'/p/'.$guid.'.xml';
1054 $x = fetch_url($source_url);
1058 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1059 $source_xml = parse_xml_string($x,false);
1062 $item["app"] = 'Diaspora';
1063 $item["guid"] = $guid;
1066 if ($source_xml->post->status_message->created_at)
1067 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1069 if ($source_xml->post->status_message->provider_display_name)
1070 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1072 if ($source_xml->post->status_message->diaspora_handle)
1073 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1075 if ($source_xml->post->status_message->guid)
1076 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1078 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1079 $item["object"] = json_encode($source_xml->post);
1081 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1082 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1083 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1084 $body = scale_external_images($body,false);
1085 } elseif($source_xml->post->asphoto->image_url) {
1086 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1087 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1088 $body = scale_external_images($body);
1089 } elseif($source_xml->post->status_message) {
1090 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1092 // Checking for embedded pictures
1093 if($source_xml->post->status_message->photo->remote_photo_path AND
1094 $source_xml->post->status_message->photo->remote_photo_name) {
1096 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1098 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1099 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1101 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1103 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1105 $item["object-type"] = ACTIVITY_OBJ_NOTE;
1107 $body = scale_external_images($body);
1109 // Add OEmbed and other information to the body
1110 /// @TODO It could be a repeated redmatrix item
1111 /// Then we shouldn't add further data to it
1112 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1113 $body = add_page_info_to_body($body, false, true);
1115 } elseif($source_xml->post->reshare) {
1116 // Reshare of a reshare
1117 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1119 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1120 logger('no content found: '.print_r($source_xml,true));
1124 if (trim($body) == "")
1128 $item["body"] = $body;
1133 function diaspora_reshare($importer,$xml,$msg) {
1135 logger('diaspora_reshare: init: ' . print_r($xml,true));
1138 $guid = notags(unxmlify($xml->guid));
1139 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1142 if($diaspora_handle != $msg['author']) {
1143 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1147 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1151 if(! diaspora_post_allow($importer,$contact, false)) {
1152 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1156 $message_id = $diaspora_handle . ':' . $guid;
1157 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1158 intval($importer['uid']),
1162 logger('diaspora_reshare: message exists: ' . $guid);
1166 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1167 $orig_guid = notags(unxmlify($xml->root_guid));
1168 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1170 $create_original_post = false;
1172 // Do we already have this item?
1173 $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",
1175 dbesc(NETWORK_DIASPORA)
1178 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1180 // Maybe it is already a reshared item?
1181 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1182 require_once('include/api.php');
1183 if (api_share_as_retweet($r[0]))
1186 $body = $r[0]["body"];
1187 $str_tags = $r[0]["tag"];
1188 $app = $r[0]["app"];
1189 $orig_created = $r[0]["created"];
1190 $orig_plink = $r[0]["plink"];
1191 $orig_uri = $r[0]["uri"];
1192 $object = $r[0]["object"];
1193 $objecttype = $r[0]["object-type"];
1202 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1203 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1204 $item = diaspora_fetch_message($orig_guid, $server);
1207 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1208 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1209 $item = diaspora_fetch_message($orig_guid, $server);
1212 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1213 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1214 $item = diaspora_fetch_message($orig_guid, $server);
1217 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1218 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1219 $item = diaspora_fetch_message($orig_guid, $server);
1223 $body = $item["body"];
1224 $str_tags = $item["tag"];
1225 $app = $item["app"];
1226 $orig_created = $item["created"];
1227 $orig_author = $item["author"];
1228 $orig_guid = $item["guid"];
1229 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1230 $orig_uri = $orig_author.':'.$orig_guid;
1231 $create_original_post = ($body != "");
1232 $object = $item["object"];
1233 $objecttype = $item["object-type"];
1237 $plink = diaspora_plink($diaspora_handle, $guid);
1239 $person = find_diaspora_person_by_handle($orig_author);
1241 $created = unxmlify($xml->created_at);
1242 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1244 $datarray = array();
1246 $datarray['uid'] = $importer['uid'];
1247 $datarray['contact-id'] = $contact['id'];
1248 $datarray['wall'] = 0;
1249 $datarray['network'] = NETWORK_DIASPORA;
1250 $datarray['guid'] = $guid;
1251 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1252 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1253 $datarray['private'] = $private;
1254 $datarray['parent'] = 0;
1255 $datarray['plink'] = $plink;
1256 $datarray['owner-name'] = $contact['name'];
1257 $datarray['owner-link'] = $contact['url'];
1258 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1259 if (!intval(get_config('system','wall-to-wall_share'))) {
1260 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1262 $datarray['author-name'] = $contact['name'];
1263 $datarray['author-link'] = $contact['url'];
1264 $datarray['author-avatar'] = $contact['thumb'];
1265 $datarray['body'] = $prefix.$body."[/share]";
1267 // Let reshared messages look like wall-to-wall posts
1268 $datarray['author-name'] = $person['name'];
1269 $datarray['author-link'] = $person['url'];
1270 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1271 $datarray['body'] = $body;
1274 $datarray["object"] = json_encode($xml);
1275 $datarray['object-type'] = $objecttype;
1277 $datarray['tag'] = $str_tags;
1278 $datarray['app'] = $app;
1280 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1281 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1283 // Store the original item of a reshare
1284 if ($create_original_post) {
1285 require_once("include/Contact.php");
1287 $datarray2 = $datarray;
1289 $datarray2['uid'] = 0;
1290 $datarray2['contact-id'] = get_contact($person['url'], 0);
1291 $datarray2['guid'] = $orig_guid;
1292 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1293 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1294 $datarray2['parent'] = 0;
1295 $datarray2['plink'] = $orig_plink;
1297 $datarray2['author-name'] = $person['name'];
1298 $datarray2['author-link'] = $person['url'];
1299 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1300 $datarray2['owner-name'] = $datarray2['author-name'];
1301 $datarray2['owner-link'] = $datarray2['author-link'];
1302 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1303 $datarray2['body'] = $body;
1304 $datarray2["object"] = $object;
1306 DiasporaFetchGuid($datarray2);
1307 $message_id = item_store($datarray2);
1309 logger("Store original item ".$orig_guid." under message id ".$message_id);
1312 DiasporaFetchGuid($datarray);
1313 $message_id = item_store($datarray);
1320 function diaspora_asphoto($importer,$xml,$msg) {
1321 logger('diaspora_asphoto called');
1324 $guid = notags(unxmlify($xml->guid));
1325 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1327 if($diaspora_handle != $msg['author']) {
1328 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1332 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1336 if(! diaspora_post_allow($importer,$contact, false)) {
1337 logger('diaspora_asphoto: Ignoring this author.');
1341 $message_id = $diaspora_handle . ':' . $guid;
1342 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1343 intval($importer['uid']),
1347 logger('diaspora_asphoto: message exists: ' . $guid);
1351 $created = unxmlify($xml->created_at);
1352 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1354 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1355 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1356 $body = scale_external_images($body,false);
1358 elseif($xml->image_url) {
1359 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1360 $body = scale_external_images($body);
1363 logger('diaspora_asphoto: no photo url found.');
1367 $plink = diaspora_plink($diaspora_handle, $guid);
1369 $datarray = array();
1371 $datarray['uid'] = $importer['uid'];
1372 $datarray['contact-id'] = $contact['id'];
1373 $datarray['wall'] = 0;
1374 $datarray['network'] = NETWORK_DIASPORA;
1375 $datarray['guid'] = $guid;
1376 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1377 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1378 $datarray['private'] = $private;
1379 $datarray['parent'] = 0;
1380 $datarray['plink'] = $plink;
1381 $datarray['owner-name'] = $contact['name'];
1382 $datarray['owner-link'] = $contact['url'];
1383 //$datarray['owner-avatar'] = $contact['thumb'];
1384 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1385 $datarray['author-name'] = $contact['name'];
1386 $datarray['author-link'] = $contact['url'];
1387 $datarray['author-avatar'] = $contact['thumb'];
1388 $datarray['body'] = $body;
1389 $datarray["object"] = json_encode($xml);
1390 $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1392 $datarray['app'] = 'Diaspora/Cubbi.es';
1394 DiasporaFetchGuid($datarray);
1395 $message_id = item_store($datarray);
1398 // q("update item set plink = '%s' where id = %d",
1399 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1400 // intval($message_id)
1408 function diaspora_comment($importer,$xml,$msg) {
1411 $guid = notags(unxmlify($xml->guid));
1412 $parent_guid = notags(unxmlify($xml->parent_guid));
1413 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1414 $target_type = notags(unxmlify($xml->target_type));
1415 $text = unxmlify($xml->text);
1416 $author_signature = notags(unxmlify($xml->author_signature));
1418 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1420 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1422 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1426 if(! diaspora_post_allow($importer,$contact, true)) {
1427 logger('diaspora_comment: Ignoring this author.');
1431 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1432 intval($importer['uid']),
1436 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1440 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1441 intval($importer['uid']),
1446 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1449 $person = find_diaspora_person_by_handle($diaspora_handle);
1450 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1454 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1456 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1457 intval($importer['uid']),
1464 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1467 $parent_item = $r[0];
1470 /* How Diaspora performs comment signature checking:
1472 - If an item has been sent by the comment author to the top-level post owner to relay on
1473 to the rest of the contacts on the top-level post, the top-level post owner should check
1474 the author_signature, then create a parent_author_signature before relaying the comment on
1475 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1476 check only the parent_author_signature. Basically, they trust that the top-level post
1477 owner has already verified the authenticity of anything he/she sends out
1478 - In either case, the signature that get checked is the signature created by the person
1482 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1485 if($parent_author_signature) {
1486 // If a parent_author_signature exists, then we've received the comment
1487 // relayed from the top-level post owner. There's no need to check the
1488 // author_signature if the parent_author_signature is valid
1490 $parent_author_signature = base64_decode($parent_author_signature);
1492 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1493 logger('diaspora_comment: top-level owner verification failed.');
1498 // If there's no parent_author_signature, then we've received the comment
1499 // from the comment creator. In that case, the person is commenting on
1500 // our post, so he/she must be a contact of ours and his/her public key
1501 // should be in $msg['key']
1503 $author_signature = base64_decode($author_signature);
1505 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1506 logger('diaspora_comment: comment author verification failed.');
1511 // Phew! Everything checks out. Now create an item.
1513 // Find the original comment author information.
1514 // We need this to make sure we display the comment author
1515 // information (name and avatar) correctly.
1516 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1519 $person = find_diaspora_person_by_handle($diaspora_handle);
1521 if(! is_array($person)) {
1522 logger('diaspora_comment: unable to find author details');
1527 // Fetch the contact id - if we know this contact
1528 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1529 dbesc(normalise_link($person['url'])), intval($importer['uid']));
1532 $network = $r[0]['network'];
1534 $cid = $contact['id'];
1535 $network = NETWORK_DIASPORA;
1538 $body = diaspora2bb($text);
1539 $message_id = $diaspora_handle . ':' . $guid;
1541 $datarray = array();
1543 $datarray['uid'] = $importer['uid'];
1544 $datarray['contact-id'] = $cid;
1545 $datarray['type'] = 'remote-comment';
1546 $datarray['wall'] = $parent_item['wall'];
1547 $datarray['network'] = $network;
1548 $datarray['verb'] = ACTIVITY_POST;
1549 $datarray['gravity'] = GRAVITY_COMMENT;
1550 $datarray['guid'] = $guid;
1551 $datarray['uri'] = $message_id;
1552 $datarray['parent-uri'] = $parent_item['uri'];
1554 // No timestamps for comments? OK, we'll the use current time.
1555 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1556 $datarray['private'] = $parent_item['private'];
1558 $datarray['owner-name'] = $parent_item['owner-name'];
1559 $datarray['owner-link'] = $parent_item['owner-link'];
1560 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1562 $datarray['author-name'] = $person['name'];
1563 $datarray['author-link'] = $person['url'];
1564 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1565 $datarray['body'] = $body;
1566 $datarray["object"] = json_encode($xml);
1567 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1569 // We can't be certain what the original app is if the message is relayed.
1570 if(($parent_item['origin']) && (! $parent_author_signature))
1571 $datarray['app'] = 'Diaspora';
1573 DiasporaFetchGuid($datarray);
1574 $message_id = item_store($datarray);
1576 $datarray['id'] = $message_id;
1579 //q("update item set plink = '%s' where id = %d",
1580 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1581 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1582 // intval($message_id)
1586 // If we are the origin of the parent we store the original signature and notify our followers
1587 if($parent_item['origin']) {
1588 $author_signature_base64 = base64_encode($author_signature);
1589 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
1591 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1592 intval($message_id),
1593 dbesc($signed_data),
1594 dbesc($author_signature_base64),
1595 dbesc($diaspora_handle)
1599 proc_run('php','include/notifier.php','comment-import',$message_id);
1608 function diaspora_conversation($importer,$xml,$msg) {
1612 $guid = notags(unxmlify($xml->guid));
1613 $subject = notags(unxmlify($xml->subject));
1614 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1615 $participant_handles = notags(unxmlify($xml->participant_handles));
1616 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1618 $parent_uri = $diaspora_handle . ':' . $guid;
1620 $messages = $xml->message;
1622 if(! count($messages)) {
1623 logger('diaspora_conversation: empty conversation');
1627 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1629 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1633 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1634 logger('diaspora_conversation: Ignoring this author.');
1638 $conversation = null;
1640 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1641 intval($importer['uid']),
1645 $conversation = $c[0];
1647 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1648 intval($importer['uid']),
1650 dbesc($diaspora_handle),
1651 dbesc(datetime_convert('UTC','UTC',$created_at)),
1652 dbesc(datetime_convert()),
1654 dbesc($participant_handles)
1657 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1658 intval($importer['uid']),
1662 $conversation = $c[0];
1664 if(! $conversation) {
1665 logger('diaspora_conversation: unable to create conversation.');
1669 foreach($messages as $mesg) {
1673 $msg_guid = notags(unxmlify($mesg->guid));
1674 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1675 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1676 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1677 $msg_text = unxmlify($mesg->text);
1678 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1679 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1680 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1681 if($msg_conversation_guid != $guid) {
1682 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1686 $body = diaspora2bb($msg_text);
1687 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1689 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1691 $author_signature = base64_decode($msg_author_signature);
1693 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1698 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1700 if(is_array($person) && x($person,'pubkey'))
1701 $key = $person['pubkey'];
1703 logger('diaspora_conversation: unable to find author details');
1708 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1709 logger('diaspora_conversation: verification failed.');
1713 if($msg_parent_author_signature) {
1714 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1716 $parent_author_signature = base64_decode($msg_parent_author_signature);
1720 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1721 logger('diaspora_conversation: owner verification failed.');
1726 $r = q("select id from mail where `uri` = '%s' limit 1",
1730 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1734 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')",
1735 intval($importer['uid']),
1737 intval($conversation['id']),
1738 dbesc($person['name']),
1739 dbesc($person['photo']),
1740 dbesc($person['url']),
1741 intval($contact['id']),
1748 dbesc($msg_created_at)
1751 q("update conv set updated = '%s' where id = %d",
1752 dbesc(datetime_convert()),
1753 intval($conversation['id'])
1757 'type' => NOTIFY_MAIL,
1758 'notify_flags' => $importer['notify-flags'],
1759 'language' => $importer['language'],
1760 'to_name' => $importer['username'],
1761 'to_email' => $importer['email'],
1762 'uid' =>$importer['uid'],
1763 'item' => array('subject' => $subject, 'body' => $body),
1764 'source_name' => $person['name'],
1765 'source_link' => $person['url'],
1766 'source_photo' => $person['thumb'],
1767 'verb' => ACTIVITY_POST,
1775 function diaspora_message($importer,$xml,$msg) {
1779 $msg_guid = notags(unxmlify($xml->guid));
1780 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1781 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1782 $msg_author_signature = notags(unxmlify($xml->author_signature));
1783 $msg_text = unxmlify($xml->text);
1784 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1785 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1786 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1788 $parent_uri = $msg_diaspora_handle . ':' . $msg_parent_guid;
1790 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1792 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1796 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1797 logger('diaspora_message: Ignoring this author.');
1801 $conversation = null;
1803 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1804 intval($importer['uid']),
1805 dbesc($msg_conversation_guid)
1808 $conversation = $c[0];
1810 logger('diaspora_message: conversation not available.');
1816 $body = diaspora2bb($msg_text);
1817 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1819 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1822 $author_signature = base64_decode($msg_author_signature);
1824 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1825 if(is_array($person) && x($person,'pubkey'))
1826 $key = $person['pubkey'];
1828 logger('diaspora_message: unable to find author details');
1832 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1833 logger('diaspora_message: verification failed.');
1837 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1839 intval($importer['uid'])
1842 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1846 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')",
1847 intval($importer['uid']),
1849 intval($conversation['id']),
1850 dbesc($person['name']),
1851 dbesc($person['photo']),
1852 dbesc($person['url']),
1853 intval($contact['id']),
1854 dbesc($conversation['subject']),
1860 dbesc($msg_created_at)
1863 q("update conv set updated = '%s' where id = %d",
1864 dbesc(datetime_convert()),
1865 intval($conversation['id'])
1871 function diaspora_participation($importer,$xml) {
1872 logger("Unsupported message type 'participation' ".print_r($xml, true));
1875 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1879 logger('diaspora_photo: init',LOGGER_DEBUG);
1881 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1883 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1885 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1887 $guid = notags(unxmlify($xml->guid));
1889 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1891 $public = notags(unxmlify($xml->public));
1893 $created_at = notags(unxmlify($xml_created_at));
1895 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1897 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1899 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1903 if(! diaspora_post_allow($importer,$contact, false)) {
1904 logger('diaspora_photo: Ignoring this author.');
1908 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1909 intval($importer['uid']),
1910 dbesc($status_message_guid)
1913 /* deactivated by now since it can lead to multiplicated pictures in posts.
1915 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1918 $person = find_diaspora_person_by_handle($diaspora_handle);
1919 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1923 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1925 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1926 intval($importer['uid']),
1927 dbesc($status_message_guid)
1934 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1935 intval($importer['uid']),
1936 dbesc(serialize($msg)),
1937 intval($attempt + 1)
1941 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1945 $parent_item = $r[0];
1947 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1949 $link_text = scale_external_images($link_text, true,
1950 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1952 if(strpos($parent_item['body'],$link_text) === false) {
1954 $parent_item['body'] = $link_text . $parent_item['body'];
1956 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1957 dbesc($parent_item['body']),
1958 intval($parent_item['id']),
1959 intval($parent_item['uid'])
1961 put_item_in_cache($parent_item, true);
1962 update_thread($parent_item['id']);
1971 function diaspora_like($importer,$xml,$msg) {
1974 $guid = notags(unxmlify($xml->guid));
1975 $parent_guid = notags(unxmlify($xml->parent_guid));
1976 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1977 $target_type = notags(unxmlify($xml->target_type));
1978 $positive = notags(unxmlify($xml->positive));
1979 $author_signature = notags(unxmlify($xml->author_signature));
1981 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1983 // likes on comments not supported here and likes on photos not supported by Diaspora
1985 // if($target_type !== 'Post')
1988 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1990 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1994 if(! diaspora_post_allow($importer,$contact, false)) {
1995 logger('diaspora_like: Ignoring this author.');
1999 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2000 intval($importer['uid']),
2005 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
2008 $person = find_diaspora_person_by_handle($diaspora_handle);
2009 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
2013 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
2015 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2016 intval($importer['uid']),
2023 logger('diaspora_like: parent item not found: ' . $guid);
2027 $parent_item = $r[0];
2029 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2030 intval($importer['uid']),
2034 if($positive === 'true') {
2035 logger('diaspora_like: duplicate like: ' . $guid);
2038 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2039 // It looks like "RelayableRetractions" are used for "unlike" instead
2040 if($positive === 'false') {
2041 logger('diaspora_like: received a like with positive set to "false"...ignoring');
2042 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2043 intval($r[0]['id']),
2044 intval($importer['uid'])
2046 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2047 // send notification via proc_run()
2051 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2052 // It looks like "RelayableRetractions" are used for "unlike" instead
2053 if($positive === 'false') {
2054 logger('diaspora_like: received a like with positive set to "false"');
2055 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2060 /* How Diaspora performs "like" signature checking:
2062 - If an item has been sent by the like author to the top-level post owner to relay on
2063 to the rest of the contacts on the top-level post, the top-level post owner should check
2064 the author_signature, then create a parent_author_signature before relaying the like on
2065 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2066 check only the parent_author_signature. Basically, they trust that the top-level post
2067 owner has already verified the authenticity of anything he/she sends out
2068 - In either case, the signature that get checked is the signature created by the person
2072 // Diaspora has changed the way they are signing the likes.
2073 // Just to make sure that we don't miss any likes we will check the old and the current way.
2074 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2076 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2080 if ($parent_author_signature) {
2081 // If a parent_author_signature exists, then we've received the like
2082 // relayed from the top-level post owner. There's no need to check the
2083 // author_signature if the parent_author_signature is valid
2085 $parent_author_signature = base64_decode($parent_author_signature);
2087 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2088 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2090 logger('diaspora_like: top-level owner verification failed.');
2094 // If there's no parent_author_signature, then we've received the like
2095 // from the like creator. In that case, the person is "like"ing
2096 // our post, so he/she must be a contact of ours and his/her public key
2097 // should be in $msg['key']
2099 $author_signature = base64_decode($author_signature);
2101 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2102 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2104 logger('diaspora_like: like creator verification failed.');
2109 // Phew! Everything checks out. Now create an item.
2111 // Find the original comment author information.
2112 // We need this to make sure we display the comment author
2113 // information (name and avatar) correctly.
2114 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2117 $person = find_diaspora_person_by_handle($diaspora_handle);
2119 if(! is_array($person)) {
2120 logger('diaspora_like: unable to find author details');
2125 $uri = $diaspora_handle . ':' . $guid;
2127 $activity = ACTIVITY_LIKE;
2128 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2129 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2130 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2131 $body = $parent_item['body'];
2136 <type>$objtype</type>
2138 <id>{$parent_item['uri']}</id>
2141 <content>$body</content>
2144 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2146 // Fetch the contact id - if we know this contact
2147 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
2148 dbesc(normalise_link($person['url'])), intval($importer['uid']));
2151 $network = $r[0]['network'];
2153 $cid = $contact['id'];
2154 $network = NETWORK_DIASPORA;
2160 $arr['uid'] = $importer['uid'];
2161 $arr['guid'] = $guid;
2162 $arr['network'] = $network;
2163 $arr['contact-id'] = $cid;
2164 $arr['type'] = 'activity';
2165 $arr['wall'] = $parent_item['wall'];
2166 $arr['gravity'] = GRAVITY_LIKE;
2167 $arr['parent'] = $parent_item['id'];
2168 $arr['parent-uri'] = $parent_item['uri'];
2170 $arr['owner-name'] = $parent_item['name'];
2171 $arr['owner-link'] = $parent_item['url'];
2172 //$arr['owner-avatar'] = $parent_item['thumb'];
2173 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2175 $arr['author-name'] = $person['name'];
2176 $arr['author-link'] = $person['url'];
2177 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2179 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2180 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2181 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2182 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2183 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2185 $arr['app'] = 'Diaspora';
2187 $arr['private'] = $parent_item['private'];
2188 $arr['verb'] = $activity;
2189 $arr['object-type'] = $objtype;
2190 $arr['object'] = $obj;
2191 $arr['visible'] = 1;
2193 $arr['last-child'] = 0;
2195 $message_id = item_store($arr);
2199 // q("update item set plink = '%s' where id = %d",
2200 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2201 // dbesc($a->get_baseurl().'/display/'.$guid),
2202 // intval($message_id)
2206 // If we are the origin of the parent we store the original signature and notify our followers
2207 if($parent_item['origin']) {
2208 $author_signature_base64 = base64_encode($author_signature);
2209 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
2211 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2212 intval($message_id),
2213 dbesc($signed_data),
2214 dbesc($author_signature_base64),
2215 dbesc($diaspora_handle)
2219 proc_run('php','include/notifier.php','comment-import',$message_id);
2225 function diaspora_retraction($importer,$xml) {
2228 $guid = notags(unxmlify($xml->guid));
2229 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2230 $type = notags(unxmlify($xml->type));
2232 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2236 if($type === 'Person') {
2237 require_once('include/Contact.php');
2238 contact_remove($contact['id']);
2239 } elseif($type === 'StatusMessage') {
2240 $guid = notags(unxmlify($xml->post_guid));
2242 $r = q("SELECT * FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2244 intval($importer['uid'])
2247 if(link_compare($r[0]['author-link'],$contact['url'])) {
2248 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
2249 dbesc(datetime_convert()),
2252 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2255 } elseif($type === 'Post') {
2256 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2258 intval($importer['uid'])
2261 if(link_compare($r[0]['author-link'],$contact['url'])) {
2262 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2263 dbesc(datetime_convert()),
2266 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2275 function diaspora_signed_retraction($importer,$xml,$msg) {
2278 $guid = notags(unxmlify($xml->target_guid));
2279 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2280 $type = notags(unxmlify($xml->target_type));
2281 $sig = notags(unxmlify($xml->target_author_signature));
2283 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2285 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2287 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2292 $signed_data = $guid . ';' . $type ;
2295 /* How Diaspora performs relayable_retraction signature checking:
2297 - If an item has been sent by the item author to the top-level post owner to relay on
2298 to the rest of the contacts on the top-level post, the top-level post owner checks
2299 the author_signature, then creates a parent_author_signature before relaying the item on
2300 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2301 check only the parent_author_signature. Basically, they trust that the top-level post
2302 owner has already verified the authenticity of anything he/she sends out
2303 - In either case, the signature that get checked is the signature created by the person
2307 if($parent_author_signature) {
2309 $parent_author_signature = base64_decode($parent_author_signature);
2311 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2312 logger('diaspora_signed_retraction: top-level post owner verification failed');
2318 $sig_decode = base64_decode($sig);
2320 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2321 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2326 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2327 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2329 intval($importer['uid'])
2332 if(link_compare($r[0]['author-link'],$contact['url'])) {
2333 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2334 dbesc(datetime_convert()),
2335 dbesc(datetime_convert()),
2338 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2340 // Now check if the retraction needs to be relayed by us
2342 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2343 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2344 // The only item with `parent` and `id` as the parent id is the parent item.
2345 $p = q("SELECT `origin` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2346 intval($r[0]['parent']),
2347 intval($r[0]['parent'])
2350 if($p[0]['origin']) {
2351 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2353 dbesc($signed_data),
2355 dbesc($diaspora_handle)
2358 // the existence of parent_author_signature would have meant the parent_author or owner
2359 // is already relaying.
2360 logger('diaspora_signed_retraction: relaying relayable_retraction');
2362 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2369 logger('diaspora_signed_retraction: unknown type: ' . $type);
2375 function diaspora_profile($importer,$xml,$msg) {
2378 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2381 if($diaspora_handle != $msg['author']) {
2382 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2386 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2390 //if($contact['blocked']) {
2391 // logger('diaspora_post: Ignoring this author.');
2395 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2396 $image_url = unxmlify($xml->image_url);
2397 $birthday = unxmlify($xml->birthday);
2398 $location = diaspora2bb(unxmlify($xml->location));
2399 $about = diaspora2bb(unxmlify($xml->bio));
2400 $gender = unxmlify($xml->gender);
2401 $searchable = (unxmlify($xml->searchable) == "true");
2402 $nsfw = (unxmlify($xml->nsfw) == "true");
2403 $tags = unxmlify($xml->tag_string);
2405 $tags = explode("#", $tags);
2407 $keywords = array();
2408 foreach ($tags as $tag) {
2409 $tag = trim(strtolower($tag));
2414 $keywords = implode(", ", $keywords);
2416 $handle_parts = explode("@", $diaspora_handle);
2417 $nick = $handle_parts[0];
2420 $name = $handle_parts[0];
2423 if( preg_match("|^https?://|", $image_url) === 0) {
2424 $image_url = "http://" . $handle_parts[1] . $image_url;
2427 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2428 intval($importer['uid']),
2429 intval($contact['id'])
2431 $oldphotos = ((count($r)) ? $r : null);*/
2433 require_once('include/Photo.php');
2435 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2437 // Generic birthday. We don't know the timezone. The year is irrelevant.
2439 $birthday = str_replace('1000','1901',$birthday);
2441 if ($birthday != "")
2442 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2444 // this is to prevent multiple birthday notifications in a single year
2445 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2447 if(substr($birthday,5) === substr($contact['bd'],5))
2448 $birthday = $contact['bd'];
2450 /// @TODO Update name on item['author-name'] if the name changed. See consume_feed()
2451 /// (Not doing this currently because D* protocol is scheduled for revision soon).
2453 $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",
2456 dbesc($diaspora_handle),
2457 dbesc(datetime_convert()),
2461 dbesc(datetime_convert()),
2467 intval($contact['id']),
2468 intval($importer['uid'])
2472 require_once('include/socgraph.php');
2473 poco_check($contact['url'], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
2474 datetime_convert(), 2, $contact['id'], $importer['uid']);
2477 update_gcontact(array("url" => $contact['url'], "network" => NETWORK_DIASPORA, "generation" => 2,
2478 "photo" => $image_url, "name" => $name, "location" => $location,
2479 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2480 "addr" => $diaspora_handle, "nick" => $nick, "keywords" => $keywords,
2481 "hide" => !$searchable, "nsfw" => $nsfw));
2485 foreach($oldphotos as $ph) {
2486 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2487 intval($importer['uid']),
2488 intval($contact['id']),
2489 dbesc($ph['resource-id'])
2499 function diaspora_share($me,$contact) {
2501 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2502 $theiraddr = $contact['addr'];
2504 $tpl = get_markup_template('diaspora_share.tpl');
2505 $msg = replace_macros($tpl, array(
2506 '$sender' => $myaddr,
2507 '$recipient' => $theiraddr
2510 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2511 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2513 return(diaspora_transmit($owner,$contact,$slap, false));
2516 function diaspora_unshare($me,$contact) {
2519 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2521 $tpl = get_markup_template('diaspora_retract.tpl');
2522 $msg = replace_macros($tpl, array(
2523 '$guid' => $me['guid'],
2524 '$type' => 'Person',
2525 '$handle' => $myaddr
2528 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2529 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2531 return(diaspora_transmit($owner,$contact,$slap, false));
2536 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2539 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2540 $theiraddr = $contact['addr'];
2544 $title = $item['title'];
2545 $body = $item['body'];
2548 // We're trying to match Diaspora's split message/photo protocol but
2549 // all the photos are displayed on D* as links and not img's - even
2550 // though we're sending pretty much precisely what they send us when
2551 // doing the same operation.
2552 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2553 // which seems to get through intact.
2555 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2557 foreach($matches as $mtch) {
2559 $detail['str'] = $mtch[0];
2560 $detail['path'] = dirname($mtch[1]) . '/';
2561 $detail['file'] = basename($mtch[1]);
2562 $detail['guid'] = $item['guid'];
2563 $detail['handle'] = $myaddr;
2564 $images[] = $detail;
2565 $body = str_replace($detail['str'],$mtch[1],$body);
2570 //if(strlen($title))
2571 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2573 // convert to markdown
2574 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2575 //$body = bb2diaspora($body);
2579 $body = "## ".html_entity_decode($title)."\n\n".$body;
2581 if($item['attach']) {
2582 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2584 $body .= "\n" . t('Attachments:') . "\n";
2585 foreach($matches as $mtch) {
2586 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2592 $public = (($item['private']) ? 'false' : 'true');
2594 require_once('include/datetime.php');
2595 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2597 // Detect a share element and do a reshare
2598 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2599 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2600 $tpl = get_markup_template('diaspora_reshare.tpl');
2601 $msg = replace_macros($tpl, array(
2602 '$root_handle' => xmlify($ret['root_handle']),
2603 '$root_guid' => $ret['root_guid'],
2604 '$guid' => $item['guid'],
2605 '$handle' => xmlify($myaddr),
2606 '$public' => $public,
2607 '$created' => $created,
2608 '$provider' => $item["app"]
2611 $tpl = get_markup_template('diaspora_post.tpl');
2612 $msg = replace_macros($tpl, array(
2614 '$guid' => $item['guid'],
2615 '$handle' => xmlify($myaddr),
2616 '$public' => $public,
2617 '$created' => $created,
2618 '$provider' => $item["app"]
2622 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2623 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2625 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2626 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2628 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']);
2630 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2632 if(count($images)) {
2633 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2636 return $return_code;
2639 function diaspora_is_reshare($body) {
2640 $body = trim($body);
2642 // Skip if it isn't a pure repeated messages
2643 // Does it start with a share?
2644 if (strpos($body, "[share") > 0)
2647 // Does it end with a share?
2648 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2651 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2652 // Skip if there is no shared message in there
2653 if ($body == $attributes)
2657 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2658 if ($matches[1] != "")
2659 $guid = $matches[1];
2661 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2662 if ($matches[1] != "")
2663 $guid = $matches[1];
2666 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2667 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2670 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2671 $ret["root_guid"] = $guid;
2677 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2678 if ($matches[1] != "")
2679 $profile = $matches[1];
2681 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2682 if ($matches[1] != "")
2683 $profile = $matches[1];
2687 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2688 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2692 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2693 if ($matches[1] != "")
2694 $link = $matches[1];
2696 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2697 if ($matches[1] != "")
2698 $link = $matches[1];
2700 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2701 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2707 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2709 if(! count($images))
2711 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2713 $tpl = get_markup_template('diaspora_photo.tpl');
2714 foreach($images as $image) {
2715 if(! stristr($image['path'],$mysite))
2717 $resource = str_replace('.jpg','',$image['file']);
2718 $resource = substr($resource,0,strpos($resource,'-'));
2720 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2722 intval($owner['uid'])
2726 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2727 $msg = replace_macros($tpl,array(
2728 '$path' => xmlify($image['path']),
2729 '$filename' => xmlify($image['file']),
2730 '$msg_guid' => xmlify($image['guid']),
2731 '$guid' => xmlify($r[0]['guid']),
2732 '$handle' => xmlify($image['handle']),
2733 '$public' => xmlify($public),
2734 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2738 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2739 logger('send guid '.$r[0]['guid'], LOGGER_DEBUG);
2741 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2742 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2744 diaspora_transmit($owner,$contact,$slap,$public_batch,false,$r[0]['guid']);
2749 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2752 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2753 // $theiraddr = $contact['addr'];
2755 // Diaspora doesn't support threaded comments, but some
2756 // versions of Diaspora (i.e. Diaspora-pistos) support
2757 // likes on comments
2758 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2759 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2760 dbesc($item['thr-parent'])
2764 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2765 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2766 // The only item with `parent` and `id` as the parent id is the parent item.
2767 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2768 intval($item['parent']),
2769 intval($item['parent'])
2777 if($item['verb'] === ACTIVITY_LIKE) {
2778 $tpl = get_markup_template('diaspora_like.tpl');
2780 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2781 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2782 // $positive = (($item['deleted']) ? 'false' : 'true');
2785 if(($item['deleted']))
2786 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2789 $tpl = get_markup_template('diaspora_comment.tpl');
2793 $text = html_entity_decode(bb2diaspora($item['body']));
2798 $signed_text = $positive . ';' . $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $myaddr;
2800 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2802 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2804 $msg = replace_macros($tpl,array(
2805 '$guid' => xmlify($item['guid']),
2806 '$parent_guid' => xmlify($parent['guid']),
2807 '$target_type' =>xmlify($target_type),
2808 '$authorsig' => xmlify($authorsig),
2809 '$body' => xmlify($text),
2810 '$positive' => xmlify($positive),
2811 '$handle' => xmlify($myaddr)
2814 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2815 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2817 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2818 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2820 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2824 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2828 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2829 // $theiraddr = $contact['addr'];
2831 // Diaspora doesn't support threaded comments, but some
2832 // versions of Diaspora (i.e. Diaspora-pistos) support
2833 // likes on comments
2834 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2835 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2836 dbesc($item['thr-parent'])
2840 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2841 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2842 // The only item with `parent` and `id` as the parent id is the parent item.
2843 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2844 intval($item['parent']),
2845 intval($item['parent'])
2854 $relay_retract = false;
2855 $sql_sign_id = 'iid';
2856 if( $item['deleted']) {
2857 $relay_retract = true;
2859 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2861 $sql_sign_id = 'retract_iid';
2862 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2864 elseif($item['verb'] === ACTIVITY_LIKE) {
2867 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2868 // $positive = (($item['deleted']) ? 'false' : 'true');
2871 $tpl = get_markup_template('diaspora_like_relay.tpl');
2873 else { // item is a comment
2874 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2878 // fetch the original signature if the relayable was created by a Diaspora
2879 // or DFRN user. Relayables for other networks are not supported.
2881 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE " . $sql_sign_id . " = %d LIMIT 1",
2886 $signed_text = $orig_sign['signed_text'];
2887 $authorsig = $orig_sign['signature'];
2888 $handle = $orig_sign['signer'];
2890 // Split the signed text
2891 $signed_parts = explode(";", $signed_text);
2893 // Remove the parent guid
2894 array_shift($signed_parts);
2896 // Remove the comment guid
2897 array_shift($signed_parts);
2899 // Remove the handle
2900 array_pop($signed_parts);
2902 // Glue the parts together
2903 $text = implode(";", $signed_parts);
2906 // This part is meant for cases where we don't have the signatur. (Which shouldn't happen with posts from Diaspora and Friendica)
2907 // This means that the comment won't be accepted by newer Diaspora servers
2909 $body = $item['body'];
2910 $text = html_entity_decode(bb2diaspora($body));
2912 $handle = diaspora_handle_from_contact($item['contact-id']);
2917 $signed_text = $item['guid'] . ';' . $target_type;
2919 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2921 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2923 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2926 // Sign the relayable with the top-level owner's signature
2927 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2929 $msg = replace_macros($tpl,array(
2930 '$guid' => xmlify($item['guid']),
2931 '$parent_guid' => xmlify($parent['guid']),
2932 '$target_type' =>xmlify($target_type),
2933 '$authorsig' => xmlify($authorsig),
2934 '$parentsig' => xmlify($parentauthorsig),
2935 '$body' => xmlify($text),
2936 '$positive' => xmlify($positive),
2937 '$handle' => xmlify($handle)
2940 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2941 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2943 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2944 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2946 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2952 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2955 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2957 // Check whether the retraction is for a top-level post or whether it's a relayable
2958 if( $item['uri'] !== $item['parent-uri'] ) {
2960 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2961 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2965 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2966 $target_type = 'StatusMessage';
2969 $signed_text = $item['guid'] . ';' . $target_type;
2971 $msg = replace_macros($tpl, array(
2972 '$guid' => xmlify($item['guid']),
2973 '$type' => xmlify($target_type),
2974 '$handle' => xmlify($myaddr),
2975 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2978 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2980 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2981 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2983 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2986 function diaspora_send_mail($item,$owner,$contact) {
2989 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2991 $r = q("select * from conv where id = %d and uid = %d limit 1",
2992 intval($item['convid']),
2993 intval($item['uid'])
2997 logger('diaspora_send_mail: conversation not found.');
3003 'guid' => xmlify($cnv['guid']),
3004 'subject' => xmlify($cnv['subject']),
3005 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
3006 'diaspora_handle' => xmlify($cnv['creator']),
3007 'participant_handles' => xmlify($cnv['recips'])
3010 $body = bb2diaspora($item['body']);
3011 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
3013 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
3014 . $created . ';' . $myaddr . ';' . $cnv['guid'];
3016 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
3019 'guid' => xmlify($item['guid']),
3020 'parent_guid' => xmlify($cnv['guid']),
3021 'parent_author_signature' => xmlify($sig),
3022 'author_signature' => xmlify($sig),
3023 'text' => xmlify($body),
3024 'created_at' => xmlify($created),
3025 'diaspora_handle' => xmlify($myaddr),
3026 'conversation_guid' => xmlify($cnv['guid'])
3029 if($item['reply']) {
3030 $tpl = get_markup_template('diaspora_message.tpl');
3031 $xmsg = replace_macros($tpl, array('$msg' => $msg));
3034 $conv['messages'] = array($msg);
3035 $tpl = get_markup_template('diaspora_conversation.tpl');
3036 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3039 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3040 logger('send guid '.$item['guid'], LOGGER_DEBUG);
3042 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3043 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3045 return(diaspora_transmit($owner,$contact,$slap,false,false,$item['guid']));
3050 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false,$guid = "") {
3052 $enabled = intval(get_config('system','diaspora_enabled'));
3058 $logid = random_string(4);
3059 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3061 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3065 logger('diaspora_transmit: '.$logid.'-'.$guid.' '.$dest_url);
3067 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3071 if (!intval(get_config('system','diaspora_test'))) {
3072 post_url($dest_url . '/', $slap);
3073 $return_code = $a->get_curl_code();
3075 logger('diaspora_transmit: test_mode');
3080 logger('diaspora_transmit: '.$logid.'-'.$guid.' returns: '.$return_code);
3082 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3083 logger('diaspora_transmit: queue message');
3085 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3086 intval($contact['id']),
3087 dbesc(NETWORK_DIASPORA),
3089 intval($public_batch)
3092 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3095 // queue message for redelivery
3096 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3101 return(($return_code) ? $return_code : (-1));
3104 function diaspora_fetch_relay() {
3106 $serverdata = get_config("system", "relay_server");
3107 if ($serverdata == "")
3112 $servers = explode(",", $serverdata);
3114 foreach($servers AS $server) {
3115 $server = trim($server);
3116 $batch = $server."/receive/public";
3118 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3121 $addr = "relay@".str_replace("http://", "", normalise_link($server));
3123 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
3124 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
3129 dbesc(normalise_link($server)),
3131 dbesc(NETWORK_DIASPORA),
3132 intval(CONTACT_IS_FOLLOWER),
3133 dbesc(datetime_convert()),
3134 dbesc(datetime_convert()),
3135 dbesc(datetime_convert())
3138 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3140 $relay[] = $relais[0];
3142 $relay[] = $relais[0];