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 '.print_r($msg, true));
40 // Use a dummy importer
41 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
42 diaspora_dispatch($importer,$msg);
48 function diaspora_dispatch($importer,$msg,$attempt=1) {
52 $enabled = intval(get_config('system','diaspora_enabled'));
54 logger('mod-diaspora: disabled');
58 // php doesn't like dashes in variable names
60 $msg['message'] = str_replace(
61 array('<activity_streams-photo>','</activity_streams-photo>'),
62 array('<asphoto>','</asphoto>'),
66 $parsed_xml = parse_xml_string($msg['message'],false);
68 $xmlbase = $parsed_xml->post;
70 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
73 if($xmlbase->request) {
74 $ret = diaspora_request($importer,$xmlbase->request);
76 elseif($xmlbase->status_message) {
77 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
79 elseif($xmlbase->profile) {
80 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
82 elseif($xmlbase->comment) {
83 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
85 elseif($xmlbase->like) {
86 $ret = diaspora_like($importer,$xmlbase->like,$msg);
88 elseif($xmlbase->asphoto) {
89 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
91 elseif($xmlbase->reshare) {
92 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
94 elseif($xmlbase->retraction) {
95 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
97 elseif($xmlbase->signed_retraction) {
98 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
100 elseif($xmlbase->relayable_retraction) {
101 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
103 elseif($xmlbase->photo) {
104 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
106 elseif($xmlbase->conversation) {
107 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
109 elseif($xmlbase->message) {
110 $ret = diaspora_message($importer,$xmlbase->message,$msg);
113 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
118 function diaspora_handle_from_contact($contact_id) {
121 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
123 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
129 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
131 if($contact['network'] === NETWORK_DIASPORA) {
132 $handle = $contact['addr'];
134 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
136 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
137 $baseurl_start = strpos($contact['url'],'://') + 3;
138 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
139 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
140 $handle = $contact['nick'] . '@' . $baseurl;
142 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
149 function diaspora_get_contact_by_handle($uid,$handle) {
150 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
151 dbesc(NETWORK_DIASPORA),
158 $handle_parts = explode("@", $handle);
159 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
160 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
171 function find_diaspora_person_by_handle($handle) {
181 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
182 dbesc(NETWORK_DIASPORA),
187 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
189 // update record occasionally so it doesn't get stale
190 $d = strtotime($person['updated'] . ' +00:00');
191 if($d < strtotime('now - 14 days'))
196 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
198 // If the person isn't in our 'fcontact' table, or if he/she is but
199 // his/her information hasn't been updated for more than 14 days, then
200 // we want to fetch the person's information from the remote server.
202 // Note that $person isn't changed by this block of code unless the
203 // person's information has been successfully fetched from the remote
204 // server. So if $person was 'false' to begin with (because he/she wasn't
205 // in the local cache), it'll stay false, and if $person held the local
206 // cache information to begin with, it'll keep that information. That way
207 // if there's a problem with the remote fetch, we can at least use our
208 // cached information--it's better than nothing.
210 if((! $person) || ($update)) {
211 // Lock the function to prevent race conditions if multiple items
212 // come in at the same time from a person who doesn't exist in
215 // Don't loop forever. On the last loop, try to create the contact
216 // whether the function is locked or not. Maybe the locking thread
217 // has died or something. At any rate, a duplicate in 'fcontact'
218 // is a much smaller problem than a deadlocked thread
219 $got_lock = lock_function('find_diaspora_person_by_handle', false);
220 if(($endlessloop + 1) >= $maxloops)
224 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
225 require_once('include/Scrape.php');
226 $r = probe_url($handle, PROBE_DIASPORA);
228 // Note that Friendica contacts can return a "Diaspora person"
229 // if Diaspora connectivity is enabled on their server
230 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
231 add_fcontact($r,$update);
235 unlock_function('find_diaspora_person_by_handle');
238 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
240 block_on_function_lock('find_diaspora_person_by_handle');
243 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
244 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
245 // The fact that the function was locked may mean that another process was creating the
246 // person's record. It could also mean another process was creating or updating an unrelated
249 // At any rate, we need to keep trying until we've either got the person or had a chance to
250 // try to fetch his/her remote information. But we don't want to block on locking the
251 // function, because if the other process is creating the record, then when we acquire the lock
252 // we'll dive right into creating another, duplicate record. We DO want to at least wait
253 // until the lock is released, so we don't flood the database with requests.
255 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
256 // we do have some information for the person
262 function get_diaspora_key($uri) {
263 logger('Fetching diaspora key for: ' . $uri);
265 $r = find_diaspora_person_by_handle($uri);
272 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
275 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
278 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
280 // $b64_data = base64_encode($msg);
281 // $b64url_data = base64url_encode($b64_data);
283 $b64url_data = base64url_encode($msg);
285 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
287 $type = 'application/xml';
288 $encoding = 'base64url';
291 $signable_data = $data . '.' . base64url_encode($type) . '.'
292 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
294 $signature = rsa_sign($signable_data,$prvkey);
295 $sig = base64url_encode($signature);
298 <?xml version='1.0' encoding='UTF-8'?>
299 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
301 <author_id>$handle</author_id>
304 <me:encoding>base64url</me:encoding>
305 <me:alg>RSA-SHA256</me:alg>
306 <me:data type="application/xml">$data</me:data>
307 <me:sig>$sig</me:sig>
312 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
320 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
324 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
326 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
328 // without a public key nothing will work
331 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
335 $inner_aes_key = random_string(32);
336 $b_inner_aes_key = base64_encode($inner_aes_key);
337 $inner_iv = random_string(16);
338 $b_inner_iv = base64_encode($inner_iv);
340 $outer_aes_key = random_string(32);
341 $b_outer_aes_key = base64_encode($outer_aes_key);
342 $outer_iv = random_string(16);
343 $b_outer_iv = base64_encode($outer_iv);
345 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
347 $padded_data = pkcs5_pad($msg,16);
348 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
350 $b64_data = base64_encode($inner_encrypted);
353 $b64url_data = base64url_encode($b64_data);
354 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
356 $type = 'application/xml';
357 $encoding = 'base64url';
360 $signable_data = $data . '.' . base64url_encode($type) . '.'
361 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
363 $signature = rsa_sign($signable_data,$prvkey);
364 $sig = base64url_encode($signature);
366 $decrypted_header = <<< EOT
369 <aes_key>$b_inner_aes_key</aes_key>
370 <author_id>$handle</author_id>
374 $decrypted_header = pkcs5_pad($decrypted_header,16);
376 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
378 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
380 $encrypted_outer_key_bundle = '';
381 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
383 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
385 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
387 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
388 'ciphertext' => base64_encode($ciphertext)));
389 $cipher_json = base64_encode($encrypted_header_json_object);
391 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
394 <?xml version='1.0' encoding='UTF-8'?>
395 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
398 <me:encoding>base64url</me:encoding>
399 <me:alg>RSA-SHA256</me:alg>
400 <me:data type="application/xml">$data</me:data>
401 <me:sig>$sig</me:sig>
406 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
413 * diaspora_decode($importer,$xml)
414 * array $importer -> from user table
415 * string $xml -> urldecoded Diaspora salmon
418 * 'message' -> decoded Diaspora XML message
419 * 'author' -> author diaspora handle
420 * 'key' -> author public key (converted to pkcs#8)
422 * Author and key are used elsewhere to save a lookup for verifying replies and likes
426 function diaspora_decode($importer,$xml) {
429 $basedom = parse_xml_string($xml);
431 $children = $basedom->children('https://joindiaspora.com/protocol');
433 if($children->header) {
435 $author_link = str_replace('acct:','',$children->header->author_id);
439 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
441 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
442 $ciphertext = base64_decode($encrypted_header->ciphertext);
444 $outer_key_bundle = '';
445 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
447 $j_outer_key_bundle = json_decode($outer_key_bundle);
449 $outer_iv = base64_decode($j_outer_key_bundle->iv);
450 $outer_key = base64_decode($j_outer_key_bundle->key);
452 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
455 $decrypted = pkcs5_unpad($decrypted);
458 * $decrypted now contains something like
461 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
462 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
467 * <name>Ryan Hughes</name>
468 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
473 * <author_id>galaxor@diaspora.priateship.org</author_id>
477 * </decrypted_header>
480 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
481 $idom = parse_xml_string($decrypted,false);
483 $inner_iv = base64_decode($idom->iv);
484 $inner_aes_key = base64_decode($idom->aes_key);
486 $author_link = str_replace('acct:','',$idom->author_id);
490 $dom = $basedom->children(NAMESPACE_SALMON_ME);
492 // figure out where in the DOM tree our data is hiding
494 if($dom->provenance->data)
495 $base = $dom->provenance;
496 elseif($dom->env->data)
502 logger('mod-diaspora: unable to locate salmon data in xml ');
503 http_status_exit(400);
507 // Stash the signature away for now. We have to find their key or it won't be good for anything.
508 $signature = base64url_decode($base->sig);
512 // strip whitespace so our data element will return to one big base64 blob
513 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
516 // stash away some other stuff for later
518 $type = $base->data[0]->attributes()->type[0];
519 $keyhash = $base->sig[0]->attributes()->keyhash[0];
520 $encoding = $base->encoding;
524 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
528 $data = base64url_decode($data);
532 $inner_decrypted = $data;
536 // Decode the encrypted blob
538 $inner_encrypted = base64_decode($data);
539 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
540 $inner_decrypted = pkcs5_unpad($inner_decrypted);
544 logger('mod-diaspora: Could not retrieve author URI.');
545 http_status_exit(400);
548 // Once we have the author URI, go to the web and try to find their public key
549 // (first this will look it up locally if it is in the fcontact cache)
550 // This will also convert diaspora public key from pkcs#1 to pkcs#8
552 logger('mod-diaspora: Fetching key for ' . $author_link );
553 $key = get_diaspora_key($author_link);
556 logger('mod-diaspora: Could not retrieve author key.');
557 http_status_exit(400);
560 $verify = rsa_verify($signed_data,$signature,$key);
563 logger('mod-diaspora: Message did not verify. Discarding.');
564 http_status_exit(400);
567 logger('mod-diaspora: Message verified.');
569 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
574 function diaspora_request($importer,$xml) {
578 $sender_handle = unxmlify($xml->sender_handle);
579 $recipient_handle = unxmlify($xml->recipient_handle);
581 if(! $sender_handle || ! $recipient_handle)
584 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
588 // perhaps we were already sharing with this person. Now they're sharing with us.
589 // That makes us friends.
591 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
592 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
593 intval(CONTACT_IS_FRIEND),
594 intval($contact['id']),
595 intval($importer['uid'])
600 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
601 intval($importer['uid'])
604 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
605 require_once('include/items.php');
607 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
608 intval($importer['uid'])
611 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
613 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
616 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
617 $arr['uid'] = $importer['uid'];
618 $arr['contact-id'] = $self[0]['id'];
620 $arr['type'] = 'wall';
623 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
624 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
625 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
626 $arr['verb'] = ACTIVITY_FRIEND;
627 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
629 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
630 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
631 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
632 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
634 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
635 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
636 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
637 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
638 $arr['object'] .= '</link></object>' . "\n";
639 $arr['last-child'] = 1;
641 $arr['allow_cid'] = $user[0]['allow_cid'];
642 $arr['allow_gid'] = $user[0]['allow_gid'];
643 $arr['deny_cid'] = $user[0]['deny_cid'];
644 $arr['deny_gid'] = $user[0]['deny_gid'];
646 $i = item_store($arr);
648 proc_run('php',"include/notifier.php","activity","$i");
657 $ret = find_diaspora_person_by_handle($sender_handle);
660 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
661 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
665 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
669 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
670 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
671 intval($importer['uid']),
672 dbesc($ret['network']),
676 dbesc(normalise_link($ret['url'])),
680 dbesc($ret['photo']),
681 dbesc($ret['pubkey']),
682 dbesc($ret['notify']),
688 // find the contact record we just created
690 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
692 if(! $contact_record) {
693 logger('diaspora_request: unable to locate newly created contact record.');
697 $g = q("select def_gid from user where uid = %d limit 1",
698 intval($importer['uid'])
700 if($g && intval($g[0]['def_gid'])) {
701 require_once('include/group.php');
702 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
705 if($importer['page-flags'] == PAGE_NORMAL) {
707 $hash = random_string() . (string) time(); // Generate a confirm_key
709 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
710 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
711 intval($importer['uid']),
712 intval($contact_record['id']),
715 dbesc( t('Sharing notification from Diaspora network')),
717 dbesc(datetime_convert())
722 // automatic friend approval
724 require_once('include/Photo.php');
726 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
728 // technically they are sharing with us (CONTACT_IS_SHARING),
729 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
730 // we are going to change the relationship and make them a follower.
732 if($importer['page-flags'] == PAGE_FREELOVE)
733 $new_relation = CONTACT_IS_FRIEND;
735 $new_relation = CONTACT_IS_FOLLOWER;
737 $r = q("UPDATE `contact` SET
744 `avatar-date` = '%s',
753 intval($new_relation),
754 dbesc(datetime_convert()),
755 dbesc(datetime_convert()),
756 dbesc(datetime_convert()),
757 intval($contact_record['id'])
760 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
762 $ret = diaspora_share($u[0],$contact_record);
768 function diaspora_post_allow($importer,$contact) {
770 // perhaps we were already sharing with this person. Now they're sharing with us.
771 // That makes us friends.
772 // Normally this should have handled by getting a request - but this could get lost
773 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
774 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
775 intval(CONTACT_IS_FRIEND),
776 intval($contact['id']),
777 intval($importer['uid'])
779 $contact['rel'] = CONTACT_IS_FRIEND;
780 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
783 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
785 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
787 if($contact['rel'] == CONTACT_IS_FOLLOWER)
788 if($importer['page-flags'] == PAGE_COMMUNITY)
791 // Messages for the global users are always accepted
792 if ($importer['uid'] == 0)
798 function diaspora_is_redmatrix($url) {
799 return(strstr($url, "/channel/"));
802 function diaspora_plink($addr, $guid) {
803 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", $addr);
807 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
809 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
810 // So we try another way as well.
811 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
813 $r[0]["network"] = $s[0]["network"];
815 if ($r[0]["network"] == NETWORK_DFRN)
816 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
818 if (diaspora_is_redmatrix($r[0]["url"]))
819 return $r[0]["url"]."/?f=&mid=".$guid;
821 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
824 function diaspora_post($importer,$xml,$msg) {
827 $guid = notags(unxmlify($xml->guid));
828 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
830 if($diaspora_handle != $msg['author']) {
831 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
835 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
839 if(! diaspora_post_allow($importer,$contact)) {
840 logger('diaspora_post: Ignoring this author.');
844 $message_id = $diaspora_handle . ':' . $guid;
845 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
846 intval($importer['uid']),
851 logger('diaspora_post: message exists: ' . $guid);
855 $created = unxmlify($xml->created_at);
856 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
858 $body = diaspora2bb($xml->raw_message);
862 $datarray["object"] = json_encode($xml);
864 if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
865 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
867 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
868 // Add OEmbed and other information to the body
869 if (!diaspora_is_redmatrix($contact['url']))
870 $body = add_page_info_to_body($body, false, true);
875 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
877 foreach($matches as $mtch) {
878 if(strlen($str_tags))
880 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
884 $plink = diaspora_plink($diaspora_handle, $guid);
886 $datarray['uid'] = $importer['uid'];
887 $datarray['contact-id'] = $contact['id'];
888 $datarray['wall'] = 0;
889 $datarray['network'] = NETWORK_DIASPORA;
890 $datarray['verb'] = ACTIVITY_POST;
891 $datarray['guid'] = $guid;
892 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
893 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
894 $datarray['private'] = $private;
895 $datarray['parent'] = 0;
896 $datarray['plink'] = $plink;
897 $datarray['owner-name'] = $contact['name'];
898 $datarray['owner-link'] = $contact['url'];
899 //$datarray['owner-avatar'] = $contact['thumb'];
900 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
901 $datarray['author-name'] = $contact['name'];
902 $datarray['author-link'] = $contact['url'];
903 $datarray['author-avatar'] = $contact['thumb'];
904 $datarray['body'] = $body;
905 $datarray['tag'] = $str_tags;
906 if ($xml->provider_display_name)
907 $datarray["app"] = unxmlify($xml->provider_display_name);
909 $datarray['app'] = 'Diaspora';
911 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
913 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
915 DiasporaFetchGuid($datarray);
916 $message_id = item_store($datarray);
922 function DiasporaFetchGuid($item) {
923 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
924 function ($match) use ($item){
925 return(DiasporaFetchGuidSub($match, $item));
929 function DiasporaFetchGuidSub($match, $item) {
932 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
933 diaspora_store_by_guid($match[1], $item["owner-link"]);
936 function diaspora_store_by_guid($guid, $server, $uid = 0) {
937 require_once("include/Contact.php");
939 $serverparts = parse_url($server);
940 $server = $serverparts["scheme"]."://".$serverparts["host"];
942 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
944 $item = diaspora_fetch_message($guid, $server);
949 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
951 $body = $item["body"];
952 $str_tags = $item["tag"];
954 $created = $item["created"];
955 $author = $item["author"];
956 $guid = $item["guid"];
957 $private = $item["private"];
958 $object = $item["object"];
959 $objecttype = $item["object-type"];
961 $message_id = $author.':'.$guid;
962 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
970 $person = find_diaspora_person_by_handle($author);
973 $datarray['uid'] = $uid;
974 $datarray['contact-id'] = get_contact($person['url'], $uid);
975 $datarray['wall'] = 0;
976 $datarray['network'] = NETWORK_DIASPORA;
977 $datarray['guid'] = $guid;
978 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
979 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
980 $datarray['private'] = $private;
981 $datarray['parent'] = 0;
982 $datarray['plink'] = diaspora_plink($author, $guid);
983 $datarray['author-name'] = $person['name'];
984 $datarray['author-link'] = $person['url'];
985 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
986 $datarray['owner-name'] = $datarray['author-name'];
987 $datarray['owner-link'] = $datarray['author-link'];
988 $datarray['owner-avatar'] = $datarray['author-avatar'];
989 $datarray['body'] = $body;
990 $datarray['tag'] = $str_tags;
991 $datarray['app'] = $app;
992 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
993 $datarray['object'] = $object;
994 $datarray['object-type'] = $objecttype;
996 if ($datarray['contact-id'] == 0)
999 DiasporaFetchGuid($datarray);
1000 $message_id = item_store($datarray);
1003 // Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
1008 function diaspora_fetch_message($guid, $server, $level = 0) {
1015 // This will not work if the server is not a Diaspora server
1016 $source_url = $server.'/p/'.$guid.'.xml';
1017 $x = fetch_url($source_url);
1021 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1022 $source_xml = parse_xml_string($x,false);
1025 $item["app"] = 'Diaspora';
1026 $item["guid"] = $guid;
1029 if ($source_xml->post->status_message->created_at)
1030 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1032 if ($source_xml->post->status_message->provider_display_name)
1033 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1035 if ($source_xml->post->status_message->diaspora_handle)
1036 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1038 if ($source_xml->post->status_message->guid)
1039 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1041 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1042 $item["object"] = json_encode($source_xml->post);
1044 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1045 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1046 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1047 $body = scale_external_images($body,false);
1048 } elseif($source_xml->post->asphoto->image_url) {
1049 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1050 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1051 $body = scale_external_images($body);
1052 } elseif($source_xml->post->status_message) {
1053 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1055 // Checking for embedded pictures
1056 if($source_xml->post->status_message->photo->remote_photo_path AND
1057 $source_xml->post->status_message->photo->remote_photo_name) {
1059 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1061 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1062 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1064 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1066 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1068 $item["object-type"] = ACTIVITY_OBJ_NOTE;
1070 $body = scale_external_images($body);
1072 // Add OEmbed and other information to the body
1073 // To-Do: It could be a repeated redmatrix item
1074 // Then we shouldn't add further data to it
1075 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1076 $body = add_page_info_to_body($body, false, true);
1078 } elseif($source_xml->post->reshare) {
1079 // Reshare of a reshare
1080 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1082 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1083 logger('no content found: '.print_r($source_xml,true));
1087 if (trim($body) == "")
1091 $item["body"] = $body;
1096 function diaspora_reshare($importer,$xml,$msg) {
1098 logger('diaspora_reshare: init: ' . print_r($xml,true));
1101 $guid = notags(unxmlify($xml->guid));
1102 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1105 if($diaspora_handle != $msg['author']) {
1106 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1110 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1114 if(! diaspora_post_allow($importer,$contact)) {
1115 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1119 $message_id = $diaspora_handle . ':' . $guid;
1120 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1121 intval($importer['uid']),
1126 logger('diaspora_reshare: message exists: ' . $guid);
1130 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1131 $orig_guid = notags(unxmlify($xml->root_guid));
1132 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1134 $create_original_post = false;
1136 // Do we already have this item?
1137 $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",
1139 dbesc(NETWORK_DIASPORA)
1142 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1144 // Maybe it is already a reshared item?
1145 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1146 require_once('include/api.php');
1147 if (api_share_as_retweet($r[0]))
1150 $body = $r[0]["body"];
1151 $str_tags = $r[0]["tag"];
1152 $app = $r[0]["app"];
1153 $orig_created = $r[0]["created"];
1154 $orig_plink = $r[0]["plink"];
1155 $orig_uri = $r[0]["uri"];
1156 $object = $r[0]["object"];
1157 $objecttype = $r[0]["object-type"];
1166 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1167 logger('1st 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 = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1172 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1173 $item = diaspora_fetch_message($orig_guid, $server);
1176 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1177 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1178 $item = diaspora_fetch_message($orig_guid, $server);
1181 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1182 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1183 $item = diaspora_fetch_message($orig_guid, $server);
1187 $body = $item["body"];
1188 $str_tags = $item["tag"];
1189 $app = $item["app"];
1190 $orig_created = $item["created"];
1191 $orig_author = $item["author"];
1192 $orig_guid = $item["guid"];
1193 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1194 $orig_uri = $orig_author.':'.$orig_guid;
1195 $create_original_post = ($body != "");
1196 $object = $item["object"];
1197 $objecttype = $item["object-type"];
1201 $plink = diaspora_plink($diaspora_handle, $guid);
1203 $person = find_diaspora_person_by_handle($orig_author);
1205 $created = unxmlify($xml->created_at);
1206 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1208 $datarray = array();
1210 $datarray['uid'] = $importer['uid'];
1211 $datarray['contact-id'] = $contact['id'];
1212 $datarray['wall'] = 0;
1213 $datarray['network'] = NETWORK_DIASPORA;
1214 $datarray['guid'] = $guid;
1215 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1216 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1217 $datarray['private'] = $private;
1218 $datarray['parent'] = 0;
1219 $datarray['plink'] = $plink;
1220 $datarray['owner-name'] = $contact['name'];
1221 $datarray['owner-link'] = $contact['url'];
1222 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1223 if (!intval(get_config('system','wall-to-wall_share'))) {
1224 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1226 $datarray['author-name'] = $contact['name'];
1227 $datarray['author-link'] = $contact['url'];
1228 $datarray['author-avatar'] = $contact['thumb'];
1229 $datarray['body'] = $prefix.$body."[/share]";
1231 // Let reshared messages look like wall-to-wall posts
1232 $datarray['author-name'] = $person['name'];
1233 $datarray['author-link'] = $person['url'];
1234 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1235 $datarray['body'] = $body;
1238 $datarray["object"] = json_encode($xml);
1239 $datarray['object-type'] = $objecttype;
1241 $datarray['tag'] = $str_tags;
1242 $datarray['app'] = $app;
1244 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1245 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1247 // Store the original item of a reshare
1248 if ($create_original_post) {
1249 require_once("include/Contact.php");
1251 $datarray2 = $datarray;
1253 $datarray2['uid'] = 0;
1254 $datarray2['contact-id'] = get_contact($person['url'], 0);
1255 $datarray2['guid'] = $orig_guid;
1256 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1257 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1258 $datarray2['parent'] = 0;
1259 $datarray2['plink'] = $orig_plink;
1261 $datarray2['author-name'] = $person['name'];
1262 $datarray2['author-link'] = $person['url'];
1263 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1264 $datarray2['owner-name'] = $datarray2['author-name'];
1265 $datarray2['owner-link'] = $datarray2['author-link'];
1266 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1267 $datarray2['body'] = $body;
1268 $datarray2["object"] = $object;
1270 DiasporaFetchGuid($datarray2);
1271 $message_id = item_store($datarray2);
1273 logger("Store original item ".$orig_guid." under message id ".$message_id);
1276 DiasporaFetchGuid($datarray);
1277 $message_id = item_store($datarray);
1284 function diaspora_asphoto($importer,$xml,$msg) {
1285 logger('diaspora_asphoto called');
1288 $guid = notags(unxmlify($xml->guid));
1289 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1291 if($diaspora_handle != $msg['author']) {
1292 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1296 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1300 if(! diaspora_post_allow($importer,$contact)) {
1301 logger('diaspora_asphoto: Ignoring this author.');
1305 $message_id = $diaspora_handle . ':' . $guid;
1306 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1307 intval($importer['uid']),
1312 logger('diaspora_asphoto: message exists: ' . $guid);
1316 $created = unxmlify($xml->created_at);
1317 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1319 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1320 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1321 $body = scale_external_images($body,false);
1323 elseif($xml->image_url) {
1324 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1325 $body = scale_external_images($body);
1328 logger('diaspora_asphoto: no photo url found.');
1332 $plink = diaspora_plink($diaspora_handle, $guid);
1334 $datarray = array();
1336 $datarray['uid'] = $importer['uid'];
1337 $datarray['contact-id'] = $contact['id'];
1338 $datarray['wall'] = 0;
1339 $datarray['network'] = NETWORK_DIASPORA;
1340 $datarray['guid'] = $guid;
1341 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1342 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1343 $datarray['private'] = $private;
1344 $datarray['parent'] = 0;
1345 $datarray['plink'] = $plink;
1346 $datarray['owner-name'] = $contact['name'];
1347 $datarray['owner-link'] = $contact['url'];
1348 //$datarray['owner-avatar'] = $contact['thumb'];
1349 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1350 $datarray['author-name'] = $contact['name'];
1351 $datarray['author-link'] = $contact['url'];
1352 $datarray['author-avatar'] = $contact['thumb'];
1353 $datarray['body'] = $body;
1354 $datarray["object"] = json_encode($xml);
1355 $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1357 $datarray['app'] = 'Diaspora/Cubbi.es';
1359 DiasporaFetchGuid($datarray);
1360 $message_id = item_store($datarray);
1363 // q("update item set plink = '%s' where id = %d",
1364 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1365 // intval($message_id)
1378 function diaspora_comment($importer,$xml,$msg) {
1381 $guid = notags(unxmlify($xml->guid));
1382 $parent_guid = notags(unxmlify($xml->parent_guid));
1383 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1384 $target_type = notags(unxmlify($xml->target_type));
1385 $text = unxmlify($xml->text);
1386 $author_signature = notags(unxmlify($xml->author_signature));
1388 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1390 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1392 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1396 if(! diaspora_post_allow($importer,$contact)) {
1397 logger('diaspora_comment: Ignoring this author.');
1401 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1402 intval($importer['uid']),
1406 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1410 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1411 intval($importer['uid']),
1416 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1419 $person = find_diaspora_person_by_handle($diaspora_handle);
1420 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1424 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1426 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1427 intval($importer['uid']),
1434 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1437 $parent_item = $r[0];
1440 /* How Diaspora performs comment signature checking:
1442 - If an item has been sent by the comment author to the top-level post owner to relay on
1443 to the rest of the contacts on the top-level post, the top-level post owner should check
1444 the author_signature, then create a parent_author_signature before relaying the comment on
1445 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1446 check only the parent_author_signature. Basically, they trust that the top-level post
1447 owner has already verified the authenticity of anything he/she sends out
1448 - In either case, the signature that get checked is the signature created by the person
1452 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1455 if($parent_author_signature) {
1456 // If a parent_author_signature exists, then we've received the comment
1457 // relayed from the top-level post owner. There's no need to check the
1458 // author_signature if the parent_author_signature is valid
1460 $parent_author_signature = base64_decode($parent_author_signature);
1462 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1463 logger('diaspora_comment: top-level owner verification failed.');
1468 // If there's no parent_author_signature, then we've received the comment
1469 // from the comment creator. In that case, the person is commenting on
1470 // our post, so he/she must be a contact of ours and his/her public key
1471 // should be in $msg['key']
1473 $author_signature = base64_decode($author_signature);
1475 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1476 logger('diaspora_comment: comment author verification failed.');
1481 // Phew! Everything checks out. Now create an item.
1483 // Find the original comment author information.
1484 // We need this to make sure we display the comment author
1485 // information (name and avatar) correctly.
1486 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1489 $person = find_diaspora_person_by_handle($diaspora_handle);
1491 if(! is_array($person)) {
1492 logger('diaspora_comment: unable to find author details');
1497 $body = diaspora2bb($text);
1498 $message_id = $diaspora_handle . ':' . $guid;
1500 $datarray = array();
1502 $datarray['uid'] = $importer['uid'];
1503 $datarray['contact-id'] = $contact['id'];
1504 $datarray['type'] = 'remote-comment';
1505 $datarray['wall'] = $parent_item['wall'];
1506 $datarray['network'] = NETWORK_DIASPORA;
1507 $datarray['verb'] = ACTIVITY_POST;
1508 $datarray['gravity'] = GRAVITY_COMMENT;
1509 $datarray['guid'] = $guid;
1510 $datarray['uri'] = $message_id;
1511 $datarray['parent-uri'] = $parent_item['uri'];
1513 // No timestamps for comments? OK, we'll the use current time.
1514 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1515 $datarray['private'] = $parent_item['private'];
1517 $datarray['owner-name'] = $parent_item['owner-name'];
1518 $datarray['owner-link'] = $parent_item['owner-link'];
1519 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1521 $datarray['author-name'] = $person['name'];
1522 $datarray['author-link'] = $person['url'];
1523 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1524 $datarray['body'] = $body;
1525 $datarray["object"] = json_encode($xml);
1526 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1528 // We can't be certain what the original app is if the message is relayed.
1529 if(($parent_item['origin']) && (! $parent_author_signature))
1530 $datarray['app'] = 'Diaspora';
1532 DiasporaFetchGuid($datarray);
1533 $message_id = item_store($datarray);
1535 $datarray['id'] = $message_id;
1538 //q("update item set plink = '%s' where id = %d",
1539 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1540 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1541 // intval($message_id)
1545 if(($parent_item['origin']) && (! $parent_author_signature)) {
1546 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1547 intval($message_id),
1548 dbesc($signed_data),
1549 dbesc(base64_encode($author_signature)),
1550 dbesc($diaspora_handle)
1553 // if the message isn't already being relayed, notify others
1554 // the existence of parent_author_signature means the parent_author or owner
1555 // is already relaying.
1557 proc_run('php','include/notifier.php','comment-import',$message_id);
1560 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1561 dbesc($parent_item['uri']),
1562 intval($importer['uid'])
1565 if(count($myconv)) {
1566 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1568 foreach($myconv as $conv) {
1570 // now if we find a match, it means we're in this conversation
1572 if(! link_compare($conv['author-link'],$importer_url))
1575 require_once('include/enotify.php');
1577 $conv_parent = $conv['parent'];
1580 'type' => NOTIFY_COMMENT,
1581 'notify_flags' => $importer['notify-flags'],
1582 'language' => $importer['language'],
1583 'to_name' => $importer['username'],
1584 'to_email' => $importer['email'],
1585 'uid' => $importer['uid'],
1586 'item' => $datarray,
1587 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1588 'source_name' => $datarray['author-name'],
1589 'source_link' => $datarray['author-link'],
1590 'source_photo' => $datarray['author-avatar'],
1591 'verb' => ACTIVITY_POST,
1593 'parent' => $conv_parent,
1594 'parent_uri' => $parent_uri
1597 // only send one notification
1607 function diaspora_conversation($importer,$xml,$msg) {
1611 $guid = notags(unxmlify($xml->guid));
1612 $subject = notags(unxmlify($xml->subject));
1613 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1614 $participant_handles = notags(unxmlify($xml->participant_handles));
1615 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1617 $parent_uri = $diaspora_handle . ':' . $guid;
1619 $messages = $xml->message;
1621 if(! count($messages)) {
1622 logger('diaspora_conversation: empty conversation');
1626 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1628 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1632 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1633 logger('diaspora_conversation: Ignoring this author.');
1637 $conversation = null;
1639 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1640 intval($importer['uid']),
1644 $conversation = $c[0];
1646 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1647 intval($importer['uid']),
1649 dbesc($diaspora_handle),
1650 dbesc(datetime_convert('UTC','UTC',$created_at)),
1651 dbesc(datetime_convert()),
1653 dbesc($participant_handles)
1656 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1657 intval($importer['uid']),
1661 $conversation = $c[0];
1663 if(! $conversation) {
1664 logger('diaspora_conversation: unable to create conversation.');
1668 foreach($messages as $mesg) {
1672 $msg_guid = notags(unxmlify($mesg->guid));
1673 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1674 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1675 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1676 $msg_text = unxmlify($mesg->text);
1677 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1678 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1679 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1680 if($msg_conversation_guid != $guid) {
1681 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1685 $body = diaspora2bb($msg_text);
1686 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1688 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1690 $author_signature = base64_decode($msg_author_signature);
1692 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1697 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1699 if(is_array($person) && x($person,'pubkey'))
1700 $key = $person['pubkey'];
1702 logger('diaspora_conversation: unable to find author details');
1707 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1708 logger('diaspora_conversation: verification failed.');
1712 if($msg_parent_author_signature) {
1713 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1715 $parent_author_signature = base64_decode($msg_parent_author_signature);
1719 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1720 logger('diaspora_conversation: owner verification failed.');
1725 $r = q("select id from mail where `uri` = '%s' limit 1",
1729 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1733 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')",
1734 intval($importer['uid']),
1736 intval($conversation['id']),
1737 dbesc($person['name']),
1738 dbesc($person['photo']),
1739 dbesc($person['url']),
1740 intval($contact['id']),
1747 dbesc($msg_created_at)
1750 q("update conv set updated = '%s' where id = %d",
1751 dbesc(datetime_convert()),
1752 intval($conversation['id'])
1755 require_once('include/enotify.php');
1757 'type' => NOTIFY_MAIL,
1758 'notify_flags' => $importer['notify-flags'],
1759 'language' => $importer['language'],
1760 'to_name' => $importer['username'],
1761 'to_email' => $importer['email'],
1762 'uid' =>$importer['uid'],
1763 'item' => array('subject' => $subject, 'body' => $body),
1764 'source_name' => $person['name'],
1765 'source_link' => $person['url'],
1766 'source_photo' => $person['thumb'],
1767 'verb' => ACTIVITY_POST,
1775 function diaspora_message($importer,$xml,$msg) {
1779 $msg_guid = notags(unxmlify($xml->guid));
1780 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1781 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1782 $msg_author_signature = notags(unxmlify($xml->author_signature));
1783 $msg_text = unxmlify($xml->text);
1784 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1785 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1786 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1788 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1790 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1792 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1796 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1797 logger('diaspora_message: Ignoring this author.');
1801 $conversation = null;
1803 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1804 intval($importer['uid']),
1805 dbesc($msg_conversation_guid)
1808 $conversation = $c[0];
1810 logger('diaspora_message: conversation not available.');
1816 $body = diaspora2bb($msg_text);
1817 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1819 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1822 $author_signature = base64_decode($msg_author_signature);
1824 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1825 if(is_array($person) && x($person,'pubkey'))
1826 $key = $person['pubkey'];
1828 logger('diaspora_message: unable to find author details');
1832 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1833 logger('diaspora_message: verification failed.');
1837 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1839 intval($importer['uid'])
1842 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1846 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1847 intval($importer['uid']),
1849 intval($conversation['id']),
1850 dbesc($person['name']),
1851 dbesc($person['photo']),
1852 dbesc($person['url']),
1853 intval($contact['id']),
1854 dbesc($conversation['subject']),
1860 dbesc($msg_created_at)
1863 q("update conv set updated = '%s' where id = %d",
1864 dbesc(datetime_convert()),
1865 intval($conversation['id'])
1872 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1876 logger('diaspora_photo: init',LOGGER_DEBUG);
1878 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1880 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1882 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1884 $guid = notags(unxmlify($xml->guid));
1886 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1888 $public = notags(unxmlify($xml->public));
1890 $created_at = notags(unxmlify($xml_created_at));
1892 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1894 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1896 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1900 if(! diaspora_post_allow($importer,$contact)) {
1901 logger('diaspora_photo: Ignoring this author.');
1905 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1906 intval($importer['uid']),
1907 dbesc($status_message_guid)
1910 /* deactivated by now since it can lead to multiplicated pictures in posts.
1912 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1915 $person = find_diaspora_person_by_handle($diaspora_handle);
1916 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1920 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1922 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1923 intval($importer['uid']),
1924 dbesc($status_message_guid)
1931 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1932 intval($importer['uid']),
1933 dbesc(serialize($msg)),
1934 intval($attempt + 1)
1938 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1942 $parent_item = $r[0];
1944 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1946 $link_text = scale_external_images($link_text, true,
1947 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1949 if(strpos($parent_item['body'],$link_text) === false) {
1950 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1951 dbesc($link_text . $parent_item['body']),
1952 intval($parent_item['id']),
1953 intval($parent_item['uid'])
1955 update_thread($parent_item['id']);
1964 function diaspora_like($importer,$xml,$msg) {
1967 $guid = notags(unxmlify($xml->guid));
1968 $parent_guid = notags(unxmlify($xml->parent_guid));
1969 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1970 $target_type = notags(unxmlify($xml->target_type));
1971 $positive = notags(unxmlify($xml->positive));
1972 $author_signature = notags(unxmlify($xml->author_signature));
1974 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1976 // likes on comments not supported here and likes on photos not supported by Diaspora
1978 // if($target_type !== 'Post')
1981 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1983 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1987 if(! diaspora_post_allow($importer,$contact)) {
1988 logger('diaspora_like: Ignoring this author.');
1992 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1993 intval($importer['uid']),
1998 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
2001 $person = find_diaspora_person_by_handle($diaspora_handle);
2002 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
2006 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
2008 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2009 intval($importer['uid']),
2016 logger('diaspora_like: parent item not found: ' . $guid);
2020 $parent_item = $r[0];
2022 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2023 intval($importer['uid']),
2027 if($positive === 'true') {
2028 logger('diaspora_like: duplicate like: ' . $guid);
2031 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2032 // It looks like "RelayableRetractions" are used for "unlike" instead
2033 if($positive === 'false') {
2034 logger('diaspora_like: received a like with positive set to "false"...ignoring');
2035 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2036 intval($r[0]['id']),
2037 intval($importer['uid'])
2039 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2040 // send notification via proc_run()
2044 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2045 // It looks like "RelayableRetractions" are used for "unlike" instead
2046 if($positive === 'false') {
2047 logger('diaspora_like: received a like with positive set to "false"');
2048 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2053 /* How Diaspora performs "like" signature checking:
2055 - If an item has been sent by the like author to the top-level post owner to relay on
2056 to the rest of the contacts on the top-level post, the top-level post owner should check
2057 the author_signature, then create a parent_author_signature before relaying the like on
2058 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2059 check only the parent_author_signature. Basically, they trust that the top-level post
2060 owner has already verified the authenticity of anything he/she sends out
2061 - In either case, the signature that get checked is the signature created by the person
2065 // Diaspora has changed the way they are signing the likes.
2066 // Just to make sure that we don't miss any likes we will check the old and the current way.
2067 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2069 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2073 if ($parent_author_signature) {
2074 // If a parent_author_signature exists, then we've received the like
2075 // relayed from the top-level post owner. There's no need to check the
2076 // author_signature if the parent_author_signature is valid
2078 $parent_author_signature = base64_decode($parent_author_signature);
2080 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2081 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2083 logger('diaspora_like: top-level owner verification failed.');
2087 // If there's no parent_author_signature, then we've received the like
2088 // from the like creator. In that case, the person is "like"ing
2089 // our post, so he/she must be a contact of ours and his/her public key
2090 // should be in $msg['key']
2092 $author_signature = base64_decode($author_signature);
2094 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2095 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2097 logger('diaspora_like: like creator verification failed.');
2102 // Phew! Everything checks out. Now create an item.
2104 // Find the original comment author information.
2105 // We need this to make sure we display the comment author
2106 // information (name and avatar) correctly.
2107 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2110 $person = find_diaspora_person_by_handle($diaspora_handle);
2112 if(! is_array($person)) {
2113 logger('diaspora_like: unable to find author details');
2118 $uri = $diaspora_handle . ':' . $guid;
2120 $activity = ACTIVITY_LIKE;
2121 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2122 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2123 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2124 $body = $parent_item['body'];
2129 <type>$objtype</type>
2131 <id>{$parent_item['uri']}</id>
2134 <content>$body</content>
2137 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2142 $arr['uid'] = $importer['uid'];
2143 $arr['guid'] = $guid;
2144 $arr['network'] = NETWORK_DIASPORA;
2145 $arr['contact-id'] = $contact['id'];
2146 $arr['type'] = 'activity';
2147 $arr['wall'] = $parent_item['wall'];
2148 $arr['gravity'] = GRAVITY_LIKE;
2149 $arr['parent'] = $parent_item['id'];
2150 $arr['parent-uri'] = $parent_item['uri'];
2152 $arr['owner-name'] = $parent_item['name'];
2153 $arr['owner-link'] = $parent_item['url'];
2154 //$arr['owner-avatar'] = $parent_item['thumb'];
2155 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2157 $arr['author-name'] = $person['name'];
2158 $arr['author-link'] = $person['url'];
2159 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2161 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2162 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2163 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2164 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2165 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2167 $arr['app'] = 'Diaspora';
2169 $arr['private'] = $parent_item['private'];
2170 $arr['verb'] = $activity;
2171 $arr['object-type'] = $objtype;
2172 $arr['object'] = $obj;
2173 $arr['visible'] = 1;
2175 $arr['last-child'] = 0;
2177 $message_id = item_store($arr);
2181 // q("update item set plink = '%s' where id = %d",
2182 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2183 // dbesc($a->get_baseurl().'/display/'.$guid),
2184 // intval($message_id)
2188 if(! $parent_author_signature) {
2189 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2190 intval($message_id),
2191 dbesc($signed_data),
2192 dbesc(base64_encode($author_signature)),
2193 dbesc($diaspora_handle)
2197 // if the message isn't already being relayed, notify others
2198 // the existence of parent_author_signature means the parent_author or owner
2199 // is already relaying. The parent_item['origin'] indicates the message was created on our system
2201 if(($parent_item['origin']) && (! $parent_author_signature))
2202 proc_run('php','include/notifier.php','comment-import',$message_id);
2207 function diaspora_retraction($importer,$xml) {
2210 $guid = notags(unxmlify($xml->guid));
2211 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2212 $type = notags(unxmlify($xml->type));
2214 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2218 if($type === 'Person') {
2219 require_once('include/Contact.php');
2220 contact_remove($contact['id']);
2222 elseif($type === 'Post') {
2223 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2225 intval($importer['uid'])
2228 if(link_compare($r[0]['author-link'],$contact['url'])) {
2229 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2230 dbesc(datetime_convert()),
2233 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2242 function diaspora_signed_retraction($importer,$xml,$msg) {
2245 $guid = notags(unxmlify($xml->target_guid));
2246 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2247 $type = notags(unxmlify($xml->target_type));
2248 $sig = notags(unxmlify($xml->target_author_signature));
2250 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2252 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2254 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2259 $signed_data = $guid . ';' . $type ;
2262 /* How Diaspora performs relayable_retraction signature checking:
2264 - If an item has been sent by the item author to the top-level post owner to relay on
2265 to the rest of the contacts on the top-level post, the top-level post owner checks
2266 the author_signature, then creates a parent_author_signature before relaying the item on
2267 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2268 check only the parent_author_signature. Basically, they trust that the top-level post
2269 owner has already verified the authenticity of anything he/she sends out
2270 - In either case, the signature that get checked is the signature created by the person
2274 if($parent_author_signature) {
2276 $parent_author_signature = base64_decode($parent_author_signature);
2278 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2279 logger('diaspora_signed_retraction: top-level post owner verification failed');
2286 $sig_decode = base64_decode($sig);
2288 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2289 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2294 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2295 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2297 intval($importer['uid'])
2300 if(link_compare($r[0]['author-link'],$contact['url'])) {
2301 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2302 dbesc(datetime_convert()),
2303 dbesc(datetime_convert()),
2306 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2308 // Now check if the retraction needs to be relayed by us
2310 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2311 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2312 // The only item with `parent` and `id` as the parent id is the parent item.
2313 $p = q("select origin from item where parent = %d and id = %d limit 1",
2318 if(($p[0]['origin']) && (! $parent_author_signature)) {
2319 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2321 dbesc($signed_data),
2323 dbesc($diaspora_handle)
2326 // the existence of parent_author_signature would have meant the parent_author or owner
2327 // is already relaying.
2328 logger('diaspora_signed_retraction: relaying relayable_retraction');
2330 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2337 logger('diaspora_signed_retraction: unknown type: ' . $type);
2343 function diaspora_profile($importer,$xml,$msg) {
2346 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2349 if($diaspora_handle != $msg['author']) {
2350 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2354 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2358 if($contact['blocked']) {
2359 logger('diaspora_post: Ignoring this author.');
2363 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2364 $image_url = unxmlify($xml->image_url);
2365 $birthday = unxmlify($xml->birthday);
2366 $location = diaspora2bb(unxmlify($xml->location));
2367 $about = diaspora2bb(unxmlify($xml->bio));
2368 $gender = unxmlify($xml->gender);
2369 $tags = unxmlify($xml->tag_string);
2371 $tags = explode("#", $tags);
2373 $keywords = array();
2374 foreach ($tags as $tag) {
2375 $tag = trim(strtolower($tag));
2380 $keywords = implode(", ", $keywords);
2382 $handle_parts = explode("@", $diaspora_handle);
2384 $name = $handle_parts[0];
2387 if( preg_match("|^https?://|", $image_url) === 0) {
2388 $image_url = "http://" . $handle_parts[1] . $image_url;
2391 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2392 intval($importer['uid']),
2393 intval($contact['id'])
2395 $oldphotos = ((count($r)) ? $r : null);*/
2397 require_once('include/Photo.php');
2399 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2401 // Generic birthday. We don't know the timezone. The year is irrelevant.
2403 $birthday = str_replace('1000','1901',$birthday);
2405 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2407 // this is to prevent multiple birthday notifications in a single year
2408 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2410 if(substr($birthday,5) === substr($contact['bd'],5))
2411 $birthday = $contact['bd'];
2413 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2414 // Not doing this currently because D* protocol is scheduled for revision soon.
2416 $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",
2418 dbesc(datetime_convert()),
2422 dbesc(datetime_convert()),
2428 intval($contact['id']),
2429 intval($importer['uid'])
2432 if (unxmlify($xml->searchable) == "true") {
2433 require_once('include/socgraph.php');
2434 poco_check($contact['url'], $name, NETWORK_DIASPORA, $images[0], $about, $location, $gender, $keywords, "",
2435 datetime_convert(), 2, $contact['id'], $importer['uid']);
2439 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
2440 dbesc(normalise_link($contact['url'])));
2442 if (count($author) == 0) {
2443 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`, `location`, `about`) VALUES ('%s', '%s', '%s', '%s', '%s')",
2444 dbesc(normalise_link($contact['url'])), dbesc($name), dbesc($location), dbesc($about), dbesc($images[0]));
2446 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
2447 dbesc(normalise_link($contact['url'])));
2448 } else if (normalise_link($contact['url']).$name.$location.$about != normalise_link($author[0]["url"]).$author[0]["name"].$author[0]["location"].$author[0]["about"]) {
2449 q("UPDATE unique_contacts SET name = '%s', avatar = '%s', `location` = '%s', `about` = '%s' WHERE url = '%s'",
2450 dbesc($name), dbesc($images[0]), dbesc($location), dbesc($about), dbesc(normalise_link($contact['url'])));
2455 foreach($oldphotos as $ph) {
2456 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2457 intval($importer['uid']),
2458 intval($contact['id']),
2459 dbesc($ph['resource-id'])
2469 function diaspora_share($me,$contact) {
2471 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2472 $theiraddr = $contact['addr'];
2474 $tpl = get_markup_template('diaspora_share.tpl');
2475 $msg = replace_macros($tpl, array(
2476 '$sender' => $myaddr,
2477 '$recipient' => $theiraddr
2480 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2481 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2483 return(diaspora_transmit($owner,$contact,$slap, false));
2486 function diaspora_unshare($me,$contact) {
2489 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2491 $tpl = get_markup_template('diaspora_retract.tpl');
2492 $msg = replace_macros($tpl, array(
2493 '$guid' => $me['guid'],
2494 '$type' => 'Person',
2495 '$handle' => $myaddr
2498 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2499 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2501 return(diaspora_transmit($owner,$contact,$slap, false));
2506 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2509 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2510 $theiraddr = $contact['addr'];
2514 $title = $item['title'];
2515 $body = $item['body'];
2518 // We're trying to match Diaspora's split message/photo protocol but
2519 // all the photos are displayed on D* as links and not img's - even
2520 // though we're sending pretty much precisely what they send us when
2521 // doing the same operation.
2522 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2523 // which seems to get through intact.
2525 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2527 foreach($matches as $mtch) {
2529 $detail['str'] = $mtch[0];
2530 $detail['path'] = dirname($mtch[1]) . '/';
2531 $detail['file'] = basename($mtch[1]);
2532 $detail['guid'] = $item['guid'];
2533 $detail['handle'] = $myaddr;
2534 $images[] = $detail;
2535 $body = str_replace($detail['str'],$mtch[1],$body);
2540 //if(strlen($title))
2541 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2543 // convert to markdown
2544 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2545 //$body = bb2diaspora($body);
2549 $body = "## ".html_entity_decode($title)."\n\n".$body;
2551 if($item['attach']) {
2552 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2554 $body .= "\n" . t('Attachments:') . "\n";
2555 foreach($matches as $mtch) {
2556 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2562 $public = (($item['private']) ? 'false' : 'true');
2564 require_once('include/datetime.php');
2565 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2567 // Detect a share element and do a reshare
2568 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2569 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2570 $tpl = get_markup_template('diaspora_reshare.tpl');
2571 $msg = replace_macros($tpl, array(
2572 '$root_handle' => xmlify($ret['root_handle']),
2573 '$root_guid' => $ret['root_guid'],
2574 '$guid' => $item['guid'],
2575 '$handle' => xmlify($myaddr),
2576 '$public' => $public,
2577 '$created' => $created,
2578 '$provider' => $item["app"]
2581 $tpl = get_markup_template('diaspora_post.tpl');
2582 $msg = replace_macros($tpl, array(
2584 '$guid' => $item['guid'],
2585 '$handle' => xmlify($myaddr),
2586 '$public' => $public,
2587 '$created' => $created,
2588 '$provider' => $item["app"]
2592 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2594 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2595 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2597 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2599 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2601 if(count($images)) {
2602 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2605 return $return_code;
2608 function diaspora_is_reshare($body) {
2609 $body = trim($body);
2611 // Skip if it isn't a pure repeated messages
2612 // Does it start with a share?
2613 if (strpos($body, "[share") > 0)
2616 // Does it end with a share?
2617 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2620 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2621 // Skip if there is no shared message in there
2622 if ($body == $attributes)
2626 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2627 if ($matches[1] != "")
2628 $guid = $matches[1];
2630 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2631 if ($matches[1] != "")
2632 $guid = $matches[1];
2635 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2636 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2639 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2640 $ret["root_guid"] = $guid;
2646 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2647 if ($matches[1] != "")
2648 $profile = $matches[1];
2650 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2651 if ($matches[1] != "")
2652 $profile = $matches[1];
2656 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2657 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2661 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2662 if ($matches[1] != "")
2663 $link = $matches[1];
2665 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2666 if ($matches[1] != "")
2667 $link = $matches[1];
2669 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2670 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2676 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2678 if(! count($images))
2680 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2682 $tpl = get_markup_template('diaspora_photo.tpl');
2683 foreach($images as $image) {
2684 if(! stristr($image['path'],$mysite))
2686 $resource = str_replace('.jpg','',$image['file']);
2687 $resource = substr($resource,0,strpos($resource,'-'));
2689 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2691 intval($owner['uid'])
2695 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2696 $msg = replace_macros($tpl,array(
2697 '$path' => xmlify($image['path']),
2698 '$filename' => xmlify($image['file']),
2699 '$msg_guid' => xmlify($image['guid']),
2700 '$guid' => xmlify($r[0]['guid']),
2701 '$handle' => xmlify($image['handle']),
2702 '$public' => xmlify($public),
2703 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2707 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2708 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2709 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2711 diaspora_transmit($owner,$contact,$slap,$public_batch);
2716 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2719 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2720 // $theiraddr = $contact['addr'];
2722 // Diaspora doesn't support threaded comments, but some
2723 // versions of Diaspora (i.e. Diaspora-pistos) support
2724 // likes on comments
2725 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2726 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2727 dbesc($item['thr-parent'])
2731 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2732 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2733 // The only item with `parent` and `id` as the parent id is the parent item.
2734 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2735 intval($item['parent']),
2736 intval($item['parent'])
2744 if($item['verb'] === ACTIVITY_LIKE) {
2745 $tpl = get_markup_template('diaspora_like.tpl');
2747 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2748 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2749 // $positive = (($item['deleted']) ? 'false' : 'true');
2752 if(($item['deleted']))
2753 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2756 $tpl = get_markup_template('diaspora_comment.tpl');
2760 $text = html_entity_decode(bb2diaspora($item['body']));
2765 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2767 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2769 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2771 $msg = replace_macros($tpl,array(
2772 '$guid' => xmlify($item['guid']),
2773 '$parent_guid' => xmlify($parent['guid']),
2774 '$target_type' =>xmlify($target_type),
2775 '$authorsig' => xmlify($authorsig),
2776 '$body' => xmlify($text),
2777 '$positive' => xmlify($positive),
2778 '$handle' => xmlify($myaddr)
2781 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2783 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2784 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2786 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2790 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2794 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2795 // $theiraddr = $contact['addr'];
2797 $body = $item['body'];
2798 $text = html_entity_decode(bb2diaspora($body));
2800 // Diaspora doesn't support threaded comments, but some
2801 // versions of Diaspora (i.e. Diaspora-pistos) support
2802 // likes on comments
2803 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2804 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2805 dbesc($item['thr-parent'])
2809 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2810 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2811 // The only item with `parent` and `id` as the parent id is the parent item.
2812 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2813 intval($item['parent']),
2814 intval($item['parent'])
2823 $relay_retract = false;
2824 $sql_sign_id = 'iid';
2825 if( $item['deleted']) {
2826 $relay_retract = true;
2828 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2830 $sql_sign_id = 'retract_iid';
2831 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2833 elseif($item['verb'] === ACTIVITY_LIKE) {
2836 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2837 // $positive = (($item['deleted']) ? 'false' : 'true');
2840 $tpl = get_markup_template('diaspora_like_relay.tpl');
2842 else { // item is a comment
2843 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2847 // fetch the original signature if the relayable was created by a Diaspora
2848 // or DFRN user. Relayables for other networks are not supported.
2850 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2855 $signed_text = $orig_sign['signed_text'];
2856 $authorsig = $orig_sign['signature'];
2857 $handle = $orig_sign['signer'];
2861 // Author signature information (for likes, comments, and retractions of likes or comments,
2862 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2863 // function is called
2864 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2868 /* Since the author signature is only checked by the parent, not by the relay recipients,
2869 * I think it may not be necessary for us to do so much work to preserve all the original
2870 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2871 * Let's just generate that and forget about all the original author signature stuff.
2873 * Note: this might be more of an problem if we want to support likes on comments for older
2874 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2875 * doing that, let's ignore it for now.
2877 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2881 $handle = diaspora_handle_from_contact($item['contact-id']);
2887 $sender_signed_text = $item['guid'] . ';' . $target_type;
2889 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2891 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2893 // Sign the relayable with the top-level owner's signature
2895 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2896 // stored in the database, because that provides the best chance that Diaspora will
2897 // be able to reconstruct the signed text the same way we did. This is particularly a
2898 // concern for the comment, whose signed text includes the text of the comment. The
2899 // smallest change in the text of the comment, including removing whitespace, will
2900 // make the signature verification fail. Since we translate from BB code to Diaspora's
2901 // markup at the top of this function, which is AFTER we placed the original $signed_text
2902 // in the database, it's hazardous to trust the original $signed_text.
2904 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2906 $msg = replace_macros($tpl,array(
2907 '$guid' => xmlify($item['guid']),
2908 '$parent_guid' => xmlify($parent['guid']),
2909 '$target_type' =>xmlify($target_type),
2910 '$authorsig' => xmlify($authorsig),
2911 '$parentsig' => xmlify($parentauthorsig),
2912 '$body' => xmlify($text),
2913 '$positive' => xmlify($positive),
2914 '$handle' => xmlify($handle)
2917 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2920 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2921 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2923 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2929 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2932 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2934 // Check whether the retraction is for a top-level post or whether it's a relayable
2935 if( $item['uri'] !== $item['parent-uri'] ) {
2937 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2938 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2942 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2943 $target_type = 'StatusMessage';
2946 $signed_text = $item['guid'] . ';' . $target_type;
2948 $msg = replace_macros($tpl, array(
2949 '$guid' => xmlify($item['guid']),
2950 '$type' => xmlify($target_type),
2951 '$handle' => xmlify($myaddr),
2952 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2955 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2956 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2958 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2961 function diaspora_send_mail($item,$owner,$contact) {
2964 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2966 $r = q("select * from conv where id = %d and uid = %d limit 1",
2967 intval($item['convid']),
2968 intval($item['uid'])
2972 logger('diaspora_send_mail: conversation not found.');
2978 'guid' => xmlify($cnv['guid']),
2979 'subject' => xmlify($cnv['subject']),
2980 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2981 'diaspora_handle' => xmlify($cnv['creator']),
2982 'participant_handles' => xmlify($cnv['recips'])
2985 $body = bb2diaspora($item['body']);
2986 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2988 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2989 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2991 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2994 'guid' => xmlify($item['guid']),
2995 'parent_guid' => xmlify($cnv['guid']),
2996 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2997 'author_signature' => xmlify($sig),
2998 'text' => xmlify($body),
2999 'created_at' => xmlify($created),
3000 'diaspora_handle' => xmlify($myaddr),
3001 'conversation_guid' => xmlify($cnv['guid'])
3004 if($item['reply']) {
3005 $tpl = get_markup_template('diaspora_message.tpl');
3006 $xmsg = replace_macros($tpl, array('$msg' => $msg));
3009 $conv['messages'] = array($msg);
3010 $tpl = get_markup_template('diaspora_conversation.tpl');
3011 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3014 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3016 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3017 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3019 return(diaspora_transmit($owner,$contact,$slap,false));
3024 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
3026 $enabled = intval(get_config('system','diaspora_enabled'));
3032 $logid = random_string(4);
3033 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3035 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3039 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
3041 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3045 if (!intval(get_config('system','diaspora_test'))) {
3046 post_url($dest_url . '/', $slap);
3047 $return_code = $a->get_curl_code();
3049 logger('diaspora_transmit: test_mode');
3054 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
3056 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3057 logger('diaspora_transmit: queue message');
3059 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3060 intval($contact['id']),
3061 dbesc(NETWORK_DIASPORA),
3063 intval($public_batch)
3066 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3069 // queue message for redelivery
3070 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3075 return(($return_code) ? $return_code : (-1));