5 - GET /people/9aed8882b9f64896/stream
8 require_once('include/crypto.php');
9 require_once('include/items.php');
10 require_once('include/bb2diaspora.php');
11 require_once('include/contact_selectors.php');
12 require_once('include/queue_fn.php');
13 require_once('include/lock.php');
14 require_once('include/threads.php');
15 require_once('mod/share.php');
17 function diaspora_dispatch_public($msg) {
19 $enabled = intval(get_config('system','diaspora_enabled'));
21 logger('mod-diaspora: disabled');
25 // Use a dummy importer to import the data for the public copy
26 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
27 $result = diaspora_dispatch($importer,$msg);
28 logger("Dispatcher reported ".$result, LOGGER_DEBUG);
30 // Now distribute it to the followers
31 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
32 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
33 AND `account_expired` = 0 AND `account_removed` = 0 ",
34 dbesc(NETWORK_DIASPORA),
39 logger('diaspora_public: delivering to: ' . $rr['username']);
40 diaspora_dispatch($rr,$msg);
44 logger('diaspora_public: no subscribers for '.$msg["author"].' '.print_r($msg, true));
49 function diaspora_dispatch($importer,$msg,$attempt=1) {
53 $enabled = intval(get_config('system','diaspora_enabled'));
55 logger('mod-diaspora: disabled');
59 // php doesn't like dashes in variable names
61 $msg['message'] = str_replace(
62 array('<activity_streams-photo>','</activity_streams-photo>'),
63 array('<asphoto>','</asphoto>'),
67 $parsed_xml = parse_xml_string($msg['message'],false);
69 $xmlbase = $parsed_xml->post;
71 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
74 if($xmlbase->request) {
75 $ret = diaspora_request($importer,$xmlbase->request);
77 elseif($xmlbase->status_message) {
78 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
80 elseif($xmlbase->profile) {
81 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
83 elseif($xmlbase->comment) {
84 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
86 elseif($xmlbase->like) {
87 $ret = diaspora_like($importer,$xmlbase->like,$msg);
89 elseif($xmlbase->asphoto) {
90 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
92 elseif($xmlbase->reshare) {
93 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
95 elseif($xmlbase->retraction) {
96 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
98 elseif($xmlbase->signed_retraction) {
99 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
101 elseif($xmlbase->relayable_retraction) {
102 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
104 elseif($xmlbase->photo) {
105 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
107 elseif($xmlbase->conversation) {
108 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
110 elseif($xmlbase->message) {
111 $ret = diaspora_message($importer,$xmlbase->message,$msg);
113 elseif($xmlbase->participation) {
114 $ret = diaspora_participation($importer,$xmlbase->participation);
117 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
122 function diaspora_handle_from_contact($contact_id) {
125 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
127 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
133 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
135 if($contact['network'] === NETWORK_DIASPORA) {
136 $handle = $contact['addr'];
138 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
140 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
141 $baseurl_start = strpos($contact['url'],'://') + 3;
142 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
143 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
144 $handle = $contact['nick'] . '@' . $baseurl;
146 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
153 function diaspora_get_contact_by_handle($uid,$handle) {
154 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
155 dbesc(NETWORK_DIASPORA),
162 $handle_parts = explode("@", $handle);
163 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
164 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
175 function find_diaspora_person_by_handle($handle) {
185 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
186 dbesc(NETWORK_DIASPORA),
191 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
193 // update record occasionally so it doesn't get stale
194 $d = strtotime($person['updated'] . ' +00:00');
195 if($d < strtotime('now - 14 days'))
200 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
202 // If the person isn't in our 'fcontact' table, or if he/she is but
203 // his/her information hasn't been updated for more than 14 days, then
204 // we want to fetch the person's information from the remote server.
206 // Note that $person isn't changed by this block of code unless the
207 // person's information has been successfully fetched from the remote
208 // server. So if $person was 'false' to begin with (because he/she wasn't
209 // in the local cache), it'll stay false, and if $person held the local
210 // cache information to begin with, it'll keep that information. That way
211 // if there's a problem with the remote fetch, we can at least use our
212 // cached information--it's better than nothing.
214 if((! $person) || ($update)) {
215 // Lock the function to prevent race conditions if multiple items
216 // come in at the same time from a person who doesn't exist in
219 // Don't loop forever. On the last loop, try to create the contact
220 // whether the function is locked or not. Maybe the locking thread
221 // has died or something. At any rate, a duplicate in 'fcontact'
222 // is a much smaller problem than a deadlocked thread
223 $got_lock = lock_function('find_diaspora_person_by_handle', false);
224 if(($endlessloop + 1) >= $maxloops)
228 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
229 require_once('include/Scrape.php');
230 $r = probe_url($handle, PROBE_DIASPORA);
232 // Note that Friendica contacts can return a "Diaspora person"
233 // if Diaspora connectivity is enabled on their server
234 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
235 add_fcontact($r,$update);
239 unlock_function('find_diaspora_person_by_handle');
242 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
244 block_on_function_lock('find_diaspora_person_by_handle');
247 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
248 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
249 // The fact that the function was locked may mean that another process was creating the
250 // person's record. It could also mean another process was creating or updating an unrelated
253 // At any rate, we need to keep trying until we've either got the person or had a chance to
254 // try to fetch his/her remote information. But we don't want to block on locking the
255 // function, because if the other process is creating the record, then when we acquire the lock
256 // we'll dive right into creating another, duplicate record. We DO want to at least wait
257 // until the lock is released, so we don't flood the database with requests.
259 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
260 // we do have some information for the person
266 function get_diaspora_key($uri) {
267 logger('Fetching diaspora key for: ' . $uri);
269 $r = find_diaspora_person_by_handle($uri);
276 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
279 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
282 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
284 // $b64_data = base64_encode($msg);
285 // $b64url_data = base64url_encode($b64_data);
287 $b64url_data = base64url_encode($msg);
289 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
291 $type = 'application/xml';
292 $encoding = 'base64url';
295 $signable_data = $data . '.' . base64url_encode($type) . '.'
296 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
298 $signature = rsa_sign($signable_data,$prvkey);
299 $sig = base64url_encode($signature);
302 <?xml version='1.0' encoding='UTF-8'?>
303 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
305 <author_id>$handle</author_id>
308 <me:encoding>base64url</me:encoding>
309 <me:alg>RSA-SHA256</me:alg>
310 <me:data type="application/xml">$data</me:data>
311 <me:sig>$sig</me:sig>
316 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
324 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
328 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
330 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
332 // without a public key nothing will work
335 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
339 $inner_aes_key = random_string(32);
340 $b_inner_aes_key = base64_encode($inner_aes_key);
341 $inner_iv = random_string(16);
342 $b_inner_iv = base64_encode($inner_iv);
344 $outer_aes_key = random_string(32);
345 $b_outer_aes_key = base64_encode($outer_aes_key);
346 $outer_iv = random_string(16);
347 $b_outer_iv = base64_encode($outer_iv);
349 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
351 $padded_data = pkcs5_pad($msg,16);
352 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
354 $b64_data = base64_encode($inner_encrypted);
357 $b64url_data = base64url_encode($b64_data);
358 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
360 $type = 'application/xml';
361 $encoding = 'base64url';
364 $signable_data = $data . '.' . base64url_encode($type) . '.'
365 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
367 $signature = rsa_sign($signable_data,$prvkey);
368 $sig = base64url_encode($signature);
370 $decrypted_header = <<< EOT
373 <aes_key>$b_inner_aes_key</aes_key>
374 <author_id>$handle</author_id>
378 $decrypted_header = pkcs5_pad($decrypted_header,16);
380 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
382 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
384 $encrypted_outer_key_bundle = '';
385 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
387 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
389 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
391 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
392 'ciphertext' => base64_encode($ciphertext)));
393 $cipher_json = base64_encode($encrypted_header_json_object);
395 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
398 <?xml version='1.0' encoding='UTF-8'?>
399 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
402 <me:encoding>base64url</me:encoding>
403 <me:alg>RSA-SHA256</me:alg>
404 <me:data type="application/xml">$data</me:data>
405 <me:sig>$sig</me:sig>
410 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
417 * diaspora_decode($importer,$xml)
418 * array $importer -> from user table
419 * string $xml -> urldecoded Diaspora salmon
422 * 'message' -> decoded Diaspora XML message
423 * 'author' -> author diaspora handle
424 * 'key' -> author public key (converted to pkcs#8)
426 * Author and key are used elsewhere to save a lookup for verifying replies and likes
430 function diaspora_decode($importer,$xml) {
433 $basedom = parse_xml_string($xml);
435 $children = $basedom->children('https://joindiaspora.com/protocol');
437 if($children->header) {
439 $author_link = str_replace('acct:','',$children->header->author_id);
443 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
445 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
446 $ciphertext = base64_decode($encrypted_header->ciphertext);
448 $outer_key_bundle = '';
449 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
451 $j_outer_key_bundle = json_decode($outer_key_bundle);
453 $outer_iv = base64_decode($j_outer_key_bundle->iv);
454 $outer_key = base64_decode($j_outer_key_bundle->key);
456 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
459 $decrypted = pkcs5_unpad($decrypted);
462 * $decrypted now contains something like
465 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
466 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
471 * <name>Ryan Hughes</name>
472 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
477 * <author_id>galaxor@diaspora.priateship.org</author_id>
481 * </decrypted_header>
484 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
485 $idom = parse_xml_string($decrypted,false);
487 $inner_iv = base64_decode($idom->iv);
488 $inner_aes_key = base64_decode($idom->aes_key);
490 $author_link = str_replace('acct:','',$idom->author_id);
494 $dom = $basedom->children(NAMESPACE_SALMON_ME);
496 // figure out where in the DOM tree our data is hiding
498 if($dom->provenance->data)
499 $base = $dom->provenance;
500 elseif($dom->env->data)
506 logger('mod-diaspora: unable to locate salmon data in xml ');
507 http_status_exit(400);
511 // Stash the signature away for now. We have to find their key or it won't be good for anything.
512 $signature = base64url_decode($base->sig);
516 // strip whitespace so our data element will return to one big base64 blob
517 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
520 // stash away some other stuff for later
522 $type = $base->data[0]->attributes()->type[0];
523 $keyhash = $base->sig[0]->attributes()->keyhash[0];
524 $encoding = $base->encoding;
528 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
532 $data = base64url_decode($data);
536 $inner_decrypted = $data;
540 // Decode the encrypted blob
542 $inner_encrypted = base64_decode($data);
543 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
544 $inner_decrypted = pkcs5_unpad($inner_decrypted);
548 logger('mod-diaspora: Could not retrieve author URI.');
549 http_status_exit(400);
552 // Once we have the author URI, go to the web and try to find their public key
553 // (first this will look it up locally if it is in the fcontact cache)
554 // This will also convert diaspora public key from pkcs#1 to pkcs#8
556 logger('mod-diaspora: Fetching key for ' . $author_link );
557 $key = get_diaspora_key($author_link);
560 logger('mod-diaspora: Could not retrieve author key.');
561 http_status_exit(400);
564 $verify = rsa_verify($signed_data,$signature,$key);
567 logger('mod-diaspora: Message did not verify. Discarding.');
568 http_status_exit(400);
571 logger('mod-diaspora: Message verified.');
573 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
578 function diaspora_request($importer,$xml) {
582 $sender_handle = unxmlify($xml->sender_handle);
583 $recipient_handle = unxmlify($xml->recipient_handle);
585 if(! $sender_handle || ! $recipient_handle)
588 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
592 // perhaps we were already sharing with this person. Now they're sharing with us.
593 // That makes us friends.
595 if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
596 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
597 intval(CONTACT_IS_FRIEND),
598 intval($contact['id']),
599 intval($importer['uid'])
604 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
605 intval($importer['uid'])
608 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
609 require_once('include/items.php');
611 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
612 intval($importer['uid'])
615 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
617 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
620 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
621 $arr['uid'] = $importer['uid'];
622 $arr['contact-id'] = $self[0]['id'];
624 $arr['type'] = 'wall';
627 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
628 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
629 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
630 $arr['verb'] = ACTIVITY_FRIEND;
631 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
633 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
634 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
635 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
636 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
638 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
639 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
640 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
641 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
642 $arr['object'] .= '</link></object>' . "\n";
643 $arr['last-child'] = 1;
645 $arr['allow_cid'] = $user[0]['allow_cid'];
646 $arr['allow_gid'] = $user[0]['allow_gid'];
647 $arr['deny_cid'] = $user[0]['deny_cid'];
648 $arr['deny_gid'] = $user[0]['deny_gid'];
650 $i = item_store($arr);
652 proc_run('php',"include/notifier.php","activity","$i");
661 $ret = find_diaspora_person_by_handle($sender_handle);
664 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
665 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
669 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
673 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
674 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
675 intval($importer['uid']),
676 dbesc($ret['network']),
680 dbesc(normalise_link($ret['url'])),
684 dbesc($ret['photo']),
685 dbesc($ret['pubkey']),
686 dbesc($ret['notify']),
692 // find the contact record we just created
694 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
696 if(! $contact_record) {
697 logger('diaspora_request: unable to locate newly created contact record.');
701 $g = q("select def_gid from user where uid = %d limit 1",
702 intval($importer['uid'])
704 if($g && intval($g[0]['def_gid'])) {
705 require_once('include/group.php');
706 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
709 if($importer['page-flags'] == PAGE_NORMAL) {
711 $hash = random_string() . (string) time(); // Generate a confirm_key
713 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
714 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
715 intval($importer['uid']),
716 intval($contact_record['id']),
719 dbesc( t('Sharing notification from Diaspora network')),
721 dbesc(datetime_convert())
726 // automatic friend approval
728 require_once('include/Photo.php');
730 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
732 // technically they are sharing with us (CONTACT_IS_SHARING),
733 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
734 // we are going to change the relationship and make them a follower.
736 if($importer['page-flags'] == PAGE_FREELOVE)
737 $new_relation = CONTACT_IS_FRIEND;
739 $new_relation = CONTACT_IS_FOLLOWER;
741 $r = q("UPDATE `contact` SET
748 `avatar-date` = '%s',
757 intval($new_relation),
758 dbesc(datetime_convert()),
759 dbesc(datetime_convert()),
760 dbesc(datetime_convert()),
761 intval($contact_record['id'])
764 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
766 $ret = diaspora_share($u[0],$contact_record);
772 function diaspora_post_allow($importer,$contact, $is_comment = false) {
774 // perhaps we were already sharing with this person. Now they're sharing with us.
775 // That makes us friends.
776 // Normally this should have handled by getting a request - but this could get lost
777 if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
778 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
779 intval(CONTACT_IS_FRIEND),
780 intval($contact['id']),
781 intval($importer['uid'])
783 $contact['rel'] = CONTACT_IS_FRIEND;
784 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
787 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
789 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
791 if($contact['rel'] == CONTACT_IS_FOLLOWER)
792 if(($importer['page-flags'] == PAGE_COMMUNITY) OR $is_comment)
795 // Messages for the global users are always accepted
796 if ($importer['uid'] == 0)
802 function diaspora_is_redmatrix($url) {
803 return(strstr($url, "/channel/"));
806 function diaspora_plink($addr, $guid) {
807 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", $addr);
811 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
813 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
814 // So we try another way as well.
815 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
817 $r[0]["network"] = $s[0]["network"];
819 if ($r[0]["network"] == NETWORK_DFRN)
820 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
822 if (diaspora_is_redmatrix($r[0]["url"]))
823 return $r[0]["url"]."/?f=&mid=".$guid;
825 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
828 function diaspora_post($importer,$xml,$msg) {
831 $guid = notags(unxmlify($xml->guid));
832 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
834 if($diaspora_handle != $msg['author']) {
835 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
839 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
841 logger('diaspora_post: A Contact for handle '.$diaspora_handle.' and user '.$importer['uid'].' was not found');
845 if(! diaspora_post_allow($importer,$contact, false)) {
846 logger('diaspora_post: Ignoring this author.');
850 $message_id = $diaspora_handle . ':' . $guid;
851 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
852 intval($importer['uid']),
856 logger('diaspora_post: message exists: ' . $guid);
860 $created = unxmlify($xml->created_at);
861 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
863 $body = diaspora2bb($xml->raw_message);
867 $datarray["object"] = json_encode($xml);
869 if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
870 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
872 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
873 // Add OEmbed and other information to the body
874 if (!diaspora_is_redmatrix($contact['url']))
875 $body = add_page_info_to_body($body, false, true);
880 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
882 foreach($matches as $mtch) {
883 if(strlen($str_tags))
885 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
889 $plink = diaspora_plink($diaspora_handle, $guid);
891 $datarray['uid'] = $importer['uid'];
892 $datarray['contact-id'] = $contact['id'];
893 $datarray['wall'] = 0;
894 $datarray['network'] = NETWORK_DIASPORA;
895 $datarray['verb'] = ACTIVITY_POST;
896 $datarray['guid'] = $guid;
897 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
898 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
899 $datarray['private'] = $private;
900 $datarray['parent'] = 0;
901 $datarray['plink'] = $plink;
902 $datarray['owner-name'] = $contact['name'];
903 $datarray['owner-link'] = $contact['url'];
904 //$datarray['owner-avatar'] = $contact['thumb'];
905 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
906 $datarray['author-name'] = $contact['name'];
907 $datarray['author-link'] = $contact['url'];
908 $datarray['author-avatar'] = $contact['thumb'];
909 $datarray['body'] = $body;
910 $datarray['tag'] = $str_tags;
911 if ($xml->provider_display_name)
912 $datarray["app"] = unxmlify($xml->provider_display_name);
914 $datarray['app'] = 'Diaspora';
916 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
918 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
920 DiasporaFetchGuid($datarray);
921 $message_id = item_store($datarray);
923 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
929 function DiasporaFetchGuid($item) {
930 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
931 function ($match) use ($item){
932 return(DiasporaFetchGuidSub($match, $item));
936 function DiasporaFetchGuidSub($match, $item) {
939 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
940 diaspora_store_by_guid($match[1], $item["owner-link"]);
943 function diaspora_store_by_guid($guid, $server, $uid = 0) {
944 require_once("include/Contact.php");
946 $serverparts = parse_url($server);
947 $server = $serverparts["scheme"]."://".$serverparts["host"];
949 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
951 $item = diaspora_fetch_message($guid, $server);
956 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
958 $body = $item["body"];
959 $str_tags = $item["tag"];
961 $created = $item["created"];
962 $author = $item["author"];
963 $guid = $item["guid"];
964 $private = $item["private"];
965 $object = $item["object"];
966 $objecttype = $item["object-type"];
968 $message_id = $author.':'.$guid;
969 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
976 $person = find_diaspora_person_by_handle($author);
978 $contact_id = get_contact($person['url'], $uid);
980 $contacts = q("SELECT * FROM `contact` WHERE `id` = %d", intval($contact_id));
981 $importers = q("SELECT * FROM `user` WHERE `uid` = %d", intval($uid));
983 if ($contacts AND $importers)
984 if(!diaspora_post_allow($importers[0],$contacts[0], false)) {
985 logger('Ignoring author '.$person['url'].' for uid '.$uid);
988 logger('Author '.$person['url'].' is allowed for uid '.$uid);
991 $datarray['uid'] = $uid;
992 $datarray['contact-id'] = $contact_id;
993 $datarray['wall'] = 0;
994 $datarray['network'] = NETWORK_DIASPORA;
995 $datarray['guid'] = $guid;
996 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
997 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
998 $datarray['private'] = $private;
999 $datarray['parent'] = 0;
1000 $datarray['plink'] = diaspora_plink($author, $guid);
1001 $datarray['author-name'] = $person['name'];
1002 $datarray['author-link'] = $person['url'];
1003 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1004 $datarray['owner-name'] = $datarray['author-name'];
1005 $datarray['owner-link'] = $datarray['author-link'];
1006 $datarray['owner-avatar'] = $datarray['author-avatar'];
1007 $datarray['body'] = $body;
1008 $datarray['tag'] = $str_tags;
1009 $datarray['app'] = $app;
1010 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1011 $datarray['object'] = $object;
1012 $datarray['object-type'] = $objecttype;
1014 if ($datarray['contact-id'] == 0)
1017 DiasporaFetchGuid($datarray);
1018 $message_id = item_store($datarray);
1021 // Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
1026 function diaspora_fetch_message($guid, $server, $level = 0) {
1033 // This will not work if the server is not a Diaspora server
1034 $source_url = $server.'/p/'.$guid.'.xml';
1035 $x = fetch_url($source_url);
1039 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1040 $source_xml = parse_xml_string($x,false);
1043 $item["app"] = 'Diaspora';
1044 $item["guid"] = $guid;
1047 if ($source_xml->post->status_message->created_at)
1048 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1050 if ($source_xml->post->status_message->provider_display_name)
1051 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1053 if ($source_xml->post->status_message->diaspora_handle)
1054 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1056 if ($source_xml->post->status_message->guid)
1057 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1059 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1060 $item["object"] = json_encode($source_xml->post);
1062 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1063 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1064 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1065 $body = scale_external_images($body,false);
1066 } elseif($source_xml->post->asphoto->image_url) {
1067 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1068 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1069 $body = scale_external_images($body);
1070 } elseif($source_xml->post->status_message) {
1071 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1073 // Checking for embedded pictures
1074 if($source_xml->post->status_message->photo->remote_photo_path AND
1075 $source_xml->post->status_message->photo->remote_photo_name) {
1077 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1079 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1080 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1082 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1084 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1086 $item["object-type"] = ACTIVITY_OBJ_NOTE;
1088 $body = scale_external_images($body);
1090 // Add OEmbed and other information to the body
1091 // To-Do: It could be a repeated redmatrix item
1092 // Then we shouldn't add further data to it
1093 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1094 $body = add_page_info_to_body($body, false, true);
1096 } elseif($source_xml->post->reshare) {
1097 // Reshare of a reshare
1098 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1100 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1101 logger('no content found: '.print_r($source_xml,true));
1105 if (trim($body) == "")
1109 $item["body"] = $body;
1114 function diaspora_reshare($importer,$xml,$msg) {
1116 logger('diaspora_reshare: init: ' . print_r($xml,true));
1119 $guid = notags(unxmlify($xml->guid));
1120 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1123 if($diaspora_handle != $msg['author']) {
1124 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1128 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1132 if(! diaspora_post_allow($importer,$contact, false)) {
1133 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1137 $message_id = $diaspora_handle . ':' . $guid;
1138 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1139 intval($importer['uid']),
1143 logger('diaspora_reshare: message exists: ' . $guid);
1147 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1148 $orig_guid = notags(unxmlify($xml->root_guid));
1149 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1151 $create_original_post = false;
1153 // Do we already have this item?
1154 $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",
1156 dbesc(NETWORK_DIASPORA)
1159 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1161 // Maybe it is already a reshared item?
1162 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1163 require_once('include/api.php');
1164 if (api_share_as_retweet($r[0]))
1167 $body = $r[0]["body"];
1168 $str_tags = $r[0]["tag"];
1169 $app = $r[0]["app"];
1170 $orig_created = $r[0]["created"];
1171 $orig_plink = $r[0]["plink"];
1172 $orig_uri = $r[0]["uri"];
1173 $object = $r[0]["object"];
1174 $objecttype = $r[0]["object-type"];
1183 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1184 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1185 $item = diaspora_fetch_message($orig_guid, $server);
1188 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1189 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1190 $item = diaspora_fetch_message($orig_guid, $server);
1193 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1194 logger('3rd 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 = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1199 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1200 $item = diaspora_fetch_message($orig_guid, $server);
1204 $body = $item["body"];
1205 $str_tags = $item["tag"];
1206 $app = $item["app"];
1207 $orig_created = $item["created"];
1208 $orig_author = $item["author"];
1209 $orig_guid = $item["guid"];
1210 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1211 $orig_uri = $orig_author.':'.$orig_guid;
1212 $create_original_post = ($body != "");
1213 $object = $item["object"];
1214 $objecttype = $item["object-type"];
1218 $plink = diaspora_plink($diaspora_handle, $guid);
1220 $person = find_diaspora_person_by_handle($orig_author);
1222 $created = unxmlify($xml->created_at);
1223 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1225 $datarray = array();
1227 $datarray['uid'] = $importer['uid'];
1228 $datarray['contact-id'] = $contact['id'];
1229 $datarray['wall'] = 0;
1230 $datarray['network'] = NETWORK_DIASPORA;
1231 $datarray['guid'] = $guid;
1232 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1233 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1234 $datarray['private'] = $private;
1235 $datarray['parent'] = 0;
1236 $datarray['plink'] = $plink;
1237 $datarray['owner-name'] = $contact['name'];
1238 $datarray['owner-link'] = $contact['url'];
1239 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1240 if (!intval(get_config('system','wall-to-wall_share'))) {
1241 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1243 $datarray['author-name'] = $contact['name'];
1244 $datarray['author-link'] = $contact['url'];
1245 $datarray['author-avatar'] = $contact['thumb'];
1246 $datarray['body'] = $prefix.$body."[/share]";
1248 // Let reshared messages look like wall-to-wall posts
1249 $datarray['author-name'] = $person['name'];
1250 $datarray['author-link'] = $person['url'];
1251 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1252 $datarray['body'] = $body;
1255 $datarray["object"] = json_encode($xml);
1256 $datarray['object-type'] = $objecttype;
1258 $datarray['tag'] = $str_tags;
1259 $datarray['app'] = $app;
1261 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1262 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1264 // Store the original item of a reshare
1265 if ($create_original_post) {
1266 require_once("include/Contact.php");
1268 $datarray2 = $datarray;
1270 $datarray2['uid'] = 0;
1271 $datarray2['contact-id'] = get_contact($person['url'], 0);
1272 $datarray2['guid'] = $orig_guid;
1273 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1274 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1275 $datarray2['parent'] = 0;
1276 $datarray2['plink'] = $orig_plink;
1278 $datarray2['author-name'] = $person['name'];
1279 $datarray2['author-link'] = $person['url'];
1280 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1281 $datarray2['owner-name'] = $datarray2['author-name'];
1282 $datarray2['owner-link'] = $datarray2['author-link'];
1283 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1284 $datarray2['body'] = $body;
1285 $datarray2["object"] = $object;
1287 DiasporaFetchGuid($datarray2);
1288 $message_id = item_store($datarray2);
1290 logger("Store original item ".$orig_guid." under message id ".$message_id);
1293 DiasporaFetchGuid($datarray);
1294 $message_id = item_store($datarray);
1301 function diaspora_asphoto($importer,$xml,$msg) {
1302 logger('diaspora_asphoto called');
1305 $guid = notags(unxmlify($xml->guid));
1306 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1308 if($diaspora_handle != $msg['author']) {
1309 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1313 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1317 if(! diaspora_post_allow($importer,$contact, false)) {
1318 logger('diaspora_asphoto: Ignoring this author.');
1322 $message_id = $diaspora_handle . ':' . $guid;
1323 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1324 intval($importer['uid']),
1328 logger('diaspora_asphoto: message exists: ' . $guid);
1332 $created = unxmlify($xml->created_at);
1333 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1335 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1336 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1337 $body = scale_external_images($body,false);
1339 elseif($xml->image_url) {
1340 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1341 $body = scale_external_images($body);
1344 logger('diaspora_asphoto: no photo url found.');
1348 $plink = diaspora_plink($diaspora_handle, $guid);
1350 $datarray = array();
1352 $datarray['uid'] = $importer['uid'];
1353 $datarray['contact-id'] = $contact['id'];
1354 $datarray['wall'] = 0;
1355 $datarray['network'] = NETWORK_DIASPORA;
1356 $datarray['guid'] = $guid;
1357 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1358 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1359 $datarray['private'] = $private;
1360 $datarray['parent'] = 0;
1361 $datarray['plink'] = $plink;
1362 $datarray['owner-name'] = $contact['name'];
1363 $datarray['owner-link'] = $contact['url'];
1364 //$datarray['owner-avatar'] = $contact['thumb'];
1365 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1366 $datarray['author-name'] = $contact['name'];
1367 $datarray['author-link'] = $contact['url'];
1368 $datarray['author-avatar'] = $contact['thumb'];
1369 $datarray['body'] = $body;
1370 $datarray["object"] = json_encode($xml);
1371 $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1373 $datarray['app'] = 'Diaspora/Cubbi.es';
1375 DiasporaFetchGuid($datarray);
1376 $message_id = item_store($datarray);
1379 // q("update item set plink = '%s' where id = %d",
1380 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1381 // intval($message_id)
1394 function diaspora_comment($importer,$xml,$msg) {
1397 $guid = notags(unxmlify($xml->guid));
1398 $parent_guid = notags(unxmlify($xml->parent_guid));
1399 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1400 $target_type = notags(unxmlify($xml->target_type));
1401 $text = unxmlify($xml->text);
1402 $author_signature = notags(unxmlify($xml->author_signature));
1404 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1406 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1408 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1412 if(! diaspora_post_allow($importer,$contact, true)) {
1413 logger('diaspora_comment: Ignoring this author.');
1417 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1418 intval($importer['uid']),
1422 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1426 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1427 intval($importer['uid']),
1432 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1435 $person = find_diaspora_person_by_handle($diaspora_handle);
1436 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1440 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1442 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1443 intval($importer['uid']),
1450 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1453 $parent_item = $r[0];
1456 /* How Diaspora performs comment signature checking:
1458 - If an item has been sent by the comment author to the top-level post owner to relay on
1459 to the rest of the contacts on the top-level post, the top-level post owner should check
1460 the author_signature, then create a parent_author_signature before relaying the comment on
1461 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1462 check only the parent_author_signature. Basically, they trust that the top-level post
1463 owner has already verified the authenticity of anything he/she sends out
1464 - In either case, the signature that get checked is the signature created by the person
1468 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1471 if($parent_author_signature) {
1472 // If a parent_author_signature exists, then we've received the comment
1473 // relayed from the top-level post owner. There's no need to check the
1474 // author_signature if the parent_author_signature is valid
1476 $parent_author_signature = base64_decode($parent_author_signature);
1478 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1479 logger('diaspora_comment: top-level owner verification failed.');
1484 // If there's no parent_author_signature, then we've received the comment
1485 // from the comment creator. In that case, the person is commenting on
1486 // our post, so he/she must be a contact of ours and his/her public key
1487 // should be in $msg['key']
1489 $author_signature = base64_decode($author_signature);
1491 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1492 logger('diaspora_comment: comment author verification failed.');
1497 // Phew! Everything checks out. Now create an item.
1499 // Find the original comment author information.
1500 // We need this to make sure we display the comment author
1501 // information (name and avatar) correctly.
1502 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1505 $person = find_diaspora_person_by_handle($diaspora_handle);
1507 if(! is_array($person)) {
1508 logger('diaspora_comment: unable to find author details');
1513 $body = diaspora2bb($text);
1514 $message_id = $diaspora_handle . ':' . $guid;
1516 $datarray = array();
1518 $datarray['uid'] = $importer['uid'];
1519 $datarray['contact-id'] = $contact['id'];
1520 $datarray['type'] = 'remote-comment';
1521 $datarray['wall'] = $parent_item['wall'];
1522 $datarray['network'] = NETWORK_DIASPORA;
1523 $datarray['verb'] = ACTIVITY_POST;
1524 $datarray['gravity'] = GRAVITY_COMMENT;
1525 $datarray['guid'] = $guid;
1526 $datarray['uri'] = $message_id;
1527 $datarray['parent-uri'] = $parent_item['uri'];
1529 // No timestamps for comments? OK, we'll the use current time.
1530 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1531 $datarray['private'] = $parent_item['private'];
1533 $datarray['owner-name'] = $parent_item['owner-name'];
1534 $datarray['owner-link'] = $parent_item['owner-link'];
1535 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1537 $datarray['author-name'] = $person['name'];
1538 $datarray['author-link'] = $person['url'];
1539 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1540 $datarray['body'] = $body;
1541 $datarray["object"] = json_encode($xml);
1542 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1544 // We can't be certain what the original app is if the message is relayed.
1545 if(($parent_item['origin']) && (! $parent_author_signature))
1546 $datarray['app'] = 'Diaspora';
1548 DiasporaFetchGuid($datarray);
1549 $message_id = item_store($datarray);
1551 $datarray['id'] = $message_id;
1554 //q("update item set plink = '%s' where id = %d",
1555 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1556 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1557 // intval($message_id)
1561 if(($parent_item['origin']) && (! $parent_author_signature)) {
1562 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1563 intval($message_id),
1564 dbesc($signed_data),
1565 dbesc(base64_encode($author_signature)),
1566 dbesc($diaspora_handle)
1569 // if the message isn't already being relayed, notify others
1570 // the existence of parent_author_signature means the parent_author or owner
1571 // is already relaying.
1573 proc_run('php','include/notifier.php','comment-import',$message_id);
1576 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1577 dbesc($parent_item['uri']),
1578 intval($importer['uid'])
1581 if(count($myconv)) {
1582 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1584 foreach($myconv as $conv) {
1586 // now if we find a match, it means we're in this conversation
1588 if(! link_compare($conv['author-link'],$importer_url))
1591 require_once('include/enotify.php');
1593 $conv_parent = $conv['parent'];
1596 'type' => NOTIFY_COMMENT,
1597 'notify_flags' => $importer['notify-flags'],
1598 'language' => $importer['language'],
1599 'to_name' => $importer['username'],
1600 'to_email' => $importer['email'],
1601 'uid' => $importer['uid'],
1602 'item' => $datarray,
1603 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1604 'source_name' => $datarray['author-name'],
1605 'source_link' => $datarray['author-link'],
1606 'source_photo' => $datarray['author-avatar'],
1607 'verb' => ACTIVITY_POST,
1609 'parent' => $conv_parent,
1610 'parent_uri' => $parent_uri
1613 // only send one notification
1623 function diaspora_conversation($importer,$xml,$msg) {
1627 $guid = notags(unxmlify($xml->guid));
1628 $subject = notags(unxmlify($xml->subject));
1629 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1630 $participant_handles = notags(unxmlify($xml->participant_handles));
1631 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1633 $parent_uri = $diaspora_handle . ':' . $guid;
1635 $messages = $xml->message;
1637 if(! count($messages)) {
1638 logger('diaspora_conversation: empty conversation');
1642 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1644 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1648 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1649 logger('diaspora_conversation: Ignoring this author.');
1653 $conversation = null;
1655 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1656 intval($importer['uid']),
1660 $conversation = $c[0];
1662 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1663 intval($importer['uid']),
1665 dbesc($diaspora_handle),
1666 dbesc(datetime_convert('UTC','UTC',$created_at)),
1667 dbesc(datetime_convert()),
1669 dbesc($participant_handles)
1672 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1673 intval($importer['uid']),
1677 $conversation = $c[0];
1679 if(! $conversation) {
1680 logger('diaspora_conversation: unable to create conversation.');
1684 foreach($messages as $mesg) {
1688 $msg_guid = notags(unxmlify($mesg->guid));
1689 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1690 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1691 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1692 $msg_text = unxmlify($mesg->text);
1693 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1694 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1695 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1696 if($msg_conversation_guid != $guid) {
1697 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1701 $body = diaspora2bb($msg_text);
1702 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1704 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1706 $author_signature = base64_decode($msg_author_signature);
1708 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1713 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1715 if(is_array($person) && x($person,'pubkey'))
1716 $key = $person['pubkey'];
1718 logger('diaspora_conversation: unable to find author details');
1723 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1724 logger('diaspora_conversation: verification failed.');
1728 if($msg_parent_author_signature) {
1729 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1731 $parent_author_signature = base64_decode($msg_parent_author_signature);
1735 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1736 logger('diaspora_conversation: owner verification failed.');
1741 $r = q("select id from mail where `uri` = '%s' limit 1",
1745 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1749 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')",
1750 intval($importer['uid']),
1752 intval($conversation['id']),
1753 dbesc($person['name']),
1754 dbesc($person['photo']),
1755 dbesc($person['url']),
1756 intval($contact['id']),
1763 dbesc($msg_created_at)
1766 q("update conv set updated = '%s' where id = %d",
1767 dbesc(datetime_convert()),
1768 intval($conversation['id'])
1771 require_once('include/enotify.php');
1773 'type' => NOTIFY_MAIL,
1774 'notify_flags' => $importer['notify-flags'],
1775 'language' => $importer['language'],
1776 'to_name' => $importer['username'],
1777 'to_email' => $importer['email'],
1778 'uid' =>$importer['uid'],
1779 'item' => array('subject' => $subject, 'body' => $body),
1780 'source_name' => $person['name'],
1781 'source_link' => $person['url'],
1782 'source_photo' => $person['thumb'],
1783 'verb' => ACTIVITY_POST,
1791 function diaspora_message($importer,$xml,$msg) {
1795 $msg_guid = notags(unxmlify($xml->guid));
1796 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1797 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1798 $msg_author_signature = notags(unxmlify($xml->author_signature));
1799 $msg_text = unxmlify($xml->text);
1800 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1801 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1802 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1804 $parent_uri = $msg_diaspora_handle . ':' . $msg_parent_guid;
1806 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1808 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1812 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1813 logger('diaspora_message: Ignoring this author.');
1817 $conversation = null;
1819 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1820 intval($importer['uid']),
1821 dbesc($msg_conversation_guid)
1824 $conversation = $c[0];
1826 logger('diaspora_message: conversation not available.');
1832 $body = diaspora2bb($msg_text);
1833 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1835 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1838 $author_signature = base64_decode($msg_author_signature);
1840 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1841 if(is_array($person) && x($person,'pubkey'))
1842 $key = $person['pubkey'];
1844 logger('diaspora_message: unable to find author details');
1848 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1849 logger('diaspora_message: verification failed.');
1853 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1855 intval($importer['uid'])
1858 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1862 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')",
1863 intval($importer['uid']),
1865 intval($conversation['id']),
1866 dbesc($person['name']),
1867 dbesc($person['photo']),
1868 dbesc($person['url']),
1869 intval($contact['id']),
1870 dbesc($conversation['subject']),
1876 dbesc($msg_created_at)
1879 q("update conv set updated = '%s' where id = %d",
1880 dbesc(datetime_convert()),
1881 intval($conversation['id'])
1887 function diaspora_participation($importer,$xml) {
1888 logger("Unsupported message type 'participation' ".print_r($xml, true));
1891 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1895 logger('diaspora_photo: init',LOGGER_DEBUG);
1897 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1899 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1901 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1903 $guid = notags(unxmlify($xml->guid));
1905 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1907 $public = notags(unxmlify($xml->public));
1909 $created_at = notags(unxmlify($xml_created_at));
1911 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1913 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1915 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1919 if(! diaspora_post_allow($importer,$contact, false)) {
1920 logger('diaspora_photo: Ignoring this author.');
1924 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1925 intval($importer['uid']),
1926 dbesc($status_message_guid)
1929 /* deactivated by now since it can lead to multiplicated pictures in posts.
1931 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1934 $person = find_diaspora_person_by_handle($diaspora_handle);
1935 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1939 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1941 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1942 intval($importer['uid']),
1943 dbesc($status_message_guid)
1950 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1951 intval($importer['uid']),
1952 dbesc(serialize($msg)),
1953 intval($attempt + 1)
1957 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1961 $parent_item = $r[0];
1963 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1965 $link_text = scale_external_images($link_text, true,
1966 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1968 if(strpos($parent_item['body'],$link_text) === false) {
1969 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1970 dbesc($link_text . $parent_item['body']),
1971 intval($parent_item['id']),
1972 intval($parent_item['uid'])
1974 update_thread($parent_item['id']);
1983 function diaspora_like($importer,$xml,$msg) {
1986 $guid = notags(unxmlify($xml->guid));
1987 $parent_guid = notags(unxmlify($xml->parent_guid));
1988 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1989 $target_type = notags(unxmlify($xml->target_type));
1990 $positive = notags(unxmlify($xml->positive));
1991 $author_signature = notags(unxmlify($xml->author_signature));
1993 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1995 // likes on comments not supported here and likes on photos not supported by Diaspora
1997 // if($target_type !== 'Post')
2000 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
2002 logger('diaspora_like: cannot find contact: ' . $msg['author']);
2006 if(! diaspora_post_allow($importer,$contact, false)) {
2007 logger('diaspora_like: Ignoring this author.');
2011 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2012 intval($importer['uid']),
2017 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
2020 $person = find_diaspora_person_by_handle($diaspora_handle);
2021 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
2025 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
2027 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2028 intval($importer['uid']),
2035 logger('diaspora_like: parent item not found: ' . $guid);
2039 $parent_item = $r[0];
2041 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2042 intval($importer['uid']),
2046 if($positive === 'true') {
2047 logger('diaspora_like: duplicate like: ' . $guid);
2050 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2051 // It looks like "RelayableRetractions" are used for "unlike" instead
2052 if($positive === 'false') {
2053 logger('diaspora_like: received a like with positive set to "false"...ignoring');
2054 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2055 intval($r[0]['id']),
2056 intval($importer['uid'])
2058 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2059 // send notification via proc_run()
2063 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2064 // It looks like "RelayableRetractions" are used for "unlike" instead
2065 if($positive === 'false') {
2066 logger('diaspora_like: received a like with positive set to "false"');
2067 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2072 /* How Diaspora performs "like" signature checking:
2074 - If an item has been sent by the like author to the top-level post owner to relay on
2075 to the rest of the contacts on the top-level post, the top-level post owner should check
2076 the author_signature, then create a parent_author_signature before relaying the like on
2077 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2078 check only the parent_author_signature. Basically, they trust that the top-level post
2079 owner has already verified the authenticity of anything he/she sends out
2080 - In either case, the signature that get checked is the signature created by the person
2084 // Diaspora has changed the way they are signing the likes.
2085 // Just to make sure that we don't miss any likes we will check the old and the current way.
2086 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2088 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2092 if ($parent_author_signature) {
2093 // If a parent_author_signature exists, then we've received the like
2094 // relayed from the top-level post owner. There's no need to check the
2095 // author_signature if the parent_author_signature is valid
2097 $parent_author_signature = base64_decode($parent_author_signature);
2099 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2100 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2102 logger('diaspora_like: top-level owner verification failed.');
2106 // If there's no parent_author_signature, then we've received the like
2107 // from the like creator. In that case, the person is "like"ing
2108 // our post, so he/she must be a contact of ours and his/her public key
2109 // should be in $msg['key']
2111 $author_signature = base64_decode($author_signature);
2113 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2114 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2116 logger('diaspora_like: like creator verification failed.');
2121 // Phew! Everything checks out. Now create an item.
2123 // Find the original comment author information.
2124 // We need this to make sure we display the comment author
2125 // information (name and avatar) correctly.
2126 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2129 $person = find_diaspora_person_by_handle($diaspora_handle);
2131 if(! is_array($person)) {
2132 logger('diaspora_like: unable to find author details');
2137 $uri = $diaspora_handle . ':' . $guid;
2139 $activity = ACTIVITY_LIKE;
2140 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2141 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2142 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2143 $body = $parent_item['body'];
2148 <type>$objtype</type>
2150 <id>{$parent_item['uri']}</id>
2153 <content>$body</content>
2156 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2161 $arr['uid'] = $importer['uid'];
2162 $arr['guid'] = $guid;
2163 $arr['network'] = NETWORK_DIASPORA;
2164 $arr['contact-id'] = $contact['id'];
2165 $arr['type'] = 'activity';
2166 $arr['wall'] = $parent_item['wall'];
2167 $arr['gravity'] = GRAVITY_LIKE;
2168 $arr['parent'] = $parent_item['id'];
2169 $arr['parent-uri'] = $parent_item['uri'];
2171 $arr['owner-name'] = $parent_item['name'];
2172 $arr['owner-link'] = $parent_item['url'];
2173 //$arr['owner-avatar'] = $parent_item['thumb'];
2174 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2176 $arr['author-name'] = $person['name'];
2177 $arr['author-link'] = $person['url'];
2178 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2180 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2181 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2182 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2183 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2184 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2186 $arr['app'] = 'Diaspora';
2188 $arr['private'] = $parent_item['private'];
2189 $arr['verb'] = $activity;
2190 $arr['object-type'] = $objtype;
2191 $arr['object'] = $obj;
2192 $arr['visible'] = 1;
2194 $arr['last-child'] = 0;
2196 $message_id = item_store($arr);
2200 // q("update item set plink = '%s' where id = %d",
2201 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2202 // dbesc($a->get_baseurl().'/display/'.$guid),
2203 // intval($message_id)
2207 if(! $parent_author_signature) {
2208 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2209 intval($message_id),
2210 dbesc($signed_data),
2211 dbesc(base64_encode($author_signature)),
2212 dbesc($diaspora_handle)
2216 // if the message isn't already being relayed, notify others
2217 // the existence of parent_author_signature means the parent_author or owner
2218 // is already relaying. The parent_item['origin'] indicates the message was created on our system
2220 if(($parent_item['origin']) && (! $parent_author_signature))
2221 proc_run('php','include/notifier.php','comment-import',$message_id);
2226 function diaspora_retraction($importer,$xml) {
2229 $guid = notags(unxmlify($xml->guid));
2230 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2231 $type = notags(unxmlify($xml->type));
2233 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2237 if($type === 'Person') {
2238 require_once('include/Contact.php');
2239 contact_remove($contact['id']);
2241 elseif($type === 'Post') {
2242 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2244 intval($importer['uid'])
2247 if(link_compare($r[0]['author-link'],$contact['url'])) {
2248 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2249 dbesc(datetime_convert()),
2252 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2261 function diaspora_signed_retraction($importer,$xml,$msg) {
2264 $guid = notags(unxmlify($xml->target_guid));
2265 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2266 $type = notags(unxmlify($xml->target_type));
2267 $sig = notags(unxmlify($xml->target_author_signature));
2269 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2271 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2273 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2278 $signed_data = $guid . ';' . $type ;
2281 /* How Diaspora performs relayable_retraction signature checking:
2283 - If an item has been sent by the item author to the top-level post owner to relay on
2284 to the rest of the contacts on the top-level post, the top-level post owner checks
2285 the author_signature, then creates a parent_author_signature before relaying the item on
2286 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2287 check only the parent_author_signature. Basically, they trust that the top-level post
2288 owner has already verified the authenticity of anything he/she sends out
2289 - In either case, the signature that get checked is the signature created by the person
2293 if($parent_author_signature) {
2295 $parent_author_signature = base64_decode($parent_author_signature);
2297 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2298 logger('diaspora_signed_retraction: top-level post owner verification failed');
2305 $sig_decode = base64_decode($sig);
2307 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2308 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2313 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2314 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2316 intval($importer['uid'])
2319 if(link_compare($r[0]['author-link'],$contact['url'])) {
2320 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2321 dbesc(datetime_convert()),
2322 dbesc(datetime_convert()),
2325 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2327 // Now check if the retraction needs to be relayed by us
2329 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2330 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2331 // The only item with `parent` and `id` as the parent id is the parent item.
2332 $p = q("select origin from item where parent = %d and id = %d limit 1",
2337 if(($p[0]['origin']) && (! $parent_author_signature)) {
2338 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2340 dbesc($signed_data),
2342 dbesc($diaspora_handle)
2345 // the existence of parent_author_signature would have meant the parent_author or owner
2346 // is already relaying.
2347 logger('diaspora_signed_retraction: relaying relayable_retraction');
2349 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2356 logger('diaspora_signed_retraction: unknown type: ' . $type);
2362 function diaspora_profile($importer,$xml,$msg) {
2365 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2368 if($diaspora_handle != $msg['author']) {
2369 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2373 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2377 if($contact['blocked']) {
2378 logger('diaspora_post: Ignoring this author.');
2382 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2383 $image_url = unxmlify($xml->image_url);
2384 $birthday = unxmlify($xml->birthday);
2385 $location = diaspora2bb(unxmlify($xml->location));
2386 $about = diaspora2bb(unxmlify($xml->bio));
2387 $gender = unxmlify($xml->gender);
2388 $tags = unxmlify($xml->tag_string);
2390 $tags = explode("#", $tags);
2392 $keywords = array();
2393 foreach ($tags as $tag) {
2394 $tag = trim(strtolower($tag));
2399 $keywords = implode(", ", $keywords);
2401 $handle_parts = explode("@", $diaspora_handle);
2403 $name = $handle_parts[0];
2406 if( preg_match("|^https?://|", $image_url) === 0) {
2407 $image_url = "http://" . $handle_parts[1] . $image_url;
2410 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2411 intval($importer['uid']),
2412 intval($contact['id'])
2414 $oldphotos = ((count($r)) ? $r : null);*/
2416 require_once('include/Photo.php');
2418 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2420 // Generic birthday. We don't know the timezone. The year is irrelevant.
2422 $birthday = str_replace('1000','1901',$birthday);
2424 if ($birthday != "")
2425 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2427 // this is to prevent multiple birthday notifications in a single year
2428 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2430 if(substr($birthday,5) === substr($contact['bd'],5))
2431 $birthday = $contact['bd'];
2433 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2434 // Not doing this currently because D* protocol is scheduled for revision soon.
2436 $r = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2438 dbesc(datetime_convert()),
2442 dbesc(datetime_convert()),
2448 intval($contact['id']),
2449 intval($importer['uid'])
2452 if (unxmlify($xml->searchable) == "true") {
2453 require_once('include/socgraph.php');
2454 poco_check($contact['url'], $name, NETWORK_DIASPORA, $images[0], $about, $location, $gender, $keywords, "",
2455 datetime_convert(), 2, $contact['id'], $importer['uid']);
2459 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
2460 dbesc(normalise_link($contact['url'])));
2462 if (count($author) == 0) {
2463 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`, `location`, `about`) VALUES ('%s', '%s', '%s', '%s', '%s')",
2464 dbesc(normalise_link($contact['url'])), dbesc($name), dbesc($location), dbesc($about), dbesc($images[0]));
2466 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
2467 dbesc(normalise_link($contact['url'])));
2468 } else if (normalise_link($contact['url']).$name.$location.$about != normalise_link($author[0]["url"]).$author[0]["name"].$author[0]["location"].$author[0]["about"]) {
2469 q("UPDATE unique_contacts SET name = '%s', avatar = '%s', `location` = '%s', `about` = '%s' WHERE url = '%s'",
2470 dbesc($name), dbesc($images[0]), dbesc($location), dbesc($about), dbesc(normalise_link($contact['url'])));
2475 foreach($oldphotos as $ph) {
2476 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2477 intval($importer['uid']),
2478 intval($contact['id']),
2479 dbesc($ph['resource-id'])
2489 function diaspora_share($me,$contact) {
2491 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2492 $theiraddr = $contact['addr'];
2494 $tpl = get_markup_template('diaspora_share.tpl');
2495 $msg = replace_macros($tpl, array(
2496 '$sender' => $myaddr,
2497 '$recipient' => $theiraddr
2500 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2501 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2503 return(diaspora_transmit($owner,$contact,$slap, false));
2506 function diaspora_unshare($me,$contact) {
2509 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2511 $tpl = get_markup_template('diaspora_retract.tpl');
2512 $msg = replace_macros($tpl, array(
2513 '$guid' => $me['guid'],
2514 '$type' => 'Person',
2515 '$handle' => $myaddr
2518 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2519 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2521 return(diaspora_transmit($owner,$contact,$slap, false));
2526 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2529 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2530 $theiraddr = $contact['addr'];
2534 $title = $item['title'];
2535 $body = $item['body'];
2538 // We're trying to match Diaspora's split message/photo protocol but
2539 // all the photos are displayed on D* as links and not img's - even
2540 // though we're sending pretty much precisely what they send us when
2541 // doing the same operation.
2542 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2543 // which seems to get through intact.
2545 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2547 foreach($matches as $mtch) {
2549 $detail['str'] = $mtch[0];
2550 $detail['path'] = dirname($mtch[1]) . '/';
2551 $detail['file'] = basename($mtch[1]);
2552 $detail['guid'] = $item['guid'];
2553 $detail['handle'] = $myaddr;
2554 $images[] = $detail;
2555 $body = str_replace($detail['str'],$mtch[1],$body);
2560 //if(strlen($title))
2561 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2563 // convert to markdown
2564 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2565 //$body = bb2diaspora($body);
2569 $body = "## ".html_entity_decode($title)."\n\n".$body;
2571 if($item['attach']) {
2572 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2574 $body .= "\n" . t('Attachments:') . "\n";
2575 foreach($matches as $mtch) {
2576 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2582 $public = (($item['private']) ? 'false' : 'true');
2584 require_once('include/datetime.php');
2585 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2587 // Detect a share element and do a reshare
2588 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2589 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2590 $tpl = get_markup_template('diaspora_reshare.tpl');
2591 $msg = replace_macros($tpl, array(
2592 '$root_handle' => xmlify($ret['root_handle']),
2593 '$root_guid' => $ret['root_guid'],
2594 '$guid' => $item['guid'],
2595 '$handle' => xmlify($myaddr),
2596 '$public' => $public,
2597 '$created' => $created,
2598 '$provider' => $item["app"]
2601 $tpl = get_markup_template('diaspora_post.tpl');
2602 $msg = replace_macros($tpl, array(
2604 '$guid' => $item['guid'],
2605 '$handle' => xmlify($myaddr),
2606 '$public' => $public,
2607 '$created' => $created,
2608 '$provider' => $item["app"]
2612 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2614 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2615 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2617 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2619 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2621 if(count($images)) {
2622 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2625 return $return_code;
2628 function diaspora_is_reshare($body) {
2629 $body = trim($body);
2631 // Skip if it isn't a pure repeated messages
2632 // Does it start with a share?
2633 if (strpos($body, "[share") > 0)
2636 // Does it end with a share?
2637 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2640 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2641 // Skip if there is no shared message in there
2642 if ($body == $attributes)
2646 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2647 if ($matches[1] != "")
2648 $guid = $matches[1];
2650 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2651 if ($matches[1] != "")
2652 $guid = $matches[1];
2655 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2656 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2659 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2660 $ret["root_guid"] = $guid;
2666 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2667 if ($matches[1] != "")
2668 $profile = $matches[1];
2670 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2671 if ($matches[1] != "")
2672 $profile = $matches[1];
2676 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2677 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2681 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2682 if ($matches[1] != "")
2683 $link = $matches[1];
2685 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2686 if ($matches[1] != "")
2687 $link = $matches[1];
2689 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2690 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2696 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2698 if(! count($images))
2700 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2702 $tpl = get_markup_template('diaspora_photo.tpl');
2703 foreach($images as $image) {
2704 if(! stristr($image['path'],$mysite))
2706 $resource = str_replace('.jpg','',$image['file']);
2707 $resource = substr($resource,0,strpos($resource,'-'));
2709 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2711 intval($owner['uid'])
2715 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2716 $msg = replace_macros($tpl,array(
2717 '$path' => xmlify($image['path']),
2718 '$filename' => xmlify($image['file']),
2719 '$msg_guid' => xmlify($image['guid']),
2720 '$guid' => xmlify($r[0]['guid']),
2721 '$handle' => xmlify($image['handle']),
2722 '$public' => xmlify($public),
2723 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2727 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2728 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2729 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2731 diaspora_transmit($owner,$contact,$slap,$public_batch);
2736 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2739 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2740 // $theiraddr = $contact['addr'];
2742 // Diaspora doesn't support threaded comments, but some
2743 // versions of Diaspora (i.e. Diaspora-pistos) support
2744 // likes on comments
2745 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2746 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2747 dbesc($item['thr-parent'])
2751 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2752 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2753 // The only item with `parent` and `id` as the parent id is the parent item.
2754 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2755 intval($item['parent']),
2756 intval($item['parent'])
2764 if($item['verb'] === ACTIVITY_LIKE) {
2765 $tpl = get_markup_template('diaspora_like.tpl');
2767 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2768 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2769 // $positive = (($item['deleted']) ? 'false' : 'true');
2772 if(($item['deleted']))
2773 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2776 $tpl = get_markup_template('diaspora_comment.tpl');
2780 $text = html_entity_decode(bb2diaspora($item['body']));
2785 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2787 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2789 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2791 $msg = replace_macros($tpl,array(
2792 '$guid' => xmlify($item['guid']),
2793 '$parent_guid' => xmlify($parent['guid']),
2794 '$target_type' =>xmlify($target_type),
2795 '$authorsig' => xmlify($authorsig),
2796 '$body' => xmlify($text),
2797 '$positive' => xmlify($positive),
2798 '$handle' => xmlify($myaddr)
2801 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2803 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2804 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2806 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2810 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2814 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2815 // $theiraddr = $contact['addr'];
2817 $body = $item['body'];
2818 $text = html_entity_decode(bb2diaspora($body));
2820 // Diaspora doesn't support threaded comments, but some
2821 // versions of Diaspora (i.e. Diaspora-pistos) support
2822 // likes on comments
2823 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2824 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2825 dbesc($item['thr-parent'])
2829 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2830 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2831 // The only item with `parent` and `id` as the parent id is the parent item.
2832 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2833 intval($item['parent']),
2834 intval($item['parent'])
2843 $relay_retract = false;
2844 $sql_sign_id = 'iid';
2845 if( $item['deleted']) {
2846 $relay_retract = true;
2848 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2850 $sql_sign_id = 'retract_iid';
2851 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2853 elseif($item['verb'] === ACTIVITY_LIKE) {
2856 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2857 // $positive = (($item['deleted']) ? 'false' : 'true');
2860 $tpl = get_markup_template('diaspora_like_relay.tpl');
2862 else { // item is a comment
2863 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2867 // fetch the original signature if the relayable was created by a Diaspora
2868 // or DFRN user. Relayables for other networks are not supported.
2870 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2875 $signed_text = $orig_sign['signed_text'];
2876 $authorsig = $orig_sign['signature'];
2877 $handle = $orig_sign['signer'];
2881 // Author signature information (for likes, comments, and retractions of likes or comments,
2882 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2883 // function is called
2884 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2888 /* Since the author signature is only checked by the parent, not by the relay recipients,
2889 * I think it may not be necessary for us to do so much work to preserve all the original
2890 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2891 * Let's just generate that and forget about all the original author signature stuff.
2893 * Note: this might be more of an problem if we want to support likes on comments for older
2894 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2895 * doing that, let's ignore it for now.
2897 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2901 $handle = diaspora_handle_from_contact($item['contact-id']);
2907 $sender_signed_text = $item['guid'] . ';' . $target_type;
2909 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2911 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2913 // Sign the relayable with the top-level owner's signature
2915 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2916 // stored in the database, because that provides the best chance that Diaspora will
2917 // be able to reconstruct the signed text the same way we did. This is particularly a
2918 // concern for the comment, whose signed text includes the text of the comment. The
2919 // smallest change in the text of the comment, including removing whitespace, will
2920 // make the signature verification fail. Since we translate from BB code to Diaspora's
2921 // markup at the top of this function, which is AFTER we placed the original $signed_text
2922 // in the database, it's hazardous to trust the original $signed_text.
2924 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2926 $msg = replace_macros($tpl,array(
2927 '$guid' => xmlify($item['guid']),
2928 '$parent_guid' => xmlify($parent['guid']),
2929 '$target_type' =>xmlify($target_type),
2930 '$authorsig' => xmlify($authorsig),
2931 '$parentsig' => xmlify($parentauthorsig),
2932 '$body' => xmlify($text),
2933 '$positive' => xmlify($positive),
2934 '$handle' => xmlify($handle)
2937 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2940 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2941 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2943 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2949 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2952 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2954 // Check whether the retraction is for a top-level post or whether it's a relayable
2955 if( $item['uri'] !== $item['parent-uri'] ) {
2957 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2958 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2962 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2963 $target_type = 'StatusMessage';
2966 $signed_text = $item['guid'] . ';' . $target_type;
2968 $msg = replace_macros($tpl, array(
2969 '$guid' => xmlify($item['guid']),
2970 '$type' => xmlify($target_type),
2971 '$handle' => xmlify($myaddr),
2972 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2975 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2976 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2978 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2981 function diaspora_send_mail($item,$owner,$contact) {
2984 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2986 $r = q("select * from conv where id = %d and uid = %d limit 1",
2987 intval($item['convid']),
2988 intval($item['uid'])
2992 logger('diaspora_send_mail: conversation not found.');
2998 'guid' => xmlify($cnv['guid']),
2999 'subject' => xmlify($cnv['subject']),
3000 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
3001 'diaspora_handle' => xmlify($cnv['creator']),
3002 'participant_handles' => xmlify($cnv['recips'])
3005 $body = bb2diaspora($item['body']);
3006 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
3008 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
3009 . $created . ';' . $myaddr . ';' . $cnv['guid'];
3011 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
3014 'guid' => xmlify($item['guid']),
3015 'parent_guid' => xmlify($cnv['guid']),
3016 'parent_author_signature' => xmlify($sig),
3017 'author_signature' => xmlify($sig),
3018 'text' => xmlify($body),
3019 'created_at' => xmlify($created),
3020 'diaspora_handle' => xmlify($myaddr),
3021 'conversation_guid' => xmlify($cnv['guid'])
3024 if($item['reply']) {
3025 $tpl = get_markup_template('diaspora_message.tpl');
3026 $xmsg = replace_macros($tpl, array('$msg' => $msg));
3029 $conv['messages'] = array($msg);
3030 $tpl = get_markup_template('diaspora_conversation.tpl');
3031 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3034 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3036 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3037 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3039 return(diaspora_transmit($owner,$contact,$slap,false));
3044 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
3046 $enabled = intval(get_config('system','diaspora_enabled'));
3052 $logid = random_string(4);
3053 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3055 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3059 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
3061 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3065 if (!intval(get_config('system','diaspora_test'))) {
3066 post_url($dest_url . '/', $slap);
3067 $return_code = $a->get_curl_code();
3069 logger('diaspora_transmit: test_mode');
3074 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
3076 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3077 logger('diaspora_transmit: queue message');
3079 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3080 intval($contact['id']),
3081 dbesc(NETWORK_DIASPORA),
3083 intval($public_batch)
3086 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3089 // queue message for redelivery
3090 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3095 return(($return_code) ? $return_code : (-1));
3098 function diaspora_fetch_relay() {
3100 $serverdata = get_config("system", "relay_server");
3101 if ($serverdata == "")
3106 $servers = explode(",", $serverdata);
3108 foreach($servers AS $server) {
3109 $server = trim($server);
3110 $batch = $server."/receive/public";
3112 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3115 $addr = "relay@".str_replace("http://", "", normalise_link($server));
3117 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
3118 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
3123 dbesc(normalise_link($server)),
3125 dbesc(NETWORK_DIASPORA),
3126 intval(CONTACT_IS_FOLLOWER),
3127 dbesc(datetime_convert()),
3128 dbesc(datetime_convert()),
3129 dbesc(datetime_convert())
3132 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3134 $relay[] = $relais[0];
3136 $relay[] = $relais[0];