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 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
26 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
27 AND `account_expired` = 0 AND `account_removed` = 0 ",
28 dbesc(NETWORK_DIASPORA),
33 logger('diaspora_public: delivering to: ' . $rr['username']);
34 diaspora_dispatch($rr,$msg);
38 logger('diaspora_public: no subscribers');
43 function diaspora_dispatch($importer,$msg,$attempt=1) {
47 $enabled = intval(get_config('system','diaspora_enabled'));
49 logger('mod-diaspora: disabled');
53 // php doesn't like dashes in variable names
55 $msg['message'] = str_replace(
56 array('<activity_streams-photo>','</activity_streams-photo>'),
57 array('<asphoto>','</asphoto>'),
61 $parsed_xml = parse_xml_string($msg['message'],false);
63 $xmlbase = $parsed_xml->post;
65 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
68 if($xmlbase->request) {
69 $ret = diaspora_request($importer,$xmlbase->request);
71 elseif($xmlbase->status_message) {
72 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
74 elseif($xmlbase->profile) {
75 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
77 elseif($xmlbase->comment) {
78 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
80 elseif($xmlbase->like) {
81 $ret = diaspora_like($importer,$xmlbase->like,$msg);
83 elseif($xmlbase->asphoto) {
84 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
86 elseif($xmlbase->reshare) {
87 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
89 elseif($xmlbase->retraction) {
90 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
92 elseif($xmlbase->signed_retraction) {
93 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
95 elseif($xmlbase->relayable_retraction) {
96 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
98 elseif($xmlbase->photo) {
99 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
101 elseif($xmlbase->conversation) {
102 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
104 elseif($xmlbase->message) {
105 $ret = diaspora_message($importer,$xmlbase->message,$msg);
108 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
113 function diaspora_handle_from_contact($contact_id) {
116 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
118 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
124 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
126 if($contact['network'] === NETWORK_DIASPORA) {
127 $handle = $contact['addr'];
129 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
131 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
132 $baseurl_start = strpos($contact['url'],'://') + 3;
133 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
134 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
135 $handle = $contact['nick'] . '@' . $baseurl;
137 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
144 function diaspora_get_contact_by_handle($uid,$handle) {
145 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
146 dbesc(NETWORK_DIASPORA),
153 $handle_parts = explode("@", $handle);
154 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
155 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
166 function find_diaspora_person_by_handle($handle) {
176 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
177 dbesc(NETWORK_DIASPORA),
182 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
184 // update record occasionally so it doesn't get stale
185 $d = strtotime($person['updated'] . ' +00:00');
186 if($d < strtotime('now - 14 days'))
191 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
193 // If the person isn't in our 'fcontact' table, or if he/she is but
194 // his/her information hasn't been updated for more than 14 days, then
195 // we want to fetch the person's information from the remote server.
197 // Note that $person isn't changed by this block of code unless the
198 // person's information has been successfully fetched from the remote
199 // server. So if $person was 'false' to begin with (because he/she wasn't
200 // in the local cache), it'll stay false, and if $person held the local
201 // cache information to begin with, it'll keep that information. That way
202 // if there's a problem with the remote fetch, we can at least use our
203 // cached information--it's better than nothing.
205 if((! $person) || ($update)) {
206 // Lock the function to prevent race conditions if multiple items
207 // come in at the same time from a person who doesn't exist in
210 // Don't loop forever. On the last loop, try to create the contact
211 // whether the function is locked or not. Maybe the locking thread
212 // has died or something. At any rate, a duplicate in 'fcontact'
213 // is a much smaller problem than a deadlocked thread
214 $got_lock = lock_function('find_diaspora_person_by_handle', false);
215 if(($endlessloop + 1) >= $maxloops)
219 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
220 require_once('include/Scrape.php');
221 $r = probe_url($handle, PROBE_DIASPORA);
223 // Note that Friendica contacts can return a "Diaspora person"
224 // if Diaspora connectivity is enabled on their server
225 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
226 add_fcontact($r,$update);
230 unlock_function('find_diaspora_person_by_handle');
233 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
235 block_on_function_lock('find_diaspora_person_by_handle');
238 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
239 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
240 // The fact that the function was locked may mean that another process was creating the
241 // person's record. It could also mean another process was creating or updating an unrelated
244 // At any rate, we need to keep trying until we've either got the person or had a chance to
245 // try to fetch his/her remote information. But we don't want to block on locking the
246 // function, because if the other process is creating the record, then when we acquire the lock
247 // we'll dive right into creating another, duplicate record. We DO want to at least wait
248 // until the lock is released, so we don't flood the database with requests.
250 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
251 // we do have some information for the person
257 function get_diaspora_key($uri) {
258 logger('Fetching diaspora key for: ' . $uri);
260 $r = find_diaspora_person_by_handle($uri);
267 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
270 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
273 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
275 // $b64_data = base64_encode($msg);
276 // $b64url_data = base64url_encode($b64_data);
278 $b64url_data = base64url_encode($msg);
280 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
282 $type = 'application/xml';
283 $encoding = 'base64url';
286 $signable_data = $data . '.' . base64url_encode($type) . '.'
287 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
289 $signature = rsa_sign($signable_data,$prvkey);
290 $sig = base64url_encode($signature);
293 <?xml version='1.0' encoding='UTF-8'?>
294 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
296 <author_id>$handle</author_id>
299 <me:encoding>base64url</me:encoding>
300 <me:alg>RSA-SHA256</me:alg>
301 <me:data type="application/xml">$data</me:data>
302 <me:sig>$sig</me:sig>
307 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
315 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
319 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
321 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
323 // without a public key nothing will work
326 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
330 $inner_aes_key = random_string(32);
331 $b_inner_aes_key = base64_encode($inner_aes_key);
332 $inner_iv = random_string(16);
333 $b_inner_iv = base64_encode($inner_iv);
335 $outer_aes_key = random_string(32);
336 $b_outer_aes_key = base64_encode($outer_aes_key);
337 $outer_iv = random_string(16);
338 $b_outer_iv = base64_encode($outer_iv);
340 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
342 $padded_data = pkcs5_pad($msg,16);
343 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
345 $b64_data = base64_encode($inner_encrypted);
348 $b64url_data = base64url_encode($b64_data);
349 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
351 $type = 'application/xml';
352 $encoding = 'base64url';
355 $signable_data = $data . '.' . base64url_encode($type) . '.'
356 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
358 $signature = rsa_sign($signable_data,$prvkey);
359 $sig = base64url_encode($signature);
361 $decrypted_header = <<< EOT
364 <aes_key>$b_inner_aes_key</aes_key>
365 <author_id>$handle</author_id>
369 $decrypted_header = pkcs5_pad($decrypted_header,16);
371 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
373 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
375 $encrypted_outer_key_bundle = '';
376 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
378 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
380 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
382 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
383 'ciphertext' => base64_encode($ciphertext)));
384 $cipher_json = base64_encode($encrypted_header_json_object);
386 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
389 <?xml version='1.0' encoding='UTF-8'?>
390 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
393 <me:encoding>base64url</me:encoding>
394 <me:alg>RSA-SHA256</me:alg>
395 <me:data type="application/xml">$data</me:data>
396 <me:sig>$sig</me:sig>
401 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
408 * diaspora_decode($importer,$xml)
409 * array $importer -> from user table
410 * string $xml -> urldecoded Diaspora salmon
413 * 'message' -> decoded Diaspora XML message
414 * 'author' -> author diaspora handle
415 * 'key' -> author public key (converted to pkcs#8)
417 * Author and key are used elsewhere to save a lookup for verifying replies and likes
421 function diaspora_decode($importer,$xml) {
424 $basedom = parse_xml_string($xml);
426 $children = $basedom->children('https://joindiaspora.com/protocol');
428 if($children->header) {
430 $author_link = str_replace('acct:','',$children->header->author_id);
434 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
436 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
437 $ciphertext = base64_decode($encrypted_header->ciphertext);
439 $outer_key_bundle = '';
440 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
442 $j_outer_key_bundle = json_decode($outer_key_bundle);
444 $outer_iv = base64_decode($j_outer_key_bundle->iv);
445 $outer_key = base64_decode($j_outer_key_bundle->key);
447 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
450 $decrypted = pkcs5_unpad($decrypted);
453 * $decrypted now contains something like
456 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
457 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
462 * <name>Ryan Hughes</name>
463 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
468 * <author_id>galaxor@diaspora.priateship.org</author_id>
472 * </decrypted_header>
475 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
476 $idom = parse_xml_string($decrypted,false);
478 $inner_iv = base64_decode($idom->iv);
479 $inner_aes_key = base64_decode($idom->aes_key);
481 $author_link = str_replace('acct:','',$idom->author_id);
485 $dom = $basedom->children(NAMESPACE_SALMON_ME);
487 // figure out where in the DOM tree our data is hiding
489 if($dom->provenance->data)
490 $base = $dom->provenance;
491 elseif($dom->env->data)
497 logger('mod-diaspora: unable to locate salmon data in xml ');
498 http_status_exit(400);
502 // Stash the signature away for now. We have to find their key or it won't be good for anything.
503 $signature = base64url_decode($base->sig);
507 // strip whitespace so our data element will return to one big base64 blob
508 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
511 // stash away some other stuff for later
513 $type = $base->data[0]->attributes()->type[0];
514 $keyhash = $base->sig[0]->attributes()->keyhash[0];
515 $encoding = $base->encoding;
519 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
523 $data = base64url_decode($data);
527 $inner_decrypted = $data;
531 // Decode the encrypted blob
533 $inner_encrypted = base64_decode($data);
534 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
535 $inner_decrypted = pkcs5_unpad($inner_decrypted);
539 logger('mod-diaspora: Could not retrieve author URI.');
540 http_status_exit(400);
543 // Once we have the author URI, go to the web and try to find their public key
544 // (first this will look it up locally if it is in the fcontact cache)
545 // This will also convert diaspora public key from pkcs#1 to pkcs#8
547 logger('mod-diaspora: Fetching key for ' . $author_link );
548 $key = get_diaspora_key($author_link);
551 logger('mod-diaspora: Could not retrieve author key.');
552 http_status_exit(400);
555 $verify = rsa_verify($signed_data,$signature,$key);
558 logger('mod-diaspora: Message did not verify. Discarding.');
559 http_status_exit(400);
562 logger('mod-diaspora: Message verified.');
564 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
569 function diaspora_request($importer,$xml) {
573 $sender_handle = unxmlify($xml->sender_handle);
574 $recipient_handle = unxmlify($xml->recipient_handle);
576 if(! $sender_handle || ! $recipient_handle)
579 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
583 // perhaps we were already sharing with this person. Now they're sharing with us.
584 // That makes us friends.
586 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
587 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
588 intval(CONTACT_IS_FRIEND),
589 intval($contact['id']),
590 intval($importer['uid'])
595 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
596 intval($importer['uid'])
599 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
600 require_once('include/items.php');
602 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
603 intval($importer['uid'])
606 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
608 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
611 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
612 $arr['uid'] = $importer['uid'];
613 $arr['contact-id'] = $self[0]['id'];
615 $arr['type'] = 'wall';
618 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
619 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
620 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
621 $arr['verb'] = ACTIVITY_FRIEND;
622 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
624 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
625 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
626 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
627 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
629 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
630 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
631 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
632 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
633 $arr['object'] .= '</link></object>' . "\n";
634 $arr['last-child'] = 1;
636 $arr['allow_cid'] = $user[0]['allow_cid'];
637 $arr['allow_gid'] = $user[0]['allow_gid'];
638 $arr['deny_cid'] = $user[0]['deny_cid'];
639 $arr['deny_gid'] = $user[0]['deny_gid'];
641 $i = item_store($arr);
643 proc_run('php',"include/notifier.php","activity","$i");
652 $ret = find_diaspora_person_by_handle($sender_handle);
655 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
656 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
660 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
664 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
665 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
666 intval($importer['uid']),
667 dbesc($ret['network']),
671 dbesc(normalise_link($ret['url'])),
675 dbesc($ret['photo']),
676 dbesc($ret['pubkey']),
677 dbesc($ret['notify']),
683 // find the contact record we just created
685 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
687 if(! $contact_record) {
688 logger('diaspora_request: unable to locate newly created contact record.');
692 $g = q("select def_gid from user where uid = %d limit 1",
693 intval($importer['uid'])
695 if($g && intval($g[0]['def_gid'])) {
696 require_once('include/group.php');
697 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
700 if($importer['page-flags'] == PAGE_NORMAL) {
702 $hash = random_string() . (string) time(); // Generate a confirm_key
704 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
705 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
706 intval($importer['uid']),
707 intval($contact_record['id']),
710 dbesc( t('Sharing notification from Diaspora network')),
712 dbesc(datetime_convert())
717 // automatic friend approval
719 require_once('include/Photo.php');
721 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
723 // technically they are sharing with us (CONTACT_IS_SHARING),
724 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
725 // we are going to change the relationship and make them a follower.
727 if($importer['page-flags'] == PAGE_FREELOVE)
728 $new_relation = CONTACT_IS_FRIEND;
730 $new_relation = CONTACT_IS_FOLLOWER;
732 $r = q("UPDATE `contact` SET
739 `avatar-date` = '%s',
748 intval($new_relation),
749 dbesc(datetime_convert()),
750 dbesc(datetime_convert()),
751 dbesc(datetime_convert()),
752 intval($contact_record['id'])
755 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
757 $ret = diaspora_share($u[0],$contact_record);
763 function diaspora_post_allow($importer,$contact) {
765 // perhaps we were already sharing with this person. Now they're sharing with us.
766 // That makes us friends.
767 // Normally this should have handled by getting a request - but this could get lost
768 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
769 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
770 intval(CONTACT_IS_FRIEND),
771 intval($contact['id']),
772 intval($importer['uid'])
774 $contact['rel'] = CONTACT_IS_FRIEND;
775 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
778 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
780 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
782 if($contact['rel'] == CONTACT_IS_FOLLOWER)
783 if($importer['page-flags'] == PAGE_COMMUNITY)
788 function diaspora_is_redmatrix($url) {
789 return(strstr($url, "/channel/"));
792 function diaspora_plink($addr, $guid) {
793 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", $addr);
797 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
799 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
800 // So we try another way as well.
801 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
803 $r[0]["network"] = $s[0]["network"];
805 if ($r[0]["network"] == NETWORK_DFRN)
806 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
808 if (diaspora_is_redmatrix($r[0]["url"]))
809 return $r[0]["url"]."/?f=&mid=".$guid;
811 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
814 function diaspora_post($importer,$xml,$msg) {
817 $guid = notags(unxmlify($xml->guid));
818 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
820 if($diaspora_handle != $msg['author']) {
821 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
825 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
829 if(! diaspora_post_allow($importer,$contact)) {
830 logger('diaspora_post: Ignoring this author.');
834 $message_id = $diaspora_handle . ':' . $guid;
835 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
836 intval($importer['uid']),
841 logger('diaspora_post: message exists: ' . $guid);
845 $created = unxmlify($xml->created_at);
846 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
848 $body = diaspora2bb($xml->raw_message);
852 $datarray["object"] = json_encode($xml);
854 if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
855 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
857 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
858 // Add OEmbed and other information to the body
859 if (!diaspora_is_redmatrix($contact['url']))
860 $body = add_page_info_to_body($body, false, true);
865 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
867 foreach($matches as $mtch) {
868 if(strlen($str_tags))
870 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
874 $plink = diaspora_plink($diaspora_handle, $guid);
876 $datarray['uid'] = $importer['uid'];
877 $datarray['contact-id'] = $contact['id'];
878 $datarray['wall'] = 0;
879 $datarray['network'] = NETWORK_DIASPORA;
880 $datarray['verb'] = ACTIVITY_POST;
881 $datarray['guid'] = $guid;
882 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
883 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
884 $datarray['private'] = $private;
885 $datarray['parent'] = 0;
886 $datarray['plink'] = $plink;
887 $datarray['owner-name'] = $contact['name'];
888 $datarray['owner-link'] = $contact['url'];
889 //$datarray['owner-avatar'] = $contact['thumb'];
890 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
891 $datarray['author-name'] = $contact['name'];
892 $datarray['author-link'] = $contact['url'];
893 $datarray['author-avatar'] = $contact['thumb'];
894 $datarray['body'] = $body;
895 $datarray['tag'] = $str_tags;
896 if ($xml->provider_display_name)
897 $datarray["app"] = unxmlify($xml->provider_display_name);
899 $datarray['app'] = 'Diaspora';
901 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
903 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
905 DiasporaFetchGuid($datarray);
906 $message_id = item_store($datarray);
912 function DiasporaFetchGuid($item) {
913 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
914 function ($match) use ($item){
915 return(DiasporaFetchGuidSub($match, $item));
919 function DiasporaFetchGuidSub($match, $item) {
922 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
923 diaspora_store_by_guid($match[1], $item["owner-link"]);
926 function diaspora_store_by_guid($guid, $server, $uid = 0) {
927 require_once("include/Contact.php");
929 $serverparts = parse_url($server);
930 $server = $serverparts["scheme"]."://".$serverparts["host"];
932 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
934 $item = diaspora_fetch_message($guid, $server);
939 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
941 $body = $item["body"];
942 $str_tags = $item["tag"];
944 $created = $item["created"];
945 $author = $item["author"];
946 $guid = $item["guid"];
947 $private = $item["private"];
948 $object = $item["object"];
949 $objecttype = $item["object-type"];
951 $message_id = $author.':'.$guid;
952 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
960 $person = find_diaspora_person_by_handle($author);
963 $datarray['uid'] = $uid;
964 $datarray['contact-id'] = get_contact($person['url'], $uid);
965 $datarray['wall'] = 0;
966 $datarray['network'] = NETWORK_DIASPORA;
967 $datarray['guid'] = $guid;
968 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
969 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
970 $datarray['private'] = $private;
971 $datarray['parent'] = 0;
972 $datarray['plink'] = diaspora_plink($author, $guid);
973 $datarray['author-name'] = $person['name'];
974 $datarray['author-link'] = $person['url'];
975 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
976 $datarray['owner-name'] = $datarray['author-name'];
977 $datarray['owner-link'] = $datarray['author-link'];
978 $datarray['owner-avatar'] = $datarray['author-avatar'];
979 $datarray['body'] = $body;
980 $datarray['tag'] = $str_tags;
981 $datarray['app'] = $app;
982 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
983 $datarray['object'] = $object;
984 $datarray['object-type'] = $objecttype;
986 if ($datarray['contact-id'] == 0)
989 DiasporaFetchGuid($datarray);
990 $message_id = item_store($datarray);
993 // Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
998 function diaspora_fetch_message($guid, $server, $level = 0) {
1005 // This will not work if the server is not a Diaspora server
1006 $source_url = $server.'/p/'.$guid.'.xml';
1007 $x = fetch_url($source_url);
1011 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1012 $source_xml = parse_xml_string($x,false);
1015 $item["app"] = 'Diaspora';
1016 $item["guid"] = $guid;
1019 if ($source_xml->post->status_message->created_at)
1020 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1022 if ($source_xml->post->status_message->provider_display_name)
1023 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1025 if ($source_xml->post->status_message->diaspora_handle)
1026 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1028 if ($source_xml->post->status_message->guid)
1029 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1031 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1032 $item["object"] = json_encode($source_xml->post);
1034 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1035 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1036 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1037 $body = scale_external_images($body,false);
1038 } elseif($source_xml->post->asphoto->image_url) {
1039 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1040 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1041 $body = scale_external_images($body);
1042 } elseif($source_xml->post->status_message) {
1043 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1045 // Checking for embedded pictures
1046 if($source_xml->post->status_message->photo->remote_photo_path AND
1047 $source_xml->post->status_message->photo->remote_photo_name) {
1049 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1051 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1052 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1054 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1056 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1058 $item["object-type"] = ACTIVITY_OBJ_NOTE;
1060 $body = scale_external_images($body);
1062 // Add OEmbed and other information to the body
1063 // To-Do: It could be a repeated redmatrix item
1064 // Then we shouldn't add further data to it
1065 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1066 $body = add_page_info_to_body($body, false, true);
1068 } elseif($source_xml->post->reshare) {
1069 // Reshare of a reshare
1070 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1072 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1073 logger('no content found: '.print_r($source_xml,true));
1077 if (trim($body) == "")
1081 $item["body"] = $body;
1086 function diaspora_reshare($importer,$xml,$msg) {
1088 logger('diaspora_reshare: init: ' . print_r($xml,true));
1091 $guid = notags(unxmlify($xml->guid));
1092 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1095 if($diaspora_handle != $msg['author']) {
1096 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1100 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1104 if(! diaspora_post_allow($importer,$contact)) {
1105 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1109 $message_id = $diaspora_handle . ':' . $guid;
1110 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1111 intval($importer['uid']),
1116 logger('diaspora_reshare: message exists: ' . $guid);
1120 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1121 $orig_guid = notags(unxmlify($xml->root_guid));
1122 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1124 $create_original_post = false;
1126 // Do we already have this item?
1127 $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",
1129 dbesc(NETWORK_DIASPORA)
1132 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1134 // Maybe it is already a reshared item?
1135 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1136 require_once('include/api.php');
1137 if (api_share_as_retweet($r[0]))
1140 $body = $r[0]["body"];
1141 $str_tags = $r[0]["tag"];
1142 $app = $r[0]["app"];
1143 $orig_created = $r[0]["created"];
1144 $orig_plink = $r[0]["plink"];
1145 $orig_uri = $r[0]["uri"];
1146 $object = $r[0]["object"];
1147 $objecttype = $r[0]["object-type"];
1156 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1157 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1158 $item = diaspora_fetch_message($orig_guid, $server);
1161 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1162 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1163 $item = diaspora_fetch_message($orig_guid, $server);
1166 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1167 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1168 $item = diaspora_fetch_message($orig_guid, $server);
1171 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1172 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1173 $item = diaspora_fetch_message($orig_guid, $server);
1177 $body = $item["body"];
1178 $str_tags = $item["tag"];
1179 $app = $item["app"];
1180 $orig_created = $item["created"];
1181 $orig_author = $item["author"];
1182 $orig_guid = $item["guid"];
1183 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1184 $orig_uri = $orig_author.':'.$orig_guid;
1185 $create_original_post = ($body != "");
1186 $object = $item["object"];
1187 $objecttype = $item["object-type"];
1191 $plink = diaspora_plink($diaspora_handle, $guid);
1193 $person = find_diaspora_person_by_handle($orig_author);
1195 $created = unxmlify($xml->created_at);
1196 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1198 $datarray = array();
1200 $datarray['uid'] = $importer['uid'];
1201 $datarray['contact-id'] = $contact['id'];
1202 $datarray['wall'] = 0;
1203 $datarray['network'] = NETWORK_DIASPORA;
1204 $datarray['guid'] = $guid;
1205 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1206 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1207 $datarray['private'] = $private;
1208 $datarray['parent'] = 0;
1209 $datarray['plink'] = $plink;
1210 $datarray['owner-name'] = $contact['name'];
1211 $datarray['owner-link'] = $contact['url'];
1212 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1213 if (!intval(get_config('system','wall-to-wall_share'))) {
1214 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1216 $datarray['author-name'] = $contact['name'];
1217 $datarray['author-link'] = $contact['url'];
1218 $datarray['author-avatar'] = $contact['thumb'];
1219 $datarray['body'] = $prefix.$body."[/share]";
1221 // Let reshared messages look like wall-to-wall posts
1222 $datarray['author-name'] = $person['name'];
1223 $datarray['author-link'] = $person['url'];
1224 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1225 $datarray['body'] = $body;
1228 $datarray["object"] = json_encode($xml);
1229 $datarray['object-type'] = $objecttype;
1231 $datarray['tag'] = $str_tags;
1232 $datarray['app'] = $app;
1234 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1235 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1237 // Store the original item of a reshare
1238 if ($create_original_post) {
1239 require_once("include/Contact.php");
1241 $datarray2 = $datarray;
1243 $datarray2['uid'] = 0;
1244 $datarray2['contact-id'] = get_contact($person['url'], 0);
1245 $datarray2['guid'] = $orig_guid;
1246 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1247 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1248 $datarray2['parent'] = 0;
1249 $datarray2['plink'] = $orig_plink;
1251 $datarray2['author-name'] = $person['name'];
1252 $datarray2['author-link'] = $person['url'];
1253 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1254 $datarray2['owner-name'] = $datarray2['author-name'];
1255 $datarray2['owner-link'] = $datarray2['author-link'];
1256 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1257 $datarray2['body'] = $body;
1258 $datarray2["object"] = $object;
1260 DiasporaFetchGuid($datarray2);
1261 $message_id = item_store($datarray2);
1263 logger("Store original item ".$orig_guid." under message id ".$message_id);
1266 DiasporaFetchGuid($datarray);
1267 $message_id = item_store($datarray);
1274 function diaspora_asphoto($importer,$xml,$msg) {
1275 logger('diaspora_asphoto called');
1278 $guid = notags(unxmlify($xml->guid));
1279 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1281 if($diaspora_handle != $msg['author']) {
1282 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1286 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1290 if(! diaspora_post_allow($importer,$contact)) {
1291 logger('diaspora_asphoto: Ignoring this author.');
1295 $message_id = $diaspora_handle . ':' . $guid;
1296 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1297 intval($importer['uid']),
1302 logger('diaspora_asphoto: message exists: ' . $guid);
1306 $created = unxmlify($xml->created_at);
1307 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1309 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1310 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1311 $body = scale_external_images($body,false);
1313 elseif($xml->image_url) {
1314 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1315 $body = scale_external_images($body);
1318 logger('diaspora_asphoto: no photo url found.');
1322 $plink = diaspora_plink($diaspora_handle, $guid);
1324 $datarray = array();
1326 $datarray['uid'] = $importer['uid'];
1327 $datarray['contact-id'] = $contact['id'];
1328 $datarray['wall'] = 0;
1329 $datarray['network'] = NETWORK_DIASPORA;
1330 $datarray['guid'] = $guid;
1331 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1332 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1333 $datarray['private'] = $private;
1334 $datarray['parent'] = 0;
1335 $datarray['plink'] = $plink;
1336 $datarray['owner-name'] = $contact['name'];
1337 $datarray['owner-link'] = $contact['url'];
1338 //$datarray['owner-avatar'] = $contact['thumb'];
1339 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1340 $datarray['author-name'] = $contact['name'];
1341 $datarray['author-link'] = $contact['url'];
1342 $datarray['author-avatar'] = $contact['thumb'];
1343 $datarray['body'] = $body;
1344 $datarray["object"] = json_encode($xml);
1345 $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1347 $datarray['app'] = 'Diaspora/Cubbi.es';
1349 DiasporaFetchGuid($datarray);
1350 $message_id = item_store($datarray);
1353 // q("update item set plink = '%s' where id = %d",
1354 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1355 // intval($message_id)
1368 function diaspora_comment($importer,$xml,$msg) {
1371 $guid = notags(unxmlify($xml->guid));
1372 $parent_guid = notags(unxmlify($xml->parent_guid));
1373 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1374 $target_type = notags(unxmlify($xml->target_type));
1375 $text = unxmlify($xml->text);
1376 $author_signature = notags(unxmlify($xml->author_signature));
1378 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1380 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1382 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1386 if(! diaspora_post_allow($importer,$contact)) {
1387 logger('diaspora_comment: Ignoring this author.');
1391 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1392 intval($importer['uid']),
1396 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1400 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1401 intval($importer['uid']),
1406 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1409 $person = find_diaspora_person_by_handle($diaspora_handle);
1410 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1414 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1416 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1417 intval($importer['uid']),
1424 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1427 $parent_item = $r[0];
1430 /* How Diaspora performs comment signature checking:
1432 - If an item has been sent by the comment author to the top-level post owner to relay on
1433 to the rest of the contacts on the top-level post, the top-level post owner should check
1434 the author_signature, then create a parent_author_signature before relaying the comment on
1435 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1436 check only the parent_author_signature. Basically, they trust that the top-level post
1437 owner has already verified the authenticity of anything he/she sends out
1438 - In either case, the signature that get checked is the signature created by the person
1442 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1445 if($parent_author_signature) {
1446 // If a parent_author_signature exists, then we've received the comment
1447 // relayed from the top-level post owner. There's no need to check the
1448 // author_signature if the parent_author_signature is valid
1450 $parent_author_signature = base64_decode($parent_author_signature);
1452 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1453 logger('diaspora_comment: top-level owner verification failed.');
1458 // If there's no parent_author_signature, then we've received the comment
1459 // from the comment creator. In that case, the person is commenting on
1460 // our post, so he/she must be a contact of ours and his/her public key
1461 // should be in $msg['key']
1463 $author_signature = base64_decode($author_signature);
1465 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1466 logger('diaspora_comment: comment author verification failed.');
1471 // Phew! Everything checks out. Now create an item.
1473 // Find the original comment author information.
1474 // We need this to make sure we display the comment author
1475 // information (name and avatar) correctly.
1476 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1479 $person = find_diaspora_person_by_handle($diaspora_handle);
1481 if(! is_array($person)) {
1482 logger('diaspora_comment: unable to find author details');
1487 $body = diaspora2bb($text);
1488 $message_id = $diaspora_handle . ':' . $guid;
1490 $datarray = array();
1492 $datarray['uid'] = $importer['uid'];
1493 $datarray['contact-id'] = $contact['id'];
1494 $datarray['type'] = 'remote-comment';
1495 $datarray['wall'] = $parent_item['wall'];
1496 $datarray['network'] = NETWORK_DIASPORA;
1497 $datarray['verb'] = ACTIVITY_POST;
1498 $datarray['gravity'] = GRAVITY_COMMENT;
1499 $datarray['guid'] = $guid;
1500 $datarray['uri'] = $message_id;
1501 $datarray['parent-uri'] = $parent_item['uri'];
1503 // No timestamps for comments? OK, we'll the use current time.
1504 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1505 $datarray['private'] = $parent_item['private'];
1507 $datarray['owner-name'] = $parent_item['owner-name'];
1508 $datarray['owner-link'] = $parent_item['owner-link'];
1509 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1511 $datarray['author-name'] = $person['name'];
1512 $datarray['author-link'] = $person['url'];
1513 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1514 $datarray['body'] = $body;
1515 $datarray["object"] = json_encode($xml);
1516 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1518 // We can't be certain what the original app is if the message is relayed.
1519 if(($parent_item['origin']) && (! $parent_author_signature))
1520 $datarray['app'] = 'Diaspora';
1522 DiasporaFetchGuid($datarray);
1523 $message_id = item_store($datarray);
1525 $datarray['id'] = $message_id;
1528 //q("update item set plink = '%s' where id = %d",
1529 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1530 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1531 // intval($message_id)
1535 if(($parent_item['origin']) && (! $parent_author_signature)) {
1536 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1537 intval($message_id),
1538 dbesc($signed_data),
1539 dbesc(base64_encode($author_signature)),
1540 dbesc($diaspora_handle)
1543 // if the message isn't already being relayed, notify others
1544 // the existence of parent_author_signature means the parent_author or owner
1545 // is already relaying.
1547 proc_run('php','include/notifier.php','comment-import',$message_id);
1550 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1551 dbesc($parent_item['uri']),
1552 intval($importer['uid'])
1555 if(count($myconv)) {
1556 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1558 foreach($myconv as $conv) {
1560 // now if we find a match, it means we're in this conversation
1562 if(! link_compare($conv['author-link'],$importer_url))
1565 require_once('include/enotify.php');
1567 $conv_parent = $conv['parent'];
1570 'type' => NOTIFY_COMMENT,
1571 'notify_flags' => $importer['notify-flags'],
1572 'language' => $importer['language'],
1573 'to_name' => $importer['username'],
1574 'to_email' => $importer['email'],
1575 'uid' => $importer['uid'],
1576 'item' => $datarray,
1577 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1578 'source_name' => $datarray['author-name'],
1579 'source_link' => $datarray['author-link'],
1580 'source_photo' => $datarray['author-avatar'],
1581 'verb' => ACTIVITY_POST,
1583 'parent' => $conv_parent,
1584 'parent_uri' => $parent_uri
1587 // only send one notification
1597 function diaspora_conversation($importer,$xml,$msg) {
1601 $guid = notags(unxmlify($xml->guid));
1602 $subject = notags(unxmlify($xml->subject));
1603 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1604 $participant_handles = notags(unxmlify($xml->participant_handles));
1605 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1607 $parent_uri = $diaspora_handle . ':' . $guid;
1609 $messages = $xml->message;
1611 if(! count($messages)) {
1612 logger('diaspora_conversation: empty conversation');
1616 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1618 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1622 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1623 logger('diaspora_conversation: Ignoring this author.');
1627 $conversation = null;
1629 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1630 intval($importer['uid']),
1634 $conversation = $c[0];
1636 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1637 intval($importer['uid']),
1639 dbesc($diaspora_handle),
1640 dbesc(datetime_convert('UTC','UTC',$created_at)),
1641 dbesc(datetime_convert()),
1643 dbesc($participant_handles)
1646 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1647 intval($importer['uid']),
1651 $conversation = $c[0];
1653 if(! $conversation) {
1654 logger('diaspora_conversation: unable to create conversation.');
1658 foreach($messages as $mesg) {
1662 $msg_guid = notags(unxmlify($mesg->guid));
1663 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1664 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1665 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1666 $msg_text = unxmlify($mesg->text);
1667 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1668 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1669 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1670 if($msg_conversation_guid != $guid) {
1671 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1675 $body = diaspora2bb($msg_text);
1676 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1678 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1680 $author_signature = base64_decode($msg_author_signature);
1682 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1687 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1689 if(is_array($person) && x($person,'pubkey'))
1690 $key = $person['pubkey'];
1692 logger('diaspora_conversation: unable to find author details');
1697 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1698 logger('diaspora_conversation: verification failed.');
1702 if($msg_parent_author_signature) {
1703 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1705 $parent_author_signature = base64_decode($msg_parent_author_signature);
1709 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1710 logger('diaspora_conversation: owner verification failed.');
1715 $r = q("select id from mail where `uri` = '%s' limit 1",
1719 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1723 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')",
1724 intval($importer['uid']),
1726 intval($conversation['id']),
1727 dbesc($person['name']),
1728 dbesc($person['photo']),
1729 dbesc($person['url']),
1730 intval($contact['id']),
1737 dbesc($msg_created_at)
1740 q("update conv set updated = '%s' where id = %d",
1741 dbesc(datetime_convert()),
1742 intval($conversation['id'])
1745 require_once('include/enotify.php');
1747 'type' => NOTIFY_MAIL,
1748 'notify_flags' => $importer['notify-flags'],
1749 'language' => $importer['language'],
1750 'to_name' => $importer['username'],
1751 'to_email' => $importer['email'],
1752 'uid' =>$importer['uid'],
1753 'item' => array('subject' => $subject, 'body' => $body),
1754 'source_name' => $person['name'],
1755 'source_link' => $person['url'],
1756 'source_photo' => $person['thumb'],
1757 'verb' => ACTIVITY_POST,
1765 function diaspora_message($importer,$xml,$msg) {
1769 $msg_guid = notags(unxmlify($xml->guid));
1770 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1771 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1772 $msg_author_signature = notags(unxmlify($xml->author_signature));
1773 $msg_text = unxmlify($xml->text);
1774 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1775 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1776 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1778 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1780 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1782 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1786 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1787 logger('diaspora_message: Ignoring this author.');
1791 $conversation = null;
1793 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1794 intval($importer['uid']),
1795 dbesc($msg_conversation_guid)
1798 $conversation = $c[0];
1800 logger('diaspora_message: conversation not available.');
1806 $body = diaspora2bb($msg_text);
1807 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1809 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1812 $author_signature = base64_decode($msg_author_signature);
1814 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1815 if(is_array($person) && x($person,'pubkey'))
1816 $key = $person['pubkey'];
1818 logger('diaspora_message: unable to find author details');
1822 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1823 logger('diaspora_message: verification failed.');
1827 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1829 intval($importer['uid'])
1832 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1836 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')",
1837 intval($importer['uid']),
1839 intval($conversation['id']),
1840 dbesc($person['name']),
1841 dbesc($person['photo']),
1842 dbesc($person['url']),
1843 intval($contact['id']),
1844 dbesc($conversation['subject']),
1850 dbesc($msg_created_at)
1853 q("update conv set updated = '%s' where id = %d",
1854 dbesc(datetime_convert()),
1855 intval($conversation['id'])
1862 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1866 logger('diaspora_photo: init',LOGGER_DEBUG);
1868 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1870 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1872 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1874 $guid = notags(unxmlify($xml->guid));
1876 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1878 $public = notags(unxmlify($xml->public));
1880 $created_at = notags(unxmlify($xml_created_at));
1882 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1884 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1886 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1890 if(! diaspora_post_allow($importer,$contact)) {
1891 logger('diaspora_photo: Ignoring this author.');
1895 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1896 intval($importer['uid']),
1897 dbesc($status_message_guid)
1900 /* deactivated by now since it can lead to multiplicated pictures in posts.
1902 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1905 $person = find_diaspora_person_by_handle($diaspora_handle);
1906 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1910 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1912 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1913 intval($importer['uid']),
1914 dbesc($status_message_guid)
1921 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1922 intval($importer['uid']),
1923 dbesc(serialize($msg)),
1924 intval($attempt + 1)
1928 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1932 $parent_item = $r[0];
1934 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1936 $link_text = scale_external_images($link_text, true,
1937 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1939 if(strpos($parent_item['body'],$link_text) === false) {
1940 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1941 dbesc($link_text . $parent_item['body']),
1942 intval($parent_item['id']),
1943 intval($parent_item['uid'])
1945 update_thread($parent_item['id']);
1954 function diaspora_like($importer,$xml,$msg) {
1957 $guid = notags(unxmlify($xml->guid));
1958 $parent_guid = notags(unxmlify($xml->parent_guid));
1959 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1960 $target_type = notags(unxmlify($xml->target_type));
1961 $positive = notags(unxmlify($xml->positive));
1962 $author_signature = notags(unxmlify($xml->author_signature));
1964 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1966 // likes on comments not supported here and likes on photos not supported by Diaspora
1968 // if($target_type !== 'Post')
1971 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1973 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1977 if(! diaspora_post_allow($importer,$contact)) {
1978 logger('diaspora_like: Ignoring this author.');
1982 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1983 intval($importer['uid']),
1988 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1991 $person = find_diaspora_person_by_handle($diaspora_handle);
1992 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1996 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1998 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1999 intval($importer['uid']),
2006 logger('diaspora_like: parent item not found: ' . $guid);
2010 $parent_item = $r[0];
2012 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2013 intval($importer['uid']),
2017 if($positive === 'true') {
2018 logger('diaspora_like: duplicate like: ' . $guid);
2021 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2022 // It looks like "RelayableRetractions" are used for "unlike" instead
2023 if($positive === 'false') {
2024 logger('diaspora_like: received a like with positive set to "false"...ignoring');
2025 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2026 intval($r[0]['id']),
2027 intval($importer['uid'])
2029 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2030 // send notification via proc_run()
2034 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2035 // It looks like "RelayableRetractions" are used for "unlike" instead
2036 if($positive === 'false') {
2037 logger('diaspora_like: received a like with positive set to "false"');
2038 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2043 /* How Diaspora performs "like" signature checking:
2045 - If an item has been sent by the like author to the top-level post owner to relay on
2046 to the rest of the contacts on the top-level post, the top-level post owner should check
2047 the author_signature, then create a parent_author_signature before relaying the like on
2048 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2049 check only the parent_author_signature. Basically, they trust that the top-level post
2050 owner has already verified the authenticity of anything he/she sends out
2051 - In either case, the signature that get checked is the signature created by the person
2055 // Diaspora has changed the way they are signing the likes.
2056 // Just to make sure that we don't miss any likes we will check the old and the current way.
2057 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2059 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2063 if ($parent_author_signature) {
2064 // If a parent_author_signature exists, then we've received the like
2065 // relayed from the top-level post owner. There's no need to check the
2066 // author_signature if the parent_author_signature is valid
2068 $parent_author_signature = base64_decode($parent_author_signature);
2070 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2071 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2073 logger('diaspora_like: top-level owner verification failed.');
2077 // If there's no parent_author_signature, then we've received the like
2078 // from the like creator. In that case, the person is "like"ing
2079 // our post, so he/she must be a contact of ours and his/her public key
2080 // should be in $msg['key']
2082 $author_signature = base64_decode($author_signature);
2084 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2085 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2087 logger('diaspora_like: like creator verification failed.');
2092 // Phew! Everything checks out. Now create an item.
2094 // Find the original comment author information.
2095 // We need this to make sure we display the comment author
2096 // information (name and avatar) correctly.
2097 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2100 $person = find_diaspora_person_by_handle($diaspora_handle);
2102 if(! is_array($person)) {
2103 logger('diaspora_like: unable to find author details');
2108 $uri = $diaspora_handle . ':' . $guid;
2110 $activity = ACTIVITY_LIKE;
2111 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2112 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2113 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2114 $body = $parent_item['body'];
2119 <type>$objtype</type>
2121 <id>{$parent_item['uri']}</id>
2124 <content>$body</content>
2127 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2132 $arr['uid'] = $importer['uid'];
2133 $arr['guid'] = $guid;
2134 $arr['network'] = NETWORK_DIASPORA;
2135 $arr['contact-id'] = $contact['id'];
2136 $arr['type'] = 'activity';
2137 $arr['wall'] = $parent_item['wall'];
2138 $arr['gravity'] = GRAVITY_LIKE;
2139 $arr['parent'] = $parent_item['id'];
2140 $arr['parent-uri'] = $parent_item['uri'];
2142 $arr['owner-name'] = $parent_item['name'];
2143 $arr['owner-link'] = $parent_item['url'];
2144 //$arr['owner-avatar'] = $parent_item['thumb'];
2145 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2147 $arr['author-name'] = $person['name'];
2148 $arr['author-link'] = $person['url'];
2149 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2151 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2152 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2153 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2154 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2155 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2157 $arr['app'] = 'Diaspora';
2159 $arr['private'] = $parent_item['private'];
2160 $arr['verb'] = $activity;
2161 $arr['object-type'] = $objtype;
2162 $arr['object'] = $obj;
2163 $arr['visible'] = 1;
2165 $arr['last-child'] = 0;
2167 $message_id = item_store($arr);
2171 // q("update item set plink = '%s' where id = %d",
2172 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2173 // dbesc($a->get_baseurl().'/display/'.$guid),
2174 // intval($message_id)
2178 if(! $parent_author_signature) {
2179 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2180 intval($message_id),
2181 dbesc($signed_data),
2182 dbesc(base64_encode($author_signature)),
2183 dbesc($diaspora_handle)
2187 // if the message isn't already being relayed, notify others
2188 // the existence of parent_author_signature means the parent_author or owner
2189 // is already relaying. The parent_item['origin'] indicates the message was created on our system
2191 if(($parent_item['origin']) && (! $parent_author_signature))
2192 proc_run('php','include/notifier.php','comment-import',$message_id);
2197 function diaspora_retraction($importer,$xml) {
2200 $guid = notags(unxmlify($xml->guid));
2201 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2202 $type = notags(unxmlify($xml->type));
2204 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2208 if($type === 'Person') {
2209 require_once('include/Contact.php');
2210 contact_remove($contact['id']);
2212 elseif($type === 'Post') {
2213 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2215 intval($importer['uid'])
2218 if(link_compare($r[0]['author-link'],$contact['url'])) {
2219 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2220 dbesc(datetime_convert()),
2223 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2232 function diaspora_signed_retraction($importer,$xml,$msg) {
2235 $guid = notags(unxmlify($xml->target_guid));
2236 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2237 $type = notags(unxmlify($xml->target_type));
2238 $sig = notags(unxmlify($xml->target_author_signature));
2240 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2242 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2244 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2249 $signed_data = $guid . ';' . $type ;
2252 /* How Diaspora performs relayable_retraction signature checking:
2254 - If an item has been sent by the item author to the top-level post owner to relay on
2255 to the rest of the contacts on the top-level post, the top-level post owner checks
2256 the author_signature, then creates a parent_author_signature before relaying the item on
2257 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2258 check only the parent_author_signature. Basically, they trust that the top-level post
2259 owner has already verified the authenticity of anything he/she sends out
2260 - In either case, the signature that get checked is the signature created by the person
2264 if($parent_author_signature) {
2266 $parent_author_signature = base64_decode($parent_author_signature);
2268 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2269 logger('diaspora_signed_retraction: top-level post owner verification failed');
2276 $sig_decode = base64_decode($sig);
2278 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2279 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2284 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2285 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2287 intval($importer['uid'])
2290 if(link_compare($r[0]['author-link'],$contact['url'])) {
2291 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2292 dbesc(datetime_convert()),
2293 dbesc(datetime_convert()),
2296 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2298 // Now check if the retraction needs to be relayed by us
2300 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2301 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2302 // The only item with `parent` and `id` as the parent id is the parent item.
2303 $p = q("select origin from item where parent = %d and id = %d limit 1",
2308 if(($p[0]['origin']) && (! $parent_author_signature)) {
2309 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2311 dbesc($signed_data),
2313 dbesc($diaspora_handle)
2316 // the existence of parent_author_signature would have meant the parent_author or owner
2317 // is already relaying.
2318 logger('diaspora_signed_retraction: relaying relayable_retraction');
2320 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2327 logger('diaspora_signed_retraction: unknown type: ' . $type);
2333 function diaspora_profile($importer,$xml,$msg) {
2336 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2339 if($diaspora_handle != $msg['author']) {
2340 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2344 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2348 if($contact['blocked']) {
2349 logger('diaspora_post: Ignoring this author.');
2353 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2354 $image_url = unxmlify($xml->image_url);
2355 $birthday = unxmlify($xml->birthday);
2356 $location = diaspora2bb(unxmlify($xml->location));
2357 $about = diaspora2bb(unxmlify($xml->bio));
2358 $gender = unxmlify($xml->gender);
2359 $tags = unxmlify($xml->tag_string);
2361 $tags = explode("#", $tags);
2363 $keywords = array();
2364 foreach ($tags as $tag) {
2365 $tag = trim(strtolower($tag));
2370 $keywords = implode(", ", $keywords);
2372 $handle_parts = explode("@", $diaspora_handle);
2374 $name = $handle_parts[0];
2377 if( preg_match("|^https?://|", $image_url) === 0) {
2378 $image_url = "http://" . $handle_parts[1] . $image_url;
2381 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2382 intval($importer['uid']),
2383 intval($contact['id'])
2385 $oldphotos = ((count($r)) ? $r : null);*/
2387 require_once('include/Photo.php');
2389 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2391 // Generic birthday. We don't know the timezone. The year is irrelevant.
2393 $birthday = str_replace('1000','1901',$birthday);
2395 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2397 // this is to prevent multiple birthday notifications in a single year
2398 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2400 if(substr($birthday,5) === substr($contact['bd'],5))
2401 $birthday = $contact['bd'];
2403 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2404 // Not doing this currently because D* protocol is scheduled for revision soon.
2406 $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",
2408 dbesc(datetime_convert()),
2412 dbesc(datetime_convert()),
2418 intval($contact['id']),
2419 intval($importer['uid'])
2422 if (unxmlify($xml->searchable) == "true") {
2423 require_once('include/socgraph.php');
2424 poco_check($contact['url'], $name, NETWORK_DIASPORA, $images[0], $about, $location, $gender, $keywords, "",
2425 datetime_convert(), 2, $contact['id'], $importer['uid']);
2429 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
2430 dbesc(normalise_link($contact['url'])));
2432 if (count($author) == 0) {
2433 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`, `location`, `about`) VALUES ('%s', '%s', '%s', '%s', '%s')",
2434 dbesc(normalise_link($contact['url'])), dbesc($name), dbesc($location), dbesc($about), dbesc($images[0]));
2436 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
2437 dbesc(normalise_link($contact['url'])));
2438 } else if (normalise_link($contact['url']).$name.$location.$about != normalise_link($author[0]["url"]).$author[0]["name"].$author[0]["location"].$author[0]["about"]) {
2439 q("UPDATE unique_contacts SET name = '%s', avatar = '%s', `location` = '%s', `about` = '%s' WHERE url = '%s'",
2440 dbesc($name), dbesc($images[0]), dbesc($location), dbesc($about), dbesc(normalise_link($contact['url'])));
2445 foreach($oldphotos as $ph) {
2446 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2447 intval($importer['uid']),
2448 intval($contact['id']),
2449 dbesc($ph['resource-id'])
2459 function diaspora_share($me,$contact) {
2461 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2462 $theiraddr = $contact['addr'];
2464 $tpl = get_markup_template('diaspora_share.tpl');
2465 $msg = replace_macros($tpl, array(
2466 '$sender' => $myaddr,
2467 '$recipient' => $theiraddr
2470 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2471 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2473 return(diaspora_transmit($owner,$contact,$slap, false));
2476 function diaspora_unshare($me,$contact) {
2479 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2481 $tpl = get_markup_template('diaspora_retract.tpl');
2482 $msg = replace_macros($tpl, array(
2483 '$guid' => $me['guid'],
2484 '$type' => 'Person',
2485 '$handle' => $myaddr
2488 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2489 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2491 return(diaspora_transmit($owner,$contact,$slap, false));
2496 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2499 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2500 $theiraddr = $contact['addr'];
2504 $title = $item['title'];
2505 $body = $item['body'];
2508 // We're trying to match Diaspora's split message/photo protocol but
2509 // all the photos are displayed on D* as links and not img's - even
2510 // though we're sending pretty much precisely what they send us when
2511 // doing the same operation.
2512 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2513 // which seems to get through intact.
2515 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2517 foreach($matches as $mtch) {
2519 $detail['str'] = $mtch[0];
2520 $detail['path'] = dirname($mtch[1]) . '/';
2521 $detail['file'] = basename($mtch[1]);
2522 $detail['guid'] = $item['guid'];
2523 $detail['handle'] = $myaddr;
2524 $images[] = $detail;
2525 $body = str_replace($detail['str'],$mtch[1],$body);
2530 //if(strlen($title))
2531 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2533 // convert to markdown
2534 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2535 //$body = bb2diaspora($body);
2539 $body = "## ".html_entity_decode($title)."\n\n".$body;
2541 if($item['attach']) {
2542 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2544 $body .= "\n" . t('Attachments:') . "\n";
2545 foreach($matches as $mtch) {
2546 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2552 $public = (($item['private']) ? 'false' : 'true');
2554 require_once('include/datetime.php');
2555 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2557 // Detect a share element and do a reshare
2558 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2559 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2560 $tpl = get_markup_template('diaspora_reshare.tpl');
2561 $msg = replace_macros($tpl, array(
2562 '$root_handle' => xmlify($ret['root_handle']),
2563 '$root_guid' => $ret['root_guid'],
2564 '$guid' => $item['guid'],
2565 '$handle' => xmlify($myaddr),
2566 '$public' => $public,
2567 '$created' => $created,
2568 '$provider' => $item["app"]
2571 $tpl = get_markup_template('diaspora_post.tpl');
2572 $msg = replace_macros($tpl, array(
2574 '$guid' => $item['guid'],
2575 '$handle' => xmlify($myaddr),
2576 '$public' => $public,
2577 '$created' => $created,
2578 '$provider' => $item["app"]
2582 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2584 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2585 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2587 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2589 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2591 if(count($images)) {
2592 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2595 return $return_code;
2598 function diaspora_is_reshare($body) {
2599 $body = trim($body);
2601 // Skip if it isn't a pure repeated messages
2602 // Does it start with a share?
2603 if (strpos($body, "[share") > 0)
2606 // Does it end with a share?
2607 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2610 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2611 // Skip if there is no shared message in there
2612 if ($body == $attributes)
2616 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2617 if ($matches[1] != "")
2618 $guid = $matches[1];
2620 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2621 if ($matches[1] != "")
2622 $guid = $matches[1];
2625 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2626 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2629 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2630 $ret["root_guid"] = $guid;
2636 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2637 if ($matches[1] != "")
2638 $profile = $matches[1];
2640 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2641 if ($matches[1] != "")
2642 $profile = $matches[1];
2646 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2647 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2651 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2652 if ($matches[1] != "")
2653 $link = $matches[1];
2655 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2656 if ($matches[1] != "")
2657 $link = $matches[1];
2659 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2660 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2666 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2668 if(! count($images))
2670 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2672 $tpl = get_markup_template('diaspora_photo.tpl');
2673 foreach($images as $image) {
2674 if(! stristr($image['path'],$mysite))
2676 $resource = str_replace('.jpg','',$image['file']);
2677 $resource = substr($resource,0,strpos($resource,'-'));
2679 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2681 intval($owner['uid'])
2685 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2686 $msg = replace_macros($tpl,array(
2687 '$path' => xmlify($image['path']),
2688 '$filename' => xmlify($image['file']),
2689 '$msg_guid' => xmlify($image['guid']),
2690 '$guid' => xmlify($r[0]['guid']),
2691 '$handle' => xmlify($image['handle']),
2692 '$public' => xmlify($public),
2693 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2697 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2698 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2699 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2701 diaspora_transmit($owner,$contact,$slap,$public_batch);
2706 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2709 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2710 // $theiraddr = $contact['addr'];
2712 // Diaspora doesn't support threaded comments, but some
2713 // versions of Diaspora (i.e. Diaspora-pistos) support
2714 // likes on comments
2715 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2716 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2717 dbesc($item['thr-parent'])
2721 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2722 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2723 // The only item with `parent` and `id` as the parent id is the parent item.
2724 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2725 intval($item['parent']),
2726 intval($item['parent'])
2734 if($item['verb'] === ACTIVITY_LIKE) {
2735 $tpl = get_markup_template('diaspora_like.tpl');
2737 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2738 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2739 // $positive = (($item['deleted']) ? 'false' : 'true');
2742 if(($item['deleted']))
2743 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2746 $tpl = get_markup_template('diaspora_comment.tpl');
2750 $text = html_entity_decode(bb2diaspora($item['body']));
2755 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2757 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2759 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2761 $msg = replace_macros($tpl,array(
2762 '$guid' => xmlify($item['guid']),
2763 '$parent_guid' => xmlify($parent['guid']),
2764 '$target_type' =>xmlify($target_type),
2765 '$authorsig' => xmlify($authorsig),
2766 '$body' => xmlify($text),
2767 '$positive' => xmlify($positive),
2768 '$handle' => xmlify($myaddr)
2771 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2773 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2774 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2776 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2780 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2784 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2785 // $theiraddr = $contact['addr'];
2787 $body = $item['body'];
2788 $text = html_entity_decode(bb2diaspora($body));
2790 // Diaspora doesn't support threaded comments, but some
2791 // versions of Diaspora (i.e. Diaspora-pistos) support
2792 // likes on comments
2793 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2794 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2795 dbesc($item['thr-parent'])
2799 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2800 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2801 // The only item with `parent` and `id` as the parent id is the parent item.
2802 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2803 intval($item['parent']),
2804 intval($item['parent'])
2813 $relay_retract = false;
2814 $sql_sign_id = 'iid';
2815 if( $item['deleted']) {
2816 $relay_retract = true;
2818 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2820 $sql_sign_id = 'retract_iid';
2821 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2823 elseif($item['verb'] === ACTIVITY_LIKE) {
2826 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2827 // $positive = (($item['deleted']) ? 'false' : 'true');
2830 $tpl = get_markup_template('diaspora_like_relay.tpl');
2832 else { // item is a comment
2833 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2837 // fetch the original signature if the relayable was created by a Diaspora
2838 // or DFRN user. Relayables for other networks are not supported.
2840 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2845 $signed_text = $orig_sign['signed_text'];
2846 $authorsig = $orig_sign['signature'];
2847 $handle = $orig_sign['signer'];
2851 // Author signature information (for likes, comments, and retractions of likes or comments,
2852 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2853 // function is called
2854 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2858 /* Since the author signature is only checked by the parent, not by the relay recipients,
2859 * I think it may not be necessary for us to do so much work to preserve all the original
2860 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2861 * Let's just generate that and forget about all the original author signature stuff.
2863 * Note: this might be more of an problem if we want to support likes on comments for older
2864 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2865 * doing that, let's ignore it for now.
2867 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2871 $handle = diaspora_handle_from_contact($item['contact-id']);
2877 $sender_signed_text = $item['guid'] . ';' . $target_type;
2879 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2881 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2883 // Sign the relayable with the top-level owner's signature
2885 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2886 // stored in the database, because that provides the best chance that Diaspora will
2887 // be able to reconstruct the signed text the same way we did. This is particularly a
2888 // concern for the comment, whose signed text includes the text of the comment. The
2889 // smallest change in the text of the comment, including removing whitespace, will
2890 // make the signature verification fail. Since we translate from BB code to Diaspora's
2891 // markup at the top of this function, which is AFTER we placed the original $signed_text
2892 // in the database, it's hazardous to trust the original $signed_text.
2894 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2896 $msg = replace_macros($tpl,array(
2897 '$guid' => xmlify($item['guid']),
2898 '$parent_guid' => xmlify($parent['guid']),
2899 '$target_type' =>xmlify($target_type),
2900 '$authorsig' => xmlify($authorsig),
2901 '$parentsig' => xmlify($parentauthorsig),
2902 '$body' => xmlify($text),
2903 '$positive' => xmlify($positive),
2904 '$handle' => xmlify($handle)
2907 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2910 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2911 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2913 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2919 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2922 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2924 // Check whether the retraction is for a top-level post or whether it's a relayable
2925 if( $item['uri'] !== $item['parent-uri'] ) {
2927 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2928 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2932 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2933 $target_type = 'StatusMessage';
2936 $signed_text = $item['guid'] . ';' . $target_type;
2938 $msg = replace_macros($tpl, array(
2939 '$guid' => xmlify($item['guid']),
2940 '$type' => xmlify($target_type),
2941 '$handle' => xmlify($myaddr),
2942 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2945 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2946 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2948 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2951 function diaspora_send_mail($item,$owner,$contact) {
2954 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2956 $r = q("select * from conv where id = %d and uid = %d limit 1",
2957 intval($item['convid']),
2958 intval($item['uid'])
2962 logger('diaspora_send_mail: conversation not found.');
2968 'guid' => xmlify($cnv['guid']),
2969 'subject' => xmlify($cnv['subject']),
2970 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2971 'diaspora_handle' => xmlify($cnv['creator']),
2972 'participant_handles' => xmlify($cnv['recips'])
2975 $body = bb2diaspora($item['body']);
2976 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2978 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2979 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2981 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2984 'guid' => xmlify($item['guid']),
2985 'parent_guid' => xmlify($cnv['guid']),
2986 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2987 'author_signature' => xmlify($sig),
2988 'text' => xmlify($body),
2989 'created_at' => xmlify($created),
2990 'diaspora_handle' => xmlify($myaddr),
2991 'conversation_guid' => xmlify($cnv['guid'])
2994 if($item['reply']) {
2995 $tpl = get_markup_template('diaspora_message.tpl');
2996 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2999 $conv['messages'] = array($msg);
3000 $tpl = get_markup_template('diaspora_conversation.tpl');
3001 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3004 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3006 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3007 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3009 return(diaspora_transmit($owner,$contact,$slap,false));
3014 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
3016 $enabled = intval(get_config('system','diaspora_enabled'));
3022 $logid = random_string(4);
3023 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3025 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3029 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
3031 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3035 if (!intval(get_config('system','diaspora_test'))) {
3036 post_url($dest_url . '/', $slap);
3037 $return_code = $a->get_curl_code();
3039 logger('diaspora_transmit: test_mode');
3044 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
3046 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3047 logger('diaspora_transmit: queue message');
3049 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3050 intval($contact['id']),
3051 dbesc(NETWORK_DIASPORA),
3053 intval($public_batch)
3056 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3059 // queue message for redelivery
3060 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3065 return(($return_code) ? $return_code : (-1));