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 update_contact_avatar($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 `rel` = %d,
751 intval($new_relation),
752 dbesc(datetime_convert()),
753 dbesc(datetime_convert()),
754 intval($contact_record['id'])
757 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
759 $ret = diaspora_share($u[0],$contact_record);
765 function diaspora_post_allow($importer,$contact, $is_comment = false) {
767 // perhaps we were already sharing with this person. Now they're sharing with us.
768 // That makes us friends.
769 // Normally this should have handled by getting a request - but this could get lost
770 if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
771 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
772 intval(CONTACT_IS_FRIEND),
773 intval($contact['id']),
774 intval($importer['uid'])
776 $contact['rel'] = CONTACT_IS_FRIEND;
777 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
780 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
782 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
784 if($contact['rel'] == CONTACT_IS_FOLLOWER)
785 if(($importer['page-flags'] == PAGE_COMMUNITY) OR $is_comment)
788 // Messages for the global users are always accepted
789 if ($importer['uid'] == 0)
795 function diaspora_is_redmatrix($url) {
796 return(strstr($url, "/channel/"));
799 function diaspora_plink($addr, $guid) {
800 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
804 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
806 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
807 // So we try another way as well.
808 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
810 $r[0]["network"] = $s[0]["network"];
812 if ($r[0]["network"] == NETWORK_DFRN)
813 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
815 if (diaspora_is_redmatrix($r[0]["url"]))
816 return $r[0]["url"]."/?f=&mid=".$guid;
818 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
821 function diaspora_repair_signature($signature, $handle = "", $level = 1) {
823 if ($signature == "")
826 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
827 $signature = base64_decode($signature);
828 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
830 // Do a recursive call to be able to fix even multiple levels
832 $signature = diaspora_repair_signature($signature, $handle, ++$level);
838 function diaspora_post($importer,$xml,$msg) {
841 $guid = notags(unxmlify($xml->guid));
842 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
844 if($diaspora_handle != $msg['author']) {
845 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
849 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
851 logger('diaspora_post: A Contact for handle '.$diaspora_handle.' and user '.$importer['uid'].' was not found');
855 if(! diaspora_post_allow($importer,$contact, false)) {
856 logger('diaspora_post: Ignoring this author.');
860 $message_id = $diaspora_handle . ':' . $guid;
861 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
862 intval($importer['uid']),
866 logger('diaspora_post: message exists: ' . $guid);
870 $created = unxmlify($xml->created_at);
871 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
873 $body = diaspora2bb($xml->raw_message);
877 $datarray["object"] = json_encode($xml);
879 if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
880 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
882 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
883 // Add OEmbed and other information to the body
884 if (!diaspora_is_redmatrix($contact['url']))
885 $body = add_page_info_to_body($body, false, true);
890 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
892 foreach($matches as $mtch) {
893 if(strlen($str_tags))
895 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
899 $plink = diaspora_plink($diaspora_handle, $guid);
901 $datarray['uid'] = $importer['uid'];
902 $datarray['contact-id'] = $contact['id'];
903 $datarray['wall'] = 0;
904 $datarray['network'] = NETWORK_DIASPORA;
905 $datarray['verb'] = ACTIVITY_POST;
906 $datarray['guid'] = $guid;
907 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
908 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
909 $datarray['private'] = $private;
910 $datarray['parent'] = 0;
911 $datarray['plink'] = $plink;
912 $datarray['owner-name'] = $contact['name'];
913 $datarray['owner-link'] = $contact['url'];
914 //$datarray['owner-avatar'] = $contact['thumb'];
915 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
916 $datarray['author-name'] = $contact['name'];
917 $datarray['author-link'] = $contact['url'];
918 $datarray['author-avatar'] = $contact['thumb'];
919 $datarray['body'] = $body;
920 $datarray['tag'] = $str_tags;
921 if ($xml->provider_display_name)
922 $datarray["app"] = unxmlify($xml->provider_display_name);
924 $datarray['app'] = 'Diaspora';
926 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
928 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
930 DiasporaFetchGuid($datarray);
931 $message_id = item_store($datarray);
933 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
939 function DiasporaFetchGuid($item) {
940 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
941 function ($match) use ($item){
942 return(DiasporaFetchGuidSub($match, $item));
946 function DiasporaFetchGuidSub($match, $item) {
949 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
950 diaspora_store_by_guid($match[1], $item["owner-link"]);
953 function diaspora_store_by_guid($guid, $server, $uid = 0) {
954 require_once("include/Contact.php");
956 $serverparts = parse_url($server);
957 $server = $serverparts["scheme"]."://".$serverparts["host"];
959 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
961 $item = diaspora_fetch_message($guid, $server);
966 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
968 $body = $item["body"];
969 $str_tags = $item["tag"];
971 $created = $item["created"];
972 $author = $item["author"];
973 $guid = $item["guid"];
974 $private = $item["private"];
975 $object = $item["object"];
976 $objecttype = $item["object-type"];
978 $message_id = $author.':'.$guid;
979 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
986 $person = find_diaspora_person_by_handle($author);
988 $contact_id = get_contact($person['url'], $uid);
990 $contacts = q("SELECT * FROM `contact` WHERE `id` = %d", intval($contact_id));
991 $importers = q("SELECT * FROM `user` WHERE `uid` = %d", intval($uid));
993 if ($contacts AND $importers)
994 if(!diaspora_post_allow($importers[0],$contacts[0], false)) {
995 logger('Ignoring author '.$person['url'].' for uid '.$uid);
998 logger('Author '.$person['url'].' is allowed for uid '.$uid);
1000 $datarray = array();
1001 $datarray['uid'] = $uid;
1002 $datarray['contact-id'] = $contact_id;
1003 $datarray['wall'] = 0;
1004 $datarray['network'] = NETWORK_DIASPORA;
1005 $datarray['guid'] = $guid;
1006 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1007 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1008 $datarray['private'] = $private;
1009 $datarray['parent'] = 0;
1010 $datarray['plink'] = diaspora_plink($author, $guid);
1011 $datarray['author-name'] = $person['name'];
1012 $datarray['author-link'] = $person['url'];
1013 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1014 $datarray['owner-name'] = $datarray['author-name'];
1015 $datarray['owner-link'] = $datarray['author-link'];
1016 $datarray['owner-avatar'] = $datarray['author-avatar'];
1017 $datarray['body'] = $body;
1018 $datarray['tag'] = $str_tags;
1019 $datarray['app'] = $app;
1020 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1021 $datarray['object'] = $object;
1022 $datarray['object-type'] = $objecttype;
1024 if ($datarray['contact-id'] == 0)
1027 DiasporaFetchGuid($datarray);
1028 $message_id = item_store($datarray);
1031 /// Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
1036 function diaspora_fetch_message($guid, $server, $level = 0) {
1043 // This will not work if the server is not a Diaspora server
1044 $source_url = $server.'/p/'.$guid.'.xml';
1045 $x = fetch_url($source_url);
1049 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1050 $source_xml = parse_xml_string($x,false);
1053 $item["app"] = 'Diaspora';
1054 $item["guid"] = $guid;
1057 if ($source_xml->post->status_message->created_at)
1058 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1060 if ($source_xml->post->status_message->provider_display_name)
1061 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1063 if ($source_xml->post->status_message->diaspora_handle)
1064 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1066 if ($source_xml->post->status_message->guid)
1067 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1069 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1070 $item["object"] = json_encode($source_xml->post);
1072 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1073 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1074 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1075 $body = scale_external_images($body,false);
1076 } elseif($source_xml->post->asphoto->image_url) {
1077 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1078 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1079 $body = scale_external_images($body);
1080 } elseif($source_xml->post->status_message) {
1081 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1083 // Checking for embedded pictures
1084 if($source_xml->post->status_message->photo->remote_photo_path AND
1085 $source_xml->post->status_message->photo->remote_photo_name) {
1087 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1089 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1090 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1092 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1094 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1096 $item["object-type"] = ACTIVITY_OBJ_NOTE;
1098 $body = scale_external_images($body);
1100 // Add OEmbed and other information to the body
1101 /// @TODO It could be a repeated redmatrix item
1102 /// Then we shouldn't add further data to it
1103 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1104 $body = add_page_info_to_body($body, false, true);
1106 } elseif($source_xml->post->reshare) {
1107 // Reshare of a reshare
1108 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1110 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1111 logger('no content found: '.print_r($source_xml,true));
1115 if (trim($body) == "")
1119 $item["body"] = $body;
1124 function diaspora_reshare($importer,$xml,$msg) {
1126 logger('diaspora_reshare: init: ' . print_r($xml,true));
1129 $guid = notags(unxmlify($xml->guid));
1130 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1133 if($diaspora_handle != $msg['author']) {
1134 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1138 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1142 if(! diaspora_post_allow($importer,$contact, false)) {
1143 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1147 $message_id = $diaspora_handle . ':' . $guid;
1148 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1149 intval($importer['uid']),
1153 logger('diaspora_reshare: message exists: ' . $guid);
1157 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1158 $orig_guid = notags(unxmlify($xml->root_guid));
1159 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1161 $create_original_post = false;
1163 // Do we already have this item?
1164 $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",
1166 dbesc(NETWORK_DIASPORA)
1169 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1171 // Maybe it is already a reshared item?
1172 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1173 require_once('include/api.php');
1174 if (api_share_as_retweet($r[0]))
1177 $body = $r[0]["body"];
1178 $str_tags = $r[0]["tag"];
1179 $app = $r[0]["app"];
1180 $orig_created = $r[0]["created"];
1181 $orig_plink = $r[0]["plink"];
1182 $orig_uri = $r[0]["uri"];
1183 $object = $r[0]["object"];
1184 $objecttype = $r[0]["object-type"];
1193 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1194 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1195 $item = diaspora_fetch_message($orig_guid, $server);
1198 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1199 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1200 $item = diaspora_fetch_message($orig_guid, $server);
1203 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1204 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1205 $item = diaspora_fetch_message($orig_guid, $server);
1208 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1209 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1210 $item = diaspora_fetch_message($orig_guid, $server);
1214 $body = $item["body"];
1215 $str_tags = $item["tag"];
1216 $app = $item["app"];
1217 $orig_created = $item["created"];
1218 $orig_author = $item["author"];
1219 $orig_guid = $item["guid"];
1220 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1221 $orig_uri = $orig_author.':'.$orig_guid;
1222 $create_original_post = ($body != "");
1223 $object = $item["object"];
1224 $objecttype = $item["object-type"];
1228 $plink = diaspora_plink($diaspora_handle, $guid);
1230 $person = find_diaspora_person_by_handle($orig_author);
1232 $created = unxmlify($xml->created_at);
1233 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1235 $datarray = array();
1237 $datarray['uid'] = $importer['uid'];
1238 $datarray['contact-id'] = $contact['id'];
1239 $datarray['wall'] = 0;
1240 $datarray['network'] = NETWORK_DIASPORA;
1241 $datarray['guid'] = $guid;
1242 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1243 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1244 $datarray['private'] = $private;
1245 $datarray['parent'] = 0;
1246 $datarray['plink'] = $plink;
1247 $datarray['owner-name'] = $contact['name'];
1248 $datarray['owner-link'] = $contact['url'];
1249 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1250 if (!intval(get_config('system','wall-to-wall_share'))) {
1251 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1253 $datarray['author-name'] = $contact['name'];
1254 $datarray['author-link'] = $contact['url'];
1255 $datarray['author-avatar'] = $contact['thumb'];
1256 $datarray['body'] = $prefix.$body."[/share]";
1258 // Let reshared messages look like wall-to-wall posts
1259 $datarray['author-name'] = $person['name'];
1260 $datarray['author-link'] = $person['url'];
1261 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1262 $datarray['body'] = $body;
1265 $datarray["object"] = json_encode($xml);
1266 $datarray['object-type'] = $objecttype;
1268 $datarray['tag'] = $str_tags;
1269 $datarray['app'] = $app;
1271 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1272 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1274 // Store the original item of a reshare
1275 if ($create_original_post) {
1276 require_once("include/Contact.php");
1278 $datarray2 = $datarray;
1280 $datarray2['uid'] = 0;
1281 $datarray2['contact-id'] = get_contact($person['url'], 0);
1282 $datarray2['guid'] = $orig_guid;
1283 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1284 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1285 $datarray2['parent'] = 0;
1286 $datarray2['plink'] = $orig_plink;
1288 $datarray2['author-name'] = $person['name'];
1289 $datarray2['author-link'] = $person['url'];
1290 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1291 $datarray2['owner-name'] = $datarray2['author-name'];
1292 $datarray2['owner-link'] = $datarray2['author-link'];
1293 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1294 $datarray2['body'] = $body;
1295 $datarray2["object"] = $object;
1297 DiasporaFetchGuid($datarray2);
1298 $message_id = item_store($datarray2);
1300 logger("Store original item ".$orig_guid." under message id ".$message_id);
1303 DiasporaFetchGuid($datarray);
1304 $message_id = item_store($datarray);
1311 function diaspora_asphoto($importer,$xml,$msg) {
1312 logger('diaspora_asphoto called');
1315 $guid = notags(unxmlify($xml->guid));
1316 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1318 if($diaspora_handle != $msg['author']) {
1319 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1323 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1327 if(! diaspora_post_allow($importer,$contact, false)) {
1328 logger('diaspora_asphoto: Ignoring this author.');
1332 $message_id = $diaspora_handle . ':' . $guid;
1333 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1334 intval($importer['uid']),
1338 logger('diaspora_asphoto: message exists: ' . $guid);
1342 $created = unxmlify($xml->created_at);
1343 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1345 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1346 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1347 $body = scale_external_images($body,false);
1349 elseif($xml->image_url) {
1350 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1351 $body = scale_external_images($body);
1354 logger('diaspora_asphoto: no photo url found.');
1358 $plink = diaspora_plink($diaspora_handle, $guid);
1360 $datarray = array();
1362 $datarray['uid'] = $importer['uid'];
1363 $datarray['contact-id'] = $contact['id'];
1364 $datarray['wall'] = 0;
1365 $datarray['network'] = NETWORK_DIASPORA;
1366 $datarray['guid'] = $guid;
1367 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1368 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1369 $datarray['private'] = $private;
1370 $datarray['parent'] = 0;
1371 $datarray['plink'] = $plink;
1372 $datarray['owner-name'] = $contact['name'];
1373 $datarray['owner-link'] = $contact['url'];
1374 //$datarray['owner-avatar'] = $contact['thumb'];
1375 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1376 $datarray['author-name'] = $contact['name'];
1377 $datarray['author-link'] = $contact['url'];
1378 $datarray['author-avatar'] = $contact['thumb'];
1379 $datarray['body'] = $body;
1380 $datarray["object"] = json_encode($xml);
1381 $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1383 $datarray['app'] = 'Diaspora/Cubbi.es';
1385 DiasporaFetchGuid($datarray);
1386 $message_id = item_store($datarray);
1389 // q("update item set plink = '%s' where id = %d",
1390 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1391 // intval($message_id)
1399 function diaspora_comment($importer,$xml,$msg) {
1402 $guid = notags(unxmlify($xml->guid));
1403 $parent_guid = notags(unxmlify($xml->parent_guid));
1404 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1405 $target_type = notags(unxmlify($xml->target_type));
1406 $text = unxmlify($xml->text);
1407 $author_signature = notags(unxmlify($xml->author_signature));
1409 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1411 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1413 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1417 if(! diaspora_post_allow($importer,$contact, true)) {
1418 logger('diaspora_comment: Ignoring this author.');
1422 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1423 intval($importer['uid']),
1427 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1431 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1432 intval($importer['uid']),
1437 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1440 $person = find_diaspora_person_by_handle($diaspora_handle);
1441 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1445 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1447 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1448 intval($importer['uid']),
1455 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1458 $parent_item = $r[0];
1461 /* How Diaspora performs comment signature checking:
1463 - If an item has been sent by the comment author to the top-level post owner to relay on
1464 to the rest of the contacts on the top-level post, the top-level post owner should check
1465 the author_signature, then create a parent_author_signature before relaying the comment on
1466 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1467 check only the parent_author_signature. Basically, they trust that the top-level post
1468 owner has already verified the authenticity of anything he/she sends out
1469 - In either case, the signature that get checked is the signature created by the person
1473 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1476 if($parent_author_signature) {
1477 // If a parent_author_signature exists, then we've received the comment
1478 // relayed from the top-level post owner. There's no need to check the
1479 // author_signature if the parent_author_signature is valid
1481 $parent_author_signature = base64_decode($parent_author_signature);
1483 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1484 logger('diaspora_comment: top-level owner verification failed.');
1489 // If there's no parent_author_signature, then we've received the comment
1490 // from the comment creator. In that case, the person is commenting on
1491 // our post, so he/she must be a contact of ours and his/her public key
1492 // should be in $msg['key']
1494 $author_signature = base64_decode($author_signature);
1496 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1497 logger('diaspora_comment: comment author verification failed.');
1502 // Phew! Everything checks out. Now create an item.
1504 // Find the original comment author information.
1505 // We need this to make sure we display the comment author
1506 // information (name and avatar) correctly.
1507 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1510 $person = find_diaspora_person_by_handle($diaspora_handle);
1512 if(! is_array($person)) {
1513 logger('diaspora_comment: unable to find author details');
1518 // Fetch the contact id - if we know this contact
1519 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1520 dbesc(normalise_link($person['url'])), intval($importer['uid']));
1523 $network = $r[0]['network'];
1525 $cid = $contact['id'];
1526 $network = NETWORK_DIASPORA;
1529 $body = diaspora2bb($text);
1530 $message_id = $diaspora_handle . ':' . $guid;
1532 $datarray = array();
1534 $datarray['uid'] = $importer['uid'];
1535 $datarray['contact-id'] = $cid;
1536 $datarray['type'] = 'remote-comment';
1537 $datarray['wall'] = $parent_item['wall'];
1538 $datarray['network'] = $network;
1539 $datarray['verb'] = ACTIVITY_POST;
1540 $datarray['gravity'] = GRAVITY_COMMENT;
1541 $datarray['guid'] = $guid;
1542 $datarray['uri'] = $message_id;
1543 $datarray['parent-uri'] = $parent_item['uri'];
1545 // No timestamps for comments? OK, we'll the use current time.
1546 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1547 $datarray['private'] = $parent_item['private'];
1549 $datarray['owner-name'] = $parent_item['owner-name'];
1550 $datarray['owner-link'] = $parent_item['owner-link'];
1551 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1553 $datarray['author-name'] = $person['name'];
1554 $datarray['author-link'] = $person['url'];
1555 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1556 $datarray['body'] = $body;
1557 $datarray["object"] = json_encode($xml);
1558 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1560 // We can't be certain what the original app is if the message is relayed.
1561 if(($parent_item['origin']) && (! $parent_author_signature))
1562 $datarray['app'] = 'Diaspora';
1564 DiasporaFetchGuid($datarray);
1565 $message_id = item_store($datarray);
1567 $datarray['id'] = $message_id;
1570 //q("update item set plink = '%s' where id = %d",
1571 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1572 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1573 // intval($message_id)
1577 // If we are the origin of the parent we store the original signature and notify our followers
1578 if($parent_item['origin']) {
1579 $author_signature_base64 = base64_encode($author_signature);
1580 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
1582 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1583 intval($message_id),
1584 dbesc($signed_data),
1585 dbesc($author_signature_base64),
1586 dbesc($diaspora_handle)
1590 proc_run('php','include/notifier.php','comment-import',$message_id);
1599 function diaspora_conversation($importer,$xml,$msg) {
1603 $guid = notags(unxmlify($xml->guid));
1604 $subject = notags(unxmlify($xml->subject));
1605 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1606 $participant_handles = notags(unxmlify($xml->participant_handles));
1607 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1609 $parent_uri = $diaspora_handle . ':' . $guid;
1611 $messages = $xml->message;
1613 if(! count($messages)) {
1614 logger('diaspora_conversation: empty conversation');
1618 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1620 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1624 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1625 logger('diaspora_conversation: Ignoring this author.');
1629 $conversation = null;
1631 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1632 intval($importer['uid']),
1636 $conversation = $c[0];
1638 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1639 intval($importer['uid']),
1641 dbesc($diaspora_handle),
1642 dbesc(datetime_convert('UTC','UTC',$created_at)),
1643 dbesc(datetime_convert()),
1645 dbesc($participant_handles)
1648 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1649 intval($importer['uid']),
1653 $conversation = $c[0];
1655 if(! $conversation) {
1656 logger('diaspora_conversation: unable to create conversation.');
1660 foreach($messages as $mesg) {
1664 $msg_guid = notags(unxmlify($mesg->guid));
1665 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1666 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1667 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1668 $msg_text = unxmlify($mesg->text);
1669 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1670 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1671 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1672 if($msg_conversation_guid != $guid) {
1673 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1677 $body = diaspora2bb($msg_text);
1678 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1680 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1682 $author_signature = base64_decode($msg_author_signature);
1684 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1689 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1691 if(is_array($person) && x($person,'pubkey'))
1692 $key = $person['pubkey'];
1694 logger('diaspora_conversation: unable to find author details');
1699 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1700 logger('diaspora_conversation: verification failed.');
1704 if($msg_parent_author_signature) {
1705 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1707 $parent_author_signature = base64_decode($msg_parent_author_signature);
1711 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1712 logger('diaspora_conversation: owner verification failed.');
1717 $r = q("select id from mail where `uri` = '%s' limit 1",
1721 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1725 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')",
1726 intval($importer['uid']),
1728 intval($conversation['id']),
1729 dbesc($person['name']),
1730 dbesc($person['photo']),
1731 dbesc($person['url']),
1732 intval($contact['id']),
1739 dbesc($msg_created_at)
1742 q("update conv set updated = '%s' where id = %d",
1743 dbesc(datetime_convert()),
1744 intval($conversation['id'])
1748 'type' => NOTIFY_MAIL,
1749 'notify_flags' => $importer['notify-flags'],
1750 'language' => $importer['language'],
1751 'to_name' => $importer['username'],
1752 'to_email' => $importer['email'],
1753 'uid' =>$importer['uid'],
1754 'item' => array('subject' => $subject, 'body' => $body),
1755 'source_name' => $person['name'],
1756 'source_link' => $person['url'],
1757 'source_photo' => $person['thumb'],
1758 'verb' => ACTIVITY_POST,
1766 function diaspora_message($importer,$xml,$msg) {
1770 $msg_guid = notags(unxmlify($xml->guid));
1771 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1772 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1773 $msg_author_signature = notags(unxmlify($xml->author_signature));
1774 $msg_text = unxmlify($xml->text);
1775 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1776 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1777 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1779 $parent_uri = $msg_diaspora_handle . ':' . $msg_parent_guid;
1781 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1783 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1787 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1788 logger('diaspora_message: Ignoring this author.');
1792 $conversation = null;
1794 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1795 intval($importer['uid']),
1796 dbesc($msg_conversation_guid)
1799 $conversation = $c[0];
1801 logger('diaspora_message: conversation not available.');
1807 $body = diaspora2bb($msg_text);
1808 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1810 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1813 $author_signature = base64_decode($msg_author_signature);
1815 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1816 if(is_array($person) && x($person,'pubkey'))
1817 $key = $person['pubkey'];
1819 logger('diaspora_message: unable to find author details');
1823 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1824 logger('diaspora_message: verification failed.');
1828 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1830 intval($importer['uid'])
1833 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1837 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')",
1838 intval($importer['uid']),
1840 intval($conversation['id']),
1841 dbesc($person['name']),
1842 dbesc($person['photo']),
1843 dbesc($person['url']),
1844 intval($contact['id']),
1845 dbesc($conversation['subject']),
1851 dbesc($msg_created_at)
1854 q("update conv set updated = '%s' where id = %d",
1855 dbesc(datetime_convert()),
1856 intval($conversation['id'])
1862 function diaspora_participation($importer,$xml) {
1863 logger("Unsupported message type 'participation' ".print_r($xml, true));
1866 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1870 logger('diaspora_photo: init',LOGGER_DEBUG);
1872 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1874 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1876 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1878 $guid = notags(unxmlify($xml->guid));
1880 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1882 $public = notags(unxmlify($xml->public));
1884 $created_at = notags(unxmlify($xml_created_at));
1886 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1888 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1890 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1894 if(! diaspora_post_allow($importer,$contact, false)) {
1895 logger('diaspora_photo: Ignoring this author.');
1899 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1900 intval($importer['uid']),
1901 dbesc($status_message_guid)
1904 /* deactivated by now since it can lead to multiplicated pictures in posts.
1906 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1909 $person = find_diaspora_person_by_handle($diaspora_handle);
1910 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1914 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1916 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1917 intval($importer['uid']),
1918 dbesc($status_message_guid)
1925 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1926 intval($importer['uid']),
1927 dbesc(serialize($msg)),
1928 intval($attempt + 1)
1932 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1936 $parent_item = $r[0];
1938 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1940 $link_text = scale_external_images($link_text, true,
1941 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1943 if(strpos($parent_item['body'],$link_text) === false) {
1945 $parent_item['body'] = $link_text . $parent_item['body'];
1947 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1948 dbesc($parent_item['body']),
1949 intval($parent_item['id']),
1950 intval($parent_item['uid'])
1952 put_item_in_cache($parent_item, true);
1953 update_thread($parent_item['id']);
1962 function diaspora_like($importer,$xml,$msg) {
1965 $guid = notags(unxmlify($xml->guid));
1966 $parent_guid = notags(unxmlify($xml->parent_guid));
1967 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1968 $target_type = notags(unxmlify($xml->target_type));
1969 $positive = notags(unxmlify($xml->positive));
1970 $author_signature = notags(unxmlify($xml->author_signature));
1972 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1974 // likes on comments not supported here and likes on photos not supported by Diaspora
1976 // if($target_type !== 'Post')
1979 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1981 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1985 if(! diaspora_post_allow($importer,$contact, false)) {
1986 logger('diaspora_like: Ignoring this author.');
1990 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1991 intval($importer['uid']),
1996 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1999 $person = find_diaspora_person_by_handle($diaspora_handle);
2000 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
2004 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
2006 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2007 intval($importer['uid']),
2014 logger('diaspora_like: parent item not found: ' . $guid);
2018 $parent_item = $r[0];
2020 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2021 intval($importer['uid']),
2025 if($positive === 'true') {
2026 logger('diaspora_like: duplicate like: ' . $guid);
2029 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2030 // It looks like "RelayableRetractions" are used for "unlike" instead
2031 if($positive === 'false') {
2032 logger('diaspora_like: received a like with positive set to "false"...ignoring');
2033 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2034 intval($r[0]['id']),
2035 intval($importer['uid'])
2037 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2038 // send notification via proc_run()
2042 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2043 // It looks like "RelayableRetractions" are used for "unlike" instead
2044 if($positive === 'false') {
2045 logger('diaspora_like: received a like with positive set to "false"');
2046 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2051 /* How Diaspora performs "like" signature checking:
2053 - If an item has been sent by the like author to the top-level post owner to relay on
2054 to the rest of the contacts on the top-level post, the top-level post owner should check
2055 the author_signature, then create a parent_author_signature before relaying the like on
2056 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2057 check only the parent_author_signature. Basically, they trust that the top-level post
2058 owner has already verified the authenticity of anything he/she sends out
2059 - In either case, the signature that get checked is the signature created by the person
2063 // Diaspora has changed the way they are signing the likes.
2064 // Just to make sure that we don't miss any likes we will check the old and the current way.
2065 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2067 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2071 if ($parent_author_signature) {
2072 // If a parent_author_signature exists, then we've received the like
2073 // relayed from the top-level post owner. There's no need to check the
2074 // author_signature if the parent_author_signature is valid
2076 $parent_author_signature = base64_decode($parent_author_signature);
2078 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2079 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2081 logger('diaspora_like: top-level owner verification failed.');
2085 // If there's no parent_author_signature, then we've received the like
2086 // from the like creator. In that case, the person is "like"ing
2087 // our post, so he/she must be a contact of ours and his/her public key
2088 // should be in $msg['key']
2090 $author_signature = base64_decode($author_signature);
2092 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2093 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2095 logger('diaspora_like: like creator verification failed.');
2100 // Phew! Everything checks out. Now create an item.
2102 // Find the original comment author information.
2103 // We need this to make sure we display the comment author
2104 // information (name and avatar) correctly.
2105 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2108 $person = find_diaspora_person_by_handle($diaspora_handle);
2110 if(! is_array($person)) {
2111 logger('diaspora_like: unable to find author details');
2116 $uri = $diaspora_handle . ':' . $guid;
2118 $activity = ACTIVITY_LIKE;
2119 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2120 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2121 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2122 $body = $parent_item['body'];
2127 <type>$objtype</type>
2129 <id>{$parent_item['uri']}</id>
2132 <content>$body</content>
2135 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2137 // Fetch the contact id - if we know this contact
2138 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
2139 dbesc(normalise_link($person['url'])), intval($importer['uid']));
2142 $network = $r[0]['network'];
2144 $cid = $contact['id'];
2145 $network = NETWORK_DIASPORA;
2151 $arr['uid'] = $importer['uid'];
2152 $arr['guid'] = $guid;
2153 $arr['network'] = $network;
2154 $arr['contact-id'] = $cid;
2155 $arr['type'] = 'activity';
2156 $arr['wall'] = $parent_item['wall'];
2157 $arr['gravity'] = GRAVITY_LIKE;
2158 $arr['parent'] = $parent_item['id'];
2159 $arr['parent-uri'] = $parent_item['uri'];
2161 $arr['owner-name'] = $parent_item['name'];
2162 $arr['owner-link'] = $parent_item['url'];
2163 //$arr['owner-avatar'] = $parent_item['thumb'];
2164 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2166 $arr['author-name'] = $person['name'];
2167 $arr['author-link'] = $person['url'];
2168 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2170 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2171 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2172 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2173 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2174 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2176 $arr['app'] = 'Diaspora';
2178 $arr['private'] = $parent_item['private'];
2179 $arr['verb'] = $activity;
2180 $arr['object-type'] = $objtype;
2181 $arr['object'] = $obj;
2182 $arr['visible'] = 1;
2184 $arr['last-child'] = 0;
2186 $message_id = item_store($arr);
2190 // q("update item set plink = '%s' where id = %d",
2191 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2192 // dbesc($a->get_baseurl().'/display/'.$guid),
2193 // intval($message_id)
2197 // If we are the origin of the parent we store the original signature and notify our followers
2198 if($parent_item['origin']) {
2199 $author_signature_base64 = base64_encode($author_signature);
2200 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
2202 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2203 intval($message_id),
2204 dbesc($signed_data),
2205 dbesc($author_signature_base64),
2206 dbesc($diaspora_handle)
2210 proc_run('php','include/notifier.php','comment-import',$message_id);
2216 function diaspora_retraction($importer,$xml) {
2219 $guid = notags(unxmlify($xml->guid));
2220 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2221 $type = notags(unxmlify($xml->type));
2223 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2227 if($type === 'Person') {
2228 require_once('include/Contact.php');
2229 contact_remove($contact['id']);
2230 } elseif($type === 'StatusMessage') {
2231 $guid = notags(unxmlify($xml->post_guid));
2233 $r = q("SELECT * FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2235 intval($importer['uid'])
2238 if(link_compare($r[0]['author-link'],$contact['url'])) {
2239 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
2240 dbesc(datetime_convert()),
2243 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2246 } elseif($type === 'Post') {
2247 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2249 intval($importer['uid'])
2252 if(link_compare($r[0]['author-link'],$contact['url'])) {
2253 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2254 dbesc(datetime_convert()),
2257 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2266 function diaspora_signed_retraction($importer,$xml,$msg) {
2269 $guid = notags(unxmlify($xml->target_guid));
2270 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2271 $type = notags(unxmlify($xml->target_type));
2272 $sig = notags(unxmlify($xml->target_author_signature));
2274 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2276 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2278 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2283 $signed_data = $guid . ';' . $type ;
2286 /* How Diaspora performs relayable_retraction signature checking:
2288 - If an item has been sent by the item author to the top-level post owner to relay on
2289 to the rest of the contacts on the top-level post, the top-level post owner checks
2290 the author_signature, then creates a parent_author_signature before relaying the item on
2291 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2292 check only the parent_author_signature. Basically, they trust that the top-level post
2293 owner has already verified the authenticity of anything he/she sends out
2294 - In either case, the signature that get checked is the signature created by the person
2298 if($parent_author_signature) {
2300 $parent_author_signature = base64_decode($parent_author_signature);
2302 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2303 logger('diaspora_signed_retraction: top-level post owner verification failed');
2309 $sig_decode = base64_decode($sig);
2311 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2312 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2317 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2318 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2320 intval($importer['uid'])
2323 if(link_compare($r[0]['author-link'],$contact['url'])) {
2324 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2325 dbesc(datetime_convert()),
2326 dbesc(datetime_convert()),
2329 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2331 // Now check if the retraction needs to be relayed by us
2333 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2334 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2335 // The only item with `parent` and `id` as the parent id is the parent item.
2336 $p = q("SELECT `origin` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2337 intval($r[0]['parent']),
2338 intval($r[0]['parent'])
2341 if($p[0]['origin']) {
2342 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2344 dbesc($signed_data),
2346 dbesc($diaspora_handle)
2349 // the existence of parent_author_signature would have meant the parent_author or owner
2350 // is already relaying.
2351 logger('diaspora_signed_retraction: relaying relayable_retraction');
2353 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2360 logger('diaspora_signed_retraction: unknown type: ' . $type);
2366 function diaspora_profile($importer,$xml,$msg) {
2369 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2372 if($diaspora_handle != $msg['author']) {
2373 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2377 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2381 //if($contact['blocked']) {
2382 // logger('diaspora_post: Ignoring this author.');
2386 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2387 $image_url = unxmlify($xml->image_url);
2388 $birthday = unxmlify($xml->birthday);
2389 $location = diaspora2bb(unxmlify($xml->location));
2390 $about = diaspora2bb(unxmlify($xml->bio));
2391 $gender = unxmlify($xml->gender);
2392 $searchable = (unxmlify($xml->searchable) == "true");
2393 $nsfw = (unxmlify($xml->nsfw) == "true");
2394 $tags = unxmlify($xml->tag_string);
2396 $tags = explode("#", $tags);
2398 $keywords = array();
2399 foreach ($tags as $tag) {
2400 $tag = trim(strtolower($tag));
2405 $keywords = implode(", ", $keywords);
2407 $handle_parts = explode("@", $diaspora_handle);
2408 $nick = $handle_parts[0];
2411 $name = $handle_parts[0];
2414 if( preg_match("|^https?://|", $image_url) === 0) {
2415 $image_url = "http://" . $handle_parts[1] . $image_url;
2418 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2419 intval($importer['uid']),
2420 intval($contact['id'])
2422 $oldphotos = ((count($r)) ? $r : null);*/
2424 require_once('include/Photo.php');
2426 update_contact_avatar($image_url,$importer['uid'],$contact['id']);
2428 // Generic birthday. We don't know the timezone. The year is irrelevant.
2430 $birthday = str_replace('1000','1901',$birthday);
2432 if ($birthday != "")
2433 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2435 // this is to prevent multiple birthday notifications in a single year
2436 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2438 if(substr($birthday,5) === substr($contact['bd'],5))
2439 $birthday = $contact['bd'];
2441 /// @TODO Update name on item['author-name'] if the name changed. See consume_feed()
2442 /// (Not doing this currently because D* protocol is scheduled for revision soon).
2444 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2445 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2448 dbesc($diaspora_handle),
2449 dbesc(datetime_convert()),
2455 intval($contact['id']),
2456 intval($importer['uid'])
2460 require_once('include/socgraph.php');
2461 poco_check($contact['url'], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
2462 datetime_convert(), 2, $contact['id'], $importer['uid']);
2465 update_gcontact(array("url" => $contact['url'], "network" => NETWORK_DIASPORA, "generation" => 2,
2466 "photo" => $image_url, "name" => $name, "location" => $location,
2467 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2468 "addr" => $diaspora_handle, "nick" => $nick, "keywords" => $keywords,
2469 "hide" => !$searchable, "nsfw" => $nsfw));
2473 foreach($oldphotos as $ph) {
2474 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2475 intval($importer['uid']),
2476 intval($contact['id']),
2477 dbesc($ph['resource-id'])
2487 function diaspora_share($me,$contact) {
2489 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2490 $theiraddr = $contact['addr'];
2492 $tpl = get_markup_template('diaspora_share.tpl');
2493 $msg = replace_macros($tpl, array(
2494 '$sender' => $myaddr,
2495 '$recipient' => $theiraddr
2498 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2499 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2501 return(diaspora_transmit($owner,$contact,$slap, false));
2504 function diaspora_unshare($me,$contact) {
2507 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2509 $tpl = get_markup_template('diaspora_retract.tpl');
2510 $msg = replace_macros($tpl, array(
2511 '$guid' => $me['guid'],
2512 '$type' => 'Person',
2513 '$handle' => $myaddr
2516 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2517 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2519 return(diaspora_transmit($owner,$contact,$slap, false));
2524 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2527 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2528 $theiraddr = $contact['addr'];
2532 $title = $item['title'];
2533 $body = $item['body'];
2536 // We're trying to match Diaspora's split message/photo protocol but
2537 // all the photos are displayed on D* as links and not img's - even
2538 // though we're sending pretty much precisely what they send us when
2539 // doing the same operation.
2540 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2541 // which seems to get through intact.
2543 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2545 foreach($matches as $mtch) {
2547 $detail['str'] = $mtch[0];
2548 $detail['path'] = dirname($mtch[1]) . '/';
2549 $detail['file'] = basename($mtch[1]);
2550 $detail['guid'] = $item['guid'];
2551 $detail['handle'] = $myaddr;
2552 $images[] = $detail;
2553 $body = str_replace($detail['str'],$mtch[1],$body);
2558 //if(strlen($title))
2559 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2561 // convert to markdown
2562 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2563 //$body = bb2diaspora($body);
2567 $body = "## ".html_entity_decode($title)."\n\n".$body;
2569 if($item['attach']) {
2570 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2572 $body .= "\n" . t('Attachments:') . "\n";
2573 foreach($matches as $mtch) {
2574 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2580 $public = (($item['private']) ? 'false' : 'true');
2582 require_once('include/datetime.php');
2583 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2585 // Detect a share element and do a reshare
2586 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2587 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2588 $tpl = get_markup_template('diaspora_reshare.tpl');
2589 $msg = replace_macros($tpl, array(
2590 '$root_handle' => xmlify($ret['root_handle']),
2591 '$root_guid' => $ret['root_guid'],
2592 '$guid' => $item['guid'],
2593 '$handle' => xmlify($myaddr),
2594 '$public' => $public,
2595 '$created' => $created,
2596 '$provider' => $item["app"]
2599 $tpl = get_markup_template('diaspora_post.tpl');
2600 $msg = replace_macros($tpl, array(
2602 '$guid' => $item['guid'],
2603 '$handle' => xmlify($myaddr),
2604 '$public' => $public,
2605 '$created' => $created,
2606 '$provider' => $item["app"]
2610 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2611 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2613 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2614 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2616 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']);
2618 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2620 if(count($images)) {
2621 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2624 return $return_code;
2627 function diaspora_is_reshare($body) {
2628 $body = trim($body);
2630 // Skip if it isn't a pure repeated messages
2631 // Does it start with a share?
2632 if (strpos($body, "[share") > 0)
2635 // Does it end with a share?
2636 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2639 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2640 // Skip if there is no shared message in there
2641 if ($body == $attributes)
2645 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2646 if ($matches[1] != "")
2647 $guid = $matches[1];
2649 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2650 if ($matches[1] != "")
2651 $guid = $matches[1];
2654 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2655 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2658 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2659 $ret["root_guid"] = $guid;
2665 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2666 if ($matches[1] != "")
2667 $profile = $matches[1];
2669 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2670 if ($matches[1] != "")
2671 $profile = $matches[1];
2675 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2676 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2680 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2681 if ($matches[1] != "")
2682 $link = $matches[1];
2684 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2685 if ($matches[1] != "")
2686 $link = $matches[1];
2688 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2689 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2695 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2697 if(! count($images))
2699 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2701 $tpl = get_markup_template('diaspora_photo.tpl');
2702 foreach($images as $image) {
2703 if(! stristr($image['path'],$mysite))
2705 $resource = str_replace('.jpg','',$image['file']);
2706 $resource = substr($resource,0,strpos($resource,'-'));
2708 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2710 intval($owner['uid'])
2714 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2715 $msg = replace_macros($tpl,array(
2716 '$path' => xmlify($image['path']),
2717 '$filename' => xmlify($image['file']),
2718 '$msg_guid' => xmlify($image['guid']),
2719 '$guid' => xmlify($r[0]['guid']),
2720 '$handle' => xmlify($image['handle']),
2721 '$public' => xmlify($public),
2722 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2726 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2727 logger('send guid '.$r[0]['guid'], LOGGER_DEBUG);
2729 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2730 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2732 diaspora_transmit($owner,$contact,$slap,$public_batch,false,$r[0]['guid']);
2737 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2740 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2741 // $theiraddr = $contact['addr'];
2743 // Diaspora doesn't support threaded comments, but some
2744 // versions of Diaspora (i.e. Diaspora-pistos) support
2745 // likes on comments
2746 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2747 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2748 dbesc($item['thr-parent'])
2752 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2753 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2754 // The only item with `parent` and `id` as the parent id is the parent item.
2755 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2756 intval($item['parent']),
2757 intval($item['parent'])
2765 if($item['verb'] === ACTIVITY_LIKE) {
2766 $tpl = get_markup_template('diaspora_like.tpl');
2768 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2769 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2770 // $positive = (($item['deleted']) ? 'false' : 'true');
2773 if(($item['deleted']))
2774 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2777 $tpl = get_markup_template('diaspora_comment.tpl');
2781 $text = html_entity_decode(bb2diaspora($item['body']));
2786 $signed_text = $positive . ';' . $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $myaddr;
2788 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2790 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2792 $msg = replace_macros($tpl,array(
2793 '$guid' => xmlify($item['guid']),
2794 '$parent_guid' => xmlify($parent['guid']),
2795 '$target_type' =>xmlify($target_type),
2796 '$authorsig' => xmlify($authorsig),
2797 '$body' => xmlify($text),
2798 '$positive' => xmlify($positive),
2799 '$handle' => xmlify($myaddr)
2802 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2803 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2805 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2806 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2808 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2812 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2816 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2817 // $theiraddr = $contact['addr'];
2819 // Diaspora doesn't support threaded comments, but some
2820 // versions of Diaspora (i.e. Diaspora-pistos) support
2821 // likes on comments
2822 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2823 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2824 dbesc($item['thr-parent'])
2828 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2829 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2830 // The only item with `parent` and `id` as the parent id is the parent item.
2831 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2832 intval($item['parent']),
2833 intval($item['parent'])
2842 $relay_retract = false;
2843 $sql_sign_id = 'iid';
2844 if( $item['deleted']) {
2845 $relay_retract = true;
2847 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2849 $sql_sign_id = 'retract_iid';
2850 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2852 elseif($item['verb'] === ACTIVITY_LIKE) {
2855 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2856 // $positive = (($item['deleted']) ? 'false' : 'true');
2859 $tpl = get_markup_template('diaspora_like_relay.tpl');
2861 else { // item is a comment
2862 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2866 // fetch the original signature if the relayable was created by a Diaspora
2867 // or DFRN user. Relayables for other networks are not supported.
2869 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE " . $sql_sign_id . " = %d LIMIT 1",
2874 $signed_text = $orig_sign['signed_text'];
2875 $authorsig = $orig_sign['signature'];
2876 $handle = $orig_sign['signer'];
2878 // Split the signed text
2879 $signed_parts = explode(";", $signed_text);
2881 // Remove the parent guid
2882 array_shift($signed_parts);
2884 // Remove the comment guid
2885 array_shift($signed_parts);
2887 // Remove the handle
2888 array_pop($signed_parts);
2890 // Glue the parts together
2891 $text = implode(";", $signed_parts);
2894 // This part is meant for cases where we don't have the signatur. (Which shouldn't happen with posts from Diaspora and Friendica)
2895 // This means that the comment won't be accepted by newer Diaspora servers
2897 $body = $item['body'];
2898 $text = html_entity_decode(bb2diaspora($body));
2900 $handle = diaspora_handle_from_contact($item['contact-id']);
2905 $signed_text = $item['guid'] . ';' . $target_type;
2907 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2909 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2911 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2914 // Sign the relayable with the top-level owner's signature
2915 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2917 $msg = replace_macros($tpl,array(
2918 '$guid' => xmlify($item['guid']),
2919 '$parent_guid' => xmlify($parent['guid']),
2920 '$target_type' =>xmlify($target_type),
2921 '$authorsig' => xmlify($authorsig),
2922 '$parentsig' => xmlify($parentauthorsig),
2923 '$body' => xmlify($text),
2924 '$positive' => xmlify($positive),
2925 '$handle' => xmlify($handle)
2928 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2929 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2931 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2932 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2934 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2940 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2943 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2945 // Check whether the retraction is for a top-level post or whether it's a relayable
2946 if( $item['uri'] !== $item['parent-uri'] ) {
2948 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2949 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2953 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2954 $target_type = 'StatusMessage';
2957 $signed_text = $item['guid'] . ';' . $target_type;
2959 $msg = replace_macros($tpl, array(
2960 '$guid' => xmlify($item['guid']),
2961 '$type' => xmlify($target_type),
2962 '$handle' => xmlify($myaddr),
2963 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2966 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2968 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2969 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2971 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2974 function diaspora_send_mail($item,$owner,$contact) {
2977 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2979 $r = q("select * from conv where id = %d and uid = %d limit 1",
2980 intval($item['convid']),
2981 intval($item['uid'])
2985 logger('diaspora_send_mail: conversation not found.');
2991 'guid' => xmlify($cnv['guid']),
2992 'subject' => xmlify($cnv['subject']),
2993 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2994 'diaspora_handle' => xmlify($cnv['creator']),
2995 'participant_handles' => xmlify($cnv['recips'])
2998 $body = bb2diaspora($item['body']);
2999 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
3001 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
3002 . $created . ';' . $myaddr . ';' . $cnv['guid'];
3004 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
3007 'guid' => xmlify($item['guid']),
3008 'parent_guid' => xmlify($cnv['guid']),
3009 'parent_author_signature' => xmlify($sig),
3010 'author_signature' => xmlify($sig),
3011 'text' => xmlify($body),
3012 'created_at' => xmlify($created),
3013 'diaspora_handle' => xmlify($myaddr),
3014 'conversation_guid' => xmlify($cnv['guid'])
3017 if($item['reply']) {
3018 $tpl = get_markup_template('diaspora_message.tpl');
3019 $xmsg = replace_macros($tpl, array('$msg' => $msg));
3022 $conv['messages'] = array($msg);
3023 $tpl = get_markup_template('diaspora_conversation.tpl');
3024 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3027 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3028 logger('send guid '.$item['guid'], LOGGER_DEBUG);
3030 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3031 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3033 return(diaspora_transmit($owner,$contact,$slap,false,false,$item['guid']));
3038 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false,$guid = "") {
3040 $enabled = intval(get_config('system','diaspora_enabled'));
3046 $logid = random_string(4);
3047 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3049 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3053 logger('diaspora_transmit: '.$logid.'-'.$guid.' '.$dest_url);
3055 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3059 if (!intval(get_config('system','diaspora_test'))) {
3060 post_url($dest_url . '/', $slap);
3061 $return_code = $a->get_curl_code();
3063 logger('diaspora_transmit: test_mode');
3068 logger('diaspora_transmit: '.$logid.'-'.$guid.' returns: '.$return_code);
3070 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3071 logger('diaspora_transmit: queue message');
3073 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3074 intval($contact['id']),
3075 dbesc(NETWORK_DIASPORA),
3077 intval($public_batch)
3080 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3083 // queue message for redelivery
3084 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3089 return(($return_code) ? $return_code : (-1));
3092 function diaspora_fetch_relay() {
3094 $serverdata = get_config("system", "relay_server");
3095 if ($serverdata == "")
3100 $servers = explode(",", $serverdata);
3102 foreach($servers AS $server) {
3103 $server = trim($server);
3104 $batch = $server."/receive/public";
3106 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3109 $addr = "relay@".str_replace("http://", "", normalise_link($server));
3111 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
3112 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
3117 dbesc(normalise_link($server)),
3119 dbesc(NETWORK_DIASPORA),
3120 intval(CONTACT_IS_FOLLOWER),
3121 dbesc(datetime_convert()),
3122 dbesc(datetime_convert()),
3123 dbesc(datetime_convert())
3126 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3128 $relay[] = $relais[0];
3130 $relay[] = $relais[0];