5 - GET /people/9aed8882b9f64896/stream
6 - POST /receive/users/9aed8882b9f64896/
9 require_once('include/crypto.php');
10 require_once('include/items.php');
11 require_once('include/bb2diaspora.php');
12 require_once('include/contact_selectors.php');
13 require_once('include/queue_fn.php');
14 require_once('include/lock.php');
15 require_once('include/threads.php');
16 require_once('mod/share.php');
18 function diaspora_dispatch_public($msg) {
20 $enabled = intval(get_config('system','diaspora_enabled'));
22 logger('mod-diaspora: disabled');
26 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
27 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
28 AND `account_expired` = 0 AND `account_removed` = 0 ",
29 dbesc(NETWORK_DIASPORA),
34 logger('diaspora_public: delivering to: ' . $rr['username']);
35 diaspora_dispatch($rr,$msg);
39 logger('diaspora_public: no subscribers');
44 function diaspora_dispatch($importer,$msg,$attempt=1) {
48 $enabled = intval(get_config('system','diaspora_enabled'));
50 logger('mod-diaspora: disabled');
54 // php doesn't like dashes in variable names
56 $msg['message'] = str_replace(
57 array('<activity_streams-photo>','</activity_streams-photo>'),
58 array('<asphoto>','</asphoto>'),
62 $parsed_xml = parse_xml_string($msg['message'],false);
64 $xmlbase = $parsed_xml->post;
66 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
69 if($xmlbase->request) {
70 $ret = diaspora_request($importer,$xmlbase->request);
72 elseif($xmlbase->status_message) {
73 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
75 elseif($xmlbase->profile) {
76 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
78 elseif($xmlbase->comment) {
79 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
81 elseif($xmlbase->like) {
82 $ret = diaspora_like($importer,$xmlbase->like,$msg);
84 elseif($xmlbase->asphoto) {
85 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
87 elseif($xmlbase->reshare) {
88 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
90 elseif($xmlbase->retraction) {
91 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
93 elseif($xmlbase->signed_retraction) {
94 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
96 elseif($xmlbase->relayable_retraction) {
97 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
99 elseif($xmlbase->photo) {
100 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
102 elseif($xmlbase->conversation) {
103 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
105 elseif($xmlbase->message) {
106 $ret = diaspora_message($importer,$xmlbase->message,$msg);
109 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
114 function diaspora_handle_from_contact($contact_id) {
117 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
119 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
125 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
127 if($contact['network'] === NETWORK_DIASPORA) {
128 $handle = $contact['addr'];
130 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
132 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
133 $baseurl_start = strpos($contact['url'],'://') + 3;
134 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
135 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
136 $handle = $contact['nick'] . '@' . $baseurl;
138 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
145 function diaspora_get_contact_by_handle($uid,$handle) {
146 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
147 dbesc(NETWORK_DIASPORA),
154 $handle_parts = explode("@", $handle);
155 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
156 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
167 function find_diaspora_person_by_handle($handle) {
177 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
178 dbesc(NETWORK_DIASPORA),
183 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
185 // update record occasionally so it doesn't get stale
186 $d = strtotime($person['updated'] . ' +00:00');
187 if($d < strtotime('now - 14 days'))
192 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
194 // If the person isn't in our 'fcontact' table, or if he/she is but
195 // his/her information hasn't been updated for more than 14 days, then
196 // we want to fetch the person's information from the remote server.
198 // Note that $person isn't changed by this block of code unless the
199 // person's information has been successfully fetched from the remote
200 // server. So if $person was 'false' to begin with (because he/she wasn't
201 // in the local cache), it'll stay false, and if $person held the local
202 // cache information to begin with, it'll keep that information. That way
203 // if there's a problem with the remote fetch, we can at least use our
204 // cached information--it's better than nothing.
206 if((! $person) || ($update)) {
207 // Lock the function to prevent race conditions if multiple items
208 // come in at the same time from a person who doesn't exist in
211 // Don't loop forever. On the last loop, try to create the contact
212 // whether the function is locked or not. Maybe the locking thread
213 // has died or something. At any rate, a duplicate in 'fcontact'
214 // is a much smaller problem than a deadlocked thread
215 $got_lock = lock_function('find_diaspora_person_by_handle', false);
216 if(($endlessloop + 1) >= $maxloops)
220 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
221 require_once('include/Scrape.php');
222 $r = probe_url($handle, PROBE_DIASPORA);
224 // Note that Friendica contacts can return a "Diaspora person"
225 // if Diaspora connectivity is enabled on their server
226 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
227 add_fcontact($r,$update);
231 unlock_function('find_diaspora_person_by_handle');
234 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
236 block_on_function_lock('find_diaspora_person_by_handle');
239 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
240 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
241 // The fact that the function was locked may mean that another process was creating the
242 // person's record. It could also mean another process was creating or updating an unrelated
245 // At any rate, we need to keep trying until we've either got the person or had a chance to
246 // try to fetch his/her remote information. But we don't want to block on locking the
247 // function, because if the other process is creating the record, then when we acquire the lock
248 // we'll dive right into creating another, duplicate record. We DO want to at least wait
249 // until the lock is released, so we don't flood the database with requests.
251 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
252 // we do have some information for the person
258 function get_diaspora_key($uri) {
259 logger('Fetching diaspora key for: ' . $uri);
261 $r = find_diaspora_person_by_handle($uri);
268 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
271 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
274 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
276 // $b64_data = base64_encode($msg);
277 // $b64url_data = base64url_encode($b64_data);
279 $b64url_data = base64url_encode($msg);
281 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
283 $type = 'application/xml';
284 $encoding = 'base64url';
287 $signable_data = $data . '.' . base64url_encode($type) . '.'
288 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
290 $signature = rsa_sign($signable_data,$prvkey);
291 $sig = base64url_encode($signature);
294 <?xml version='1.0' encoding='UTF-8'?>
295 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
297 <author_id>$handle</author_id>
300 <me:encoding>base64url</me:encoding>
301 <me:alg>RSA-SHA256</me:alg>
302 <me:data type="application/xml">$data</me:data>
303 <me:sig>$sig</me:sig>
308 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
316 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
320 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
322 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
324 // without a public key nothing will work
327 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
331 $inner_aes_key = random_string(32);
332 $b_inner_aes_key = base64_encode($inner_aes_key);
333 $inner_iv = random_string(16);
334 $b_inner_iv = base64_encode($inner_iv);
336 $outer_aes_key = random_string(32);
337 $b_outer_aes_key = base64_encode($outer_aes_key);
338 $outer_iv = random_string(16);
339 $b_outer_iv = base64_encode($outer_iv);
341 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
343 $padded_data = pkcs5_pad($msg,16);
344 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
346 $b64_data = base64_encode($inner_encrypted);
349 $b64url_data = base64url_encode($b64_data);
350 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
352 $type = 'application/xml';
353 $encoding = 'base64url';
356 $signable_data = $data . '.' . base64url_encode($type) . '.'
357 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
359 $signature = rsa_sign($signable_data,$prvkey);
360 $sig = base64url_encode($signature);
362 $decrypted_header = <<< EOT
365 <aes_key>$b_inner_aes_key</aes_key>
366 <author_id>$handle</author_id>
370 $decrypted_header = pkcs5_pad($decrypted_header,16);
372 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
374 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
376 $encrypted_outer_key_bundle = '';
377 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
379 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
381 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
383 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
384 'ciphertext' => base64_encode($ciphertext)));
385 $cipher_json = base64_encode($encrypted_header_json_object);
387 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
390 <?xml version='1.0' encoding='UTF-8'?>
391 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
394 <me:encoding>base64url</me:encoding>
395 <me:alg>RSA-SHA256</me:alg>
396 <me:data type="application/xml">$data</me:data>
397 <me:sig>$sig</me:sig>
402 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
409 * diaspora_decode($importer,$xml)
410 * array $importer -> from user table
411 * string $xml -> urldecoded Diaspora salmon
414 * 'message' -> decoded Diaspora XML message
415 * 'author' -> author diaspora handle
416 * 'key' -> author public key (converted to pkcs#8)
418 * Author and key are used elsewhere to save a lookup for verifying replies and likes
422 function diaspora_decode($importer,$xml) {
425 $basedom = parse_xml_string($xml);
427 $children = $basedom->children('https://joindiaspora.com/protocol');
429 if($children->header) {
431 $author_link = str_replace('acct:','',$children->header->author_id);
435 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
437 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
438 $ciphertext = base64_decode($encrypted_header->ciphertext);
440 $outer_key_bundle = '';
441 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
443 $j_outer_key_bundle = json_decode($outer_key_bundle);
445 $outer_iv = base64_decode($j_outer_key_bundle->iv);
446 $outer_key = base64_decode($j_outer_key_bundle->key);
448 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
451 $decrypted = pkcs5_unpad($decrypted);
454 * $decrypted now contains something like
457 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
458 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
463 * <name>Ryan Hughes</name>
464 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
469 * <author_id>galaxor@diaspora.priateship.org</author_id>
473 * </decrypted_header>
476 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
477 $idom = parse_xml_string($decrypted,false);
479 $inner_iv = base64_decode($idom->iv);
480 $inner_aes_key = base64_decode($idom->aes_key);
482 $author_link = str_replace('acct:','',$idom->author_id);
486 $dom = $basedom->children(NAMESPACE_SALMON_ME);
488 // figure out where in the DOM tree our data is hiding
490 if($dom->provenance->data)
491 $base = $dom->provenance;
492 elseif($dom->env->data)
498 logger('mod-diaspora: unable to locate salmon data in xml ');
499 http_status_exit(400);
503 // Stash the signature away for now. We have to find their key or it won't be good for anything.
504 $signature = base64url_decode($base->sig);
508 // strip whitespace so our data element will return to one big base64 blob
509 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
512 // stash away some other stuff for later
514 $type = $base->data[0]->attributes()->type[0];
515 $keyhash = $base->sig[0]->attributes()->keyhash[0];
516 $encoding = $base->encoding;
520 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
524 $data = base64url_decode($data);
528 $inner_decrypted = $data;
532 // Decode the encrypted blob
534 $inner_encrypted = base64_decode($data);
535 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
536 $inner_decrypted = pkcs5_unpad($inner_decrypted);
540 logger('mod-diaspora: Could not retrieve author URI.');
541 http_status_exit(400);
544 // Once we have the author URI, go to the web and try to find their public key
545 // (first this will look it up locally if it is in the fcontact cache)
546 // This will also convert diaspora public key from pkcs#1 to pkcs#8
548 logger('mod-diaspora: Fetching key for ' . $author_link );
549 $key = get_diaspora_key($author_link);
552 logger('mod-diaspora: Could not retrieve author key.');
553 http_status_exit(400);
556 $verify = rsa_verify($signed_data,$signature,$key);
559 logger('mod-diaspora: Message did not verify. Discarding.');
560 http_status_exit(400);
563 logger('mod-diaspora: Message verified.');
565 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
570 function diaspora_request($importer,$xml) {
574 $sender_handle = unxmlify($xml->sender_handle);
575 $recipient_handle = unxmlify($xml->recipient_handle);
577 if(! $sender_handle || ! $recipient_handle)
580 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
584 // perhaps we were already sharing with this person. Now they're sharing with us.
585 // That makes us friends.
587 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
588 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
589 intval(CONTACT_IS_FRIEND),
590 intval($contact['id']),
591 intval($importer['uid'])
596 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
597 intval($importer['uid'])
600 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
601 require_once('include/items.php');
603 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
604 intval($importer['uid'])
607 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
609 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
612 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
613 $arr['uid'] = $importer['uid'];
614 $arr['contact-id'] = $self[0]['id'];
616 $arr['type'] = 'wall';
619 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
620 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
621 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
622 $arr['verb'] = ACTIVITY_FRIEND;
623 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
625 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
626 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
627 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
628 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
630 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
631 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
632 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
633 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
634 $arr['object'] .= '</link></object>' . "\n";
635 $arr['last-child'] = 1;
637 $arr['allow_cid'] = $user[0]['allow_cid'];
638 $arr['allow_gid'] = $user[0]['allow_gid'];
639 $arr['deny_cid'] = $user[0]['deny_cid'];
640 $arr['deny_gid'] = $user[0]['deny_gid'];
642 $i = item_store($arr);
644 proc_run('php',"include/notifier.php","activity","$i");
653 $ret = find_diaspora_person_by_handle($sender_handle);
656 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
657 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
661 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
665 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
666 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
667 intval($importer['uid']),
668 dbesc($ret['network']),
672 dbesc(normalise_link($ret['url'])),
676 dbesc($ret['photo']),
677 dbesc($ret['pubkey']),
678 dbesc($ret['notify']),
684 // find the contact record we just created
686 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
688 if(! $contact_record) {
689 logger('diaspora_request: unable to locate newly created contact record.');
693 $g = q("select def_gid from user where uid = %d limit 1",
694 intval($importer['uid'])
696 if($g && intval($g[0]['def_gid'])) {
697 require_once('include/group.php');
698 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
701 if($importer['page-flags'] == PAGE_NORMAL) {
703 $hash = random_string() . (string) time(); // Generate a confirm_key
705 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
706 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
707 intval($importer['uid']),
708 intval($contact_record['id']),
711 dbesc( t('Sharing notification from Diaspora network')),
713 dbesc(datetime_convert())
718 // automatic friend approval
720 require_once('include/Photo.php');
722 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
724 // technically they are sharing with us (CONTACT_IS_SHARING),
725 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
726 // we are going to change the relationship and make them a follower.
728 if($importer['page-flags'] == PAGE_FREELOVE)
729 $new_relation = CONTACT_IS_FRIEND;
731 $new_relation = CONTACT_IS_FOLLOWER;
733 $r = q("UPDATE `contact` SET
740 `avatar-date` = '%s',
749 intval($new_relation),
750 dbesc(datetime_convert()),
751 dbesc(datetime_convert()),
752 dbesc(datetime_convert()),
753 intval($contact_record['id'])
756 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
758 $ret = diaspora_share($u[0],$contact_record);
764 function diaspora_post_allow($importer,$contact) {
766 // perhaps we were already sharing with this person. Now they're sharing with us.
767 // That makes us friends.
768 // Normally this should have handled by getting a request - but this could get lost
769 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
770 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
771 intval(CONTACT_IS_FRIEND),
772 intval($contact['id']),
773 intval($importer['uid'])
775 $contact['rel'] = CONTACT_IS_FRIEND;
776 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
779 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
781 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
783 if($contact['rel'] == CONTACT_IS_FOLLOWER)
784 if($importer['page-flags'] == PAGE_COMMUNITY)
789 function diaspora_is_redmatrix($url) {
790 return(strstr($url, "/channel/"));
793 function diaspora_plink($addr, $guid) {
794 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", $addr);
798 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
800 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
801 // So we try another way as well.
802 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
804 $r[0]["network"] = $s[0]["network"];
806 if ($r[0]["network"] == NETWORK_DFRN)
807 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
809 if (diaspora_is_redmatrix($r[0]["url"]))
810 return $r[0]["url"]."/?f=&mid=".$guid;
812 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
815 function diaspora_post($importer,$xml,$msg) {
818 $guid = notags(unxmlify($xml->guid));
819 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
821 if($diaspora_handle != $msg['author']) {
822 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
826 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
830 if(! diaspora_post_allow($importer,$contact)) {
831 logger('diaspora_post: Ignoring this author.');
835 $message_id = $diaspora_handle . ':' . $guid;
836 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
837 intval($importer['uid']),
842 logger('diaspora_post: message exists: ' . $guid);
846 $created = unxmlify($xml->created_at);
847 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
849 $body = diaspora2bb($xml->raw_message);
853 $datarray["object"] = json_encode($xml);
855 if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
856 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
858 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
859 // Add OEmbed and other information to the body
860 if (!diaspora_is_redmatrix($contact['url']))
861 $body = add_page_info_to_body($body, false, true);
866 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
868 foreach($matches as $mtch) {
869 if(strlen($str_tags))
871 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
875 $plink = diaspora_plink($diaspora_handle, $guid);
877 $datarray['uid'] = $importer['uid'];
878 $datarray['contact-id'] = $contact['id'];
879 $datarray['wall'] = 0;
880 $datarray['network'] = NETWORK_DIASPORA;
881 $datarray['verb'] = ACTIVITY_POST;
882 $datarray['guid'] = $guid;
883 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
884 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
885 $datarray['private'] = $private;
886 $datarray['parent'] = 0;
887 $datarray['plink'] = $plink;
888 $datarray['owner-name'] = $contact['name'];
889 $datarray['owner-link'] = $contact['url'];
890 //$datarray['owner-avatar'] = $contact['thumb'];
891 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
892 $datarray['author-name'] = $contact['name'];
893 $datarray['author-link'] = $contact['url'];
894 $datarray['author-avatar'] = $contact['thumb'];
895 $datarray['body'] = $body;
896 $datarray['tag'] = $str_tags;
897 if ($xml->provider_display_name)
898 $datarray["app"] = unxmlify($xml->provider_display_name);
900 $datarray['app'] = 'Diaspora';
902 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
904 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
906 DiasporaFetchGuid($datarray);
907 $message_id = item_store($datarray);
913 function DiasporaFetchGuid($item) {
914 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
915 function ($match) use ($item){
916 return(DiasporaFetchGuidSub($match, $item));
920 function DiasporaFetchGuidSub($match, $item) {
923 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
924 diaspora_store_by_guid($match[1], $item["owner-link"]);
927 function diaspora_store_by_guid($guid, $server, $uid = 0) {
928 require_once("include/Contact.php");
930 $serverparts = parse_url($server);
931 $server = $serverparts["scheme"]."://".$serverparts["host"];
933 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
935 $item = diaspora_fetch_message($guid, $server);
940 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
942 $body = $item["body"];
943 $str_tags = $item["tag"];
945 $created = $item["created"];
946 $author = $item["author"];
947 $guid = $item["guid"];
948 $private = $item["private"];
949 $object = $item["object"];
950 $objecttype = $item["object-type"];
952 $message_id = $author.':'.$guid;
953 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
961 $person = find_diaspora_person_by_handle($author);
964 $datarray['uid'] = $uid;
965 $datarray['contact-id'] = get_contact($person['url'], $uid);
966 $datarray['wall'] = 0;
967 $datarray['network'] = NETWORK_DIASPORA;
968 $datarray['guid'] = $guid;
969 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
970 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
971 $datarray['private'] = $private;
972 $datarray['parent'] = 0;
973 $datarray['plink'] = diaspora_plink($author, $guid);
974 $datarray['author-name'] = $person['name'];
975 $datarray['author-link'] = $person['url'];
976 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
977 $datarray['owner-name'] = $datarray['author-name'];
978 $datarray['owner-link'] = $datarray['author-link'];
979 $datarray['owner-avatar'] = $datarray['author-avatar'];
980 $datarray['body'] = $body;
981 $datarray['tag'] = $str_tags;
982 $datarray['app'] = $app;
983 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
984 $datarray['object'] = $object;
985 $datarray['object-type'] = $objecttype;
987 if ($datarray['contact-id'] == 0)
990 DiasporaFetchGuid($datarray);
991 $message_id = item_store($datarray);
994 // Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
999 function diaspora_fetch_message($guid, $server, $level = 0) {
1006 // This will not work if the server is not a Diaspora server
1007 $source_url = $server.'/p/'.$guid.'.xml';
1008 $x = fetch_url($source_url);
1012 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1013 $source_xml = parse_xml_string($x,false);
1016 $item["app"] = 'Diaspora';
1017 $item["guid"] = $guid;
1020 if ($source_xml->post->status_message->created_at)
1021 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1023 if ($source_xml->post->status_message->provider_display_name)
1024 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1026 if ($source_xml->post->status_message->diaspora_handle)
1027 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1029 if ($source_xml->post->status_message->guid)
1030 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1032 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1033 $item["object"] = json_encode($source_xml->post);
1035 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1036 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1037 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1038 $body = scale_external_images($body,false);
1039 } elseif($source_xml->post->asphoto->image_url) {
1040 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1041 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1042 $body = scale_external_images($body);
1043 } elseif($source_xml->post->status_message) {
1044 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1046 // Checking for embedded pictures
1047 if($source_xml->post->status_message->photo->remote_photo_path AND
1048 $source_xml->post->status_message->photo->remote_photo_name) {
1050 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1052 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1053 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1055 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1057 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1059 $item["object-type"] = ACTIVITY_OBJ_NOTE;
1061 $body = scale_external_images($body);
1063 // Add OEmbed and other information to the body
1064 // To-Do: It could be a repeated redmatrix item
1065 // Then we shouldn't add further data to it
1066 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1067 $body = add_page_info_to_body($body, false, true);
1069 } elseif($source_xml->post->reshare) {
1070 // Reshare of a reshare
1071 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1073 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1074 logger('no content found: '.print_r($source_xml,true));
1078 if (trim($body) == "")
1082 $item["body"] = $body;
1087 function diaspora_reshare($importer,$xml,$msg) {
1089 logger('diaspora_reshare: init: ' . print_r($xml,true));
1092 $guid = notags(unxmlify($xml->guid));
1093 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1096 if($diaspora_handle != $msg['author']) {
1097 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1101 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1105 if(! diaspora_post_allow($importer,$contact)) {
1106 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1110 $message_id = $diaspora_handle . ':' . $guid;
1111 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1112 intval($importer['uid']),
1117 logger('diaspora_reshare: message exists: ' . $guid);
1121 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1122 $orig_guid = notags(unxmlify($xml->root_guid));
1123 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1125 $create_original_post = false;
1127 // Do we already have this item?
1128 $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",
1130 dbesc(NETWORK_DIASPORA)
1133 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1135 // Maybe it is already a reshared item?
1136 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1137 require_once('include/api.php');
1138 if (api_share_as_retweet($r[0]))
1141 $body = $r[0]["body"];
1142 $str_tags = $r[0]["tag"];
1143 $app = $r[0]["app"];
1144 $orig_created = $r[0]["created"];
1145 $orig_plink = $r[0]["plink"];
1146 $orig_uri = $r[0]["uri"];
1147 $object = $r[0]["object"];
1148 $objecttype = $r[0]["object-type"];
1157 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1158 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1159 $item = diaspora_fetch_message($orig_guid, $server);
1162 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1163 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1164 $item = diaspora_fetch_message($orig_guid, $server);
1167 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1168 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1169 $item = diaspora_fetch_message($orig_guid, $server);
1172 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1173 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1174 $item = diaspora_fetch_message($orig_guid, $server);
1178 $body = $item["body"];
1179 $str_tags = $item["tag"];
1180 $app = $item["app"];
1181 $orig_created = $item["created"];
1182 $orig_author = $item["author"];
1183 $orig_guid = $item["guid"];
1184 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1185 $orig_uri = $orig_author.':'.$orig_guid;
1186 $create_original_post = ($body != "");
1187 $object = $item["object"];
1188 $objecttype = $item["object-type"];
1192 $plink = diaspora_plink($diaspora_handle, $guid);
1194 $person = find_diaspora_person_by_handle($orig_author);
1196 $created = unxmlify($xml->created_at);
1197 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1199 $datarray = array();
1201 $datarray['uid'] = $importer['uid'];
1202 $datarray['contact-id'] = $contact['id'];
1203 $datarray['wall'] = 0;
1204 $datarray['network'] = NETWORK_DIASPORA;
1205 $datarray['guid'] = $guid;
1206 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1207 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1208 $datarray['private'] = $private;
1209 $datarray['parent'] = 0;
1210 $datarray['plink'] = $plink;
1211 $datarray['owner-name'] = $contact['name'];
1212 $datarray['owner-link'] = $contact['url'];
1213 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1214 if (!intval(get_config('system','wall-to-wall_share'))) {
1215 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1217 $datarray['author-name'] = $contact['name'];
1218 $datarray['author-link'] = $contact['url'];
1219 $datarray['author-avatar'] = $contact['thumb'];
1220 $datarray['body'] = $prefix.$body."[/share]";
1222 // Let reshared messages look like wall-to-wall posts
1223 $datarray['author-name'] = $person['name'];
1224 $datarray['author-link'] = $person['url'];
1225 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1226 $datarray['body'] = $body;
1229 $datarray["object"] = json_encode($xml);
1230 $datarray['object-type'] = $objecttype;
1232 $datarray['tag'] = $str_tags;
1233 $datarray['app'] = $app;
1235 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1236 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1238 // Store the original item of a reshare
1239 if ($create_original_post) {
1240 require_once("include/Contact.php");
1242 $datarray2 = $datarray;
1244 $datarray2['uid'] = 0;
1245 $datarray2['contact-id'] = get_contact($person['url'], 0);
1246 $datarray2['guid'] = $orig_guid;
1247 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1248 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1249 $datarray2['parent'] = 0;
1250 $datarray2['plink'] = $orig_plink;
1252 $datarray2['author-name'] = $person['name'];
1253 $datarray2['author-link'] = $person['url'];
1254 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1255 $datarray2['owner-name'] = $datarray2['author-name'];
1256 $datarray2['owner-link'] = $datarray2['author-link'];
1257 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1258 $datarray2['body'] = $body;
1259 $datarray2["object"] = $object;
1261 DiasporaFetchGuid($datarray2);
1262 $message_id = item_store($datarray2);
1264 logger("Store original item ".$orig_guid." under message id ".$message_id);
1267 DiasporaFetchGuid($datarray);
1268 $message_id = item_store($datarray);
1275 function diaspora_asphoto($importer,$xml,$msg) {
1276 logger('diaspora_asphoto called');
1279 $guid = notags(unxmlify($xml->guid));
1280 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1282 if($diaspora_handle != $msg['author']) {
1283 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1287 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1291 if(! diaspora_post_allow($importer,$contact)) {
1292 logger('diaspora_asphoto: Ignoring this author.');
1296 $message_id = $diaspora_handle . ':' . $guid;
1297 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1298 intval($importer['uid']),
1303 logger('diaspora_asphoto: message exists: ' . $guid);
1307 $created = unxmlify($xml->created_at);
1308 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1310 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1311 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1312 $body = scale_external_images($body,false);
1314 elseif($xml->image_url) {
1315 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1316 $body = scale_external_images($body);
1319 logger('diaspora_asphoto: no photo url found.');
1323 $plink = diaspora_plink($diaspora_handle, $guid);
1325 $datarray = array();
1327 $datarray['uid'] = $importer['uid'];
1328 $datarray['contact-id'] = $contact['id'];
1329 $datarray['wall'] = 0;
1330 $datarray['network'] = NETWORK_DIASPORA;
1331 $datarray['guid'] = $guid;
1332 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1333 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1334 $datarray['private'] = $private;
1335 $datarray['parent'] = 0;
1336 $datarray['plink'] = $plink;
1337 $datarray['owner-name'] = $contact['name'];
1338 $datarray['owner-link'] = $contact['url'];
1339 //$datarray['owner-avatar'] = $contact['thumb'];
1340 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1341 $datarray['author-name'] = $contact['name'];
1342 $datarray['author-link'] = $contact['url'];
1343 $datarray['author-avatar'] = $contact['thumb'];
1344 $datarray['body'] = $body;
1345 $datarray["object"] = json_encode($xml);
1346 $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1348 $datarray['app'] = 'Diaspora/Cubbi.es';
1350 DiasporaFetchGuid($datarray);
1351 $message_id = item_store($datarray);
1354 // q("update item set plink = '%s' where id = %d",
1355 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1356 // intval($message_id)
1369 function diaspora_comment($importer,$xml,$msg) {
1372 $guid = notags(unxmlify($xml->guid));
1373 $parent_guid = notags(unxmlify($xml->parent_guid));
1374 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1375 $target_type = notags(unxmlify($xml->target_type));
1376 $text = unxmlify($xml->text);
1377 $author_signature = notags(unxmlify($xml->author_signature));
1379 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1381 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1383 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1387 if(! diaspora_post_allow($importer,$contact)) {
1388 logger('diaspora_comment: Ignoring this author.');
1392 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1393 intval($importer['uid']),
1397 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1401 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1402 intval($importer['uid']),
1407 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1410 $person = find_diaspora_person_by_handle($diaspora_handle);
1411 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1415 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1417 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1418 intval($importer['uid']),
1425 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1428 $parent_item = $r[0];
1431 /* How Diaspora performs comment signature checking:
1433 - If an item has been sent by the comment author to the top-level post owner to relay on
1434 to the rest of the contacts on the top-level post, the top-level post owner should check
1435 the author_signature, then create a parent_author_signature before relaying the comment on
1436 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1437 check only the parent_author_signature. Basically, they trust that the top-level post
1438 owner has already verified the authenticity of anything he/she sends out
1439 - In either case, the signature that get checked is the signature created by the person
1443 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1446 if($parent_author_signature) {
1447 // If a parent_author_signature exists, then we've received the comment
1448 // relayed from the top-level post owner. There's no need to check the
1449 // author_signature if the parent_author_signature is valid
1451 $parent_author_signature = base64_decode($parent_author_signature);
1453 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1454 logger('diaspora_comment: top-level owner verification failed.');
1459 // If there's no parent_author_signature, then we've received the comment
1460 // from the comment creator. In that case, the person is commenting on
1461 // our post, so he/she must be a contact of ours and his/her public key
1462 // should be in $msg['key']
1464 $author_signature = base64_decode($author_signature);
1466 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1467 logger('diaspora_comment: comment author verification failed.');
1472 // Phew! Everything checks out. Now create an item.
1474 // Find the original comment author information.
1475 // We need this to make sure we display the comment author
1476 // information (name and avatar) correctly.
1477 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1480 $person = find_diaspora_person_by_handle($diaspora_handle);
1482 if(! is_array($person)) {
1483 logger('diaspora_comment: unable to find author details');
1488 $body = diaspora2bb($text);
1489 $message_id = $diaspora_handle . ':' . $guid;
1491 $datarray = array();
1493 $datarray['uid'] = $importer['uid'];
1494 $datarray['contact-id'] = $contact['id'];
1495 $datarray['type'] = 'remote-comment';
1496 $datarray['wall'] = $parent_item['wall'];
1497 $datarray['network'] = NETWORK_DIASPORA;
1498 $datarray['verb'] = ACTIVITY_POST;
1499 $datarray['gravity'] = GRAVITY_COMMENT;
1500 $datarray['guid'] = $guid;
1501 $datarray['uri'] = $message_id;
1502 $datarray['parent-uri'] = $parent_item['uri'];
1504 // No timestamps for comments? OK, we'll the use current time.
1505 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1506 $datarray['private'] = $parent_item['private'];
1508 $datarray['owner-name'] = $parent_item['owner-name'];
1509 $datarray['owner-link'] = $parent_item['owner-link'];
1510 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1512 $datarray['author-name'] = $person['name'];
1513 $datarray['author-link'] = $person['url'];
1514 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1515 $datarray['body'] = $body;
1516 $datarray["object"] = json_encode($xml);
1517 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1519 // We can't be certain what the original app is if the message is relayed.
1520 if(($parent_item['origin']) && (! $parent_author_signature))
1521 $datarray['app'] = 'Diaspora';
1523 DiasporaFetchGuid($datarray);
1524 $message_id = item_store($datarray);
1526 $datarray['id'] = $message_id;
1529 //q("update item set plink = '%s' where id = %d",
1530 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1531 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1532 // intval($message_id)
1536 if(($parent_item['origin']) && (! $parent_author_signature)) {
1537 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1538 intval($message_id),
1539 dbesc($signed_data),
1540 dbesc(base64_encode($author_signature)),
1541 dbesc($diaspora_handle)
1544 // if the message isn't already being relayed, notify others
1545 // the existence of parent_author_signature means the parent_author or owner
1546 // is already relaying.
1548 proc_run('php','include/notifier.php','comment-import',$message_id);
1551 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1552 dbesc($parent_item['uri']),
1553 intval($importer['uid'])
1556 if(count($myconv)) {
1557 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1559 foreach($myconv as $conv) {
1561 // now if we find a match, it means we're in this conversation
1563 if(! link_compare($conv['author-link'],$importer_url))
1566 require_once('include/enotify.php');
1568 $conv_parent = $conv['parent'];
1571 'type' => NOTIFY_COMMENT,
1572 'notify_flags' => $importer['notify-flags'],
1573 'language' => $importer['language'],
1574 'to_name' => $importer['username'],
1575 'to_email' => $importer['email'],
1576 'uid' => $importer['uid'],
1577 'item' => $datarray,
1578 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1579 'source_name' => $datarray['author-name'],
1580 'source_link' => $datarray['author-link'],
1581 'source_photo' => $datarray['author-avatar'],
1582 'verb' => ACTIVITY_POST,
1584 'parent' => $conv_parent,
1585 'parent_uri' => $parent_uri
1588 // only send one notification
1598 function diaspora_conversation($importer,$xml,$msg) {
1602 $guid = notags(unxmlify($xml->guid));
1603 $subject = notags(unxmlify($xml->subject));
1604 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1605 $participant_handles = notags(unxmlify($xml->participant_handles));
1606 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1608 $parent_uri = $diaspora_handle . ':' . $guid;
1610 $messages = $xml->message;
1612 if(! count($messages)) {
1613 logger('diaspora_conversation: empty conversation');
1617 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1619 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1623 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1624 logger('diaspora_conversation: Ignoring this author.');
1628 $conversation = null;
1630 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1631 intval($importer['uid']),
1635 $conversation = $c[0];
1637 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1638 intval($importer['uid']),
1640 dbesc($diaspora_handle),
1641 dbesc(datetime_convert('UTC','UTC',$created_at)),
1642 dbesc(datetime_convert()),
1644 dbesc($participant_handles)
1647 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1648 intval($importer['uid']),
1652 $conversation = $c[0];
1654 if(! $conversation) {
1655 logger('diaspora_conversation: unable to create conversation.');
1659 foreach($messages as $mesg) {
1663 $msg_guid = notags(unxmlify($mesg->guid));
1664 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1665 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1666 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1667 $msg_text = unxmlify($mesg->text);
1668 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1669 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1670 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1671 if($msg_conversation_guid != $guid) {
1672 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1676 $body = diaspora2bb($msg_text);
1677 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1679 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1681 $author_signature = base64_decode($msg_author_signature);
1683 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1688 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1690 if(is_array($person) && x($person,'pubkey'))
1691 $key = $person['pubkey'];
1693 logger('diaspora_conversation: unable to find author details');
1698 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1699 logger('diaspora_conversation: verification failed.');
1703 if($msg_parent_author_signature) {
1704 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1706 $parent_author_signature = base64_decode($msg_parent_author_signature);
1710 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1711 logger('diaspora_conversation: owner verification failed.');
1716 $r = q("select id from mail where `uri` = '%s' limit 1",
1720 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1724 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')",
1725 intval($importer['uid']),
1727 intval($conversation['id']),
1728 dbesc($person['name']),
1729 dbesc($person['photo']),
1730 dbesc($person['url']),
1731 intval($contact['id']),
1738 dbesc($msg_created_at)
1741 q("update conv set updated = '%s' where id = %d",
1742 dbesc(datetime_convert()),
1743 intval($conversation['id'])
1746 require_once('include/enotify.php');
1748 'type' => NOTIFY_MAIL,
1749 'notify_flags' => $importer['notify-flags'],
1750 'language' => $importer['language'],
1751 'to_name' => $importer['username'],
1752 'to_email' => $importer['email'],
1753 'uid' =>$importer['uid'],
1754 'item' => array('subject' => $subject, 'body' => $body),
1755 'source_name' => $person['name'],
1756 'source_link' => $person['url'],
1757 'source_photo' => $person['thumb'],
1758 'verb' => ACTIVITY_POST,
1766 function diaspora_message($importer,$xml,$msg) {
1770 $msg_guid = notags(unxmlify($xml->guid));
1771 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1772 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1773 $msg_author_signature = notags(unxmlify($xml->author_signature));
1774 $msg_text = unxmlify($xml->text);
1775 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1776 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1777 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1779 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1781 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1783 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1787 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1788 logger('diaspora_message: Ignoring this author.');
1792 $conversation = null;
1794 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1795 intval($importer['uid']),
1796 dbesc($msg_conversation_guid)
1799 $conversation = $c[0];
1801 logger('diaspora_message: conversation not available.');
1807 $body = diaspora2bb($msg_text);
1808 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1810 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1813 $author_signature = base64_decode($msg_author_signature);
1815 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1816 if(is_array($person) && x($person,'pubkey'))
1817 $key = $person['pubkey'];
1819 logger('diaspora_message: unable to find author details');
1823 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1824 logger('diaspora_message: verification failed.');
1828 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1830 intval($importer['uid'])
1833 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1837 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1838 intval($importer['uid']),
1840 intval($conversation['id']),
1841 dbesc($person['name']),
1842 dbesc($person['photo']),
1843 dbesc($person['url']),
1844 intval($contact['id']),
1845 dbesc($conversation['subject']),
1851 dbesc($msg_created_at)
1854 q("update conv set updated = '%s' where id = %d",
1855 dbesc(datetime_convert()),
1856 intval($conversation['id'])
1863 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1867 logger('diaspora_photo: init',LOGGER_DEBUG);
1869 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1871 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1873 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1875 $guid = notags(unxmlify($xml->guid));
1877 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1879 $public = notags(unxmlify($xml->public));
1881 $created_at = notags(unxmlify($xml_created_at));
1883 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1885 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1887 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1891 if(! diaspora_post_allow($importer,$contact)) {
1892 logger('diaspora_photo: Ignoring this author.');
1896 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1897 intval($importer['uid']),
1898 dbesc($status_message_guid)
1901 /* deactivated by now since it can lead to multiplicated pictures in posts.
1903 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1906 $person = find_diaspora_person_by_handle($diaspora_handle);
1907 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1911 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1913 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1914 intval($importer['uid']),
1915 dbesc($status_message_guid)
1922 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1923 intval($importer['uid']),
1924 dbesc(serialize($msg)),
1925 intval($attempt + 1)
1929 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1933 $parent_item = $r[0];
1935 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1937 $link_text = scale_external_images($link_text, true,
1938 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1940 if(strpos($parent_item['body'],$link_text) === false) {
1941 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1942 dbesc($link_text . $parent_item['body']),
1943 intval($parent_item['id']),
1944 intval($parent_item['uid'])
1946 update_thread($parent_item['id']);
1955 function diaspora_like($importer,$xml,$msg) {
1958 $guid = notags(unxmlify($xml->guid));
1959 $parent_guid = notags(unxmlify($xml->parent_guid));
1960 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1961 $target_type = notags(unxmlify($xml->target_type));
1962 $positive = notags(unxmlify($xml->positive));
1963 $author_signature = notags(unxmlify($xml->author_signature));
1965 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1967 // likes on comments not supported here and likes on photos not supported by Diaspora
1969 // if($target_type !== 'Post')
1972 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1974 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1978 if(! diaspora_post_allow($importer,$contact)) {
1979 logger('diaspora_like: Ignoring this author.');
1983 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1984 intval($importer['uid']),
1989 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1992 $person = find_diaspora_person_by_handle($diaspora_handle);
1993 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1997 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1999 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2000 intval($importer['uid']),
2007 logger('diaspora_like: parent item not found: ' . $guid);
2011 $parent_item = $r[0];
2013 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2014 intval($importer['uid']),
2018 if($positive === 'true') {
2019 logger('diaspora_like: duplicate like: ' . $guid);
2022 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2023 // It looks like "RelayableRetractions" are used for "unlike" instead
2024 if($positive === 'false') {
2025 logger('diaspora_like: received a like with positive set to "false"...ignoring');
2026 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2027 intval($r[0]['id']),
2028 intval($importer['uid'])
2030 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2031 // send notification via proc_run()
2035 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2036 // It looks like "RelayableRetractions" are used for "unlike" instead
2037 if($positive === 'false') {
2038 logger('diaspora_like: received a like with positive set to "false"');
2039 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2044 /* How Diaspora performs "like" signature checking:
2046 - If an item has been sent by the like author to the top-level post owner to relay on
2047 to the rest of the contacts on the top-level post, the top-level post owner should check
2048 the author_signature, then create a parent_author_signature before relaying the like on
2049 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2050 check only the parent_author_signature. Basically, they trust that the top-level post
2051 owner has already verified the authenticity of anything he/she sends out
2052 - In either case, the signature that get checked is the signature created by the person
2056 // Diaspora has changed the way they are signing the likes.
2057 // Just to make sure that we don't miss any likes we will check the old and the current way.
2058 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2060 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2064 if ($parent_author_signature) {
2065 // If a parent_author_signature exists, then we've received the like
2066 // relayed from the top-level post owner. There's no need to check the
2067 // author_signature if the parent_author_signature is valid
2069 $parent_author_signature = base64_decode($parent_author_signature);
2071 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2072 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2074 logger('diaspora_like: top-level owner verification failed.');
2078 // If there's no parent_author_signature, then we've received the like
2079 // from the like creator. In that case, the person is "like"ing
2080 // our post, so he/she must be a contact of ours and his/her public key
2081 // should be in $msg['key']
2083 $author_signature = base64_decode($author_signature);
2085 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2086 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2088 logger('diaspora_like: like creator verification failed.');
2093 // Phew! Everything checks out. Now create an item.
2095 // Find the original comment author information.
2096 // We need this to make sure we display the comment author
2097 // information (name and avatar) correctly.
2098 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2101 $person = find_diaspora_person_by_handle($diaspora_handle);
2103 if(! is_array($person)) {
2104 logger('diaspora_like: unable to find author details');
2109 $uri = $diaspora_handle . ':' . $guid;
2111 $activity = ACTIVITY_LIKE;
2112 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2113 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2114 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2115 $body = $parent_item['body'];
2120 <type>$objtype</type>
2122 <id>{$parent_item['uri']}</id>
2125 <content>$body</content>
2128 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2133 $arr['uid'] = $importer['uid'];
2134 $arr['guid'] = $guid;
2135 $arr['network'] = NETWORK_DIASPORA;
2136 $arr['contact-id'] = $contact['id'];
2137 $arr['type'] = 'activity';
2138 $arr['wall'] = $parent_item['wall'];
2139 $arr['gravity'] = GRAVITY_LIKE;
2140 $arr['parent'] = $parent_item['id'];
2141 $arr['parent-uri'] = $parent_item['uri'];
2143 $arr['owner-name'] = $parent_item['name'];
2144 $arr['owner-link'] = $parent_item['url'];
2145 //$arr['owner-avatar'] = $parent_item['thumb'];
2146 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2148 $arr['author-name'] = $person['name'];
2149 $arr['author-link'] = $person['url'];
2150 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2152 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2153 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2154 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2155 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2156 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2158 $arr['app'] = 'Diaspora';
2160 $arr['private'] = $parent_item['private'];
2161 $arr['verb'] = $activity;
2162 $arr['object-type'] = $objtype;
2163 $arr['object'] = $obj;
2164 $arr['visible'] = 1;
2166 $arr['last-child'] = 0;
2168 $message_id = item_store($arr);
2172 // q("update item set plink = '%s' where id = %d",
2173 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2174 // dbesc($a->get_baseurl().'/display/'.$guid),
2175 // intval($message_id)
2179 if(! $parent_author_signature) {
2180 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2181 intval($message_id),
2182 dbesc($signed_data),
2183 dbesc(base64_encode($author_signature)),
2184 dbesc($diaspora_handle)
2188 // if the message isn't already being relayed, notify others
2189 // the existence of parent_author_signature means the parent_author or owner
2190 // is already relaying. The parent_item['origin'] indicates the message was created on our system
2192 if(($parent_item['origin']) && (! $parent_author_signature))
2193 proc_run('php','include/notifier.php','comment-import',$message_id);
2198 function diaspora_retraction($importer,$xml) {
2201 $guid = notags(unxmlify($xml->guid));
2202 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2203 $type = notags(unxmlify($xml->type));
2205 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2209 if($type === 'Person') {
2210 require_once('include/Contact.php');
2211 contact_remove($contact['id']);
2213 elseif($type === 'Post') {
2214 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2216 intval($importer['uid'])
2219 if(link_compare($r[0]['author-link'],$contact['url'])) {
2220 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2221 dbesc(datetime_convert()),
2224 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2233 function diaspora_signed_retraction($importer,$xml,$msg) {
2236 $guid = notags(unxmlify($xml->target_guid));
2237 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2238 $type = notags(unxmlify($xml->target_type));
2239 $sig = notags(unxmlify($xml->target_author_signature));
2241 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2243 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2245 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2250 $signed_data = $guid . ';' . $type ;
2253 /* How Diaspora performs relayable_retraction signature checking:
2255 - If an item has been sent by the item author to the top-level post owner to relay on
2256 to the rest of the contacts on the top-level post, the top-level post owner checks
2257 the author_signature, then creates a parent_author_signature before relaying the item on
2258 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2259 check only the parent_author_signature. Basically, they trust that the top-level post
2260 owner has already verified the authenticity of anything he/she sends out
2261 - In either case, the signature that get checked is the signature created by the person
2265 if($parent_author_signature) {
2267 $parent_author_signature = base64_decode($parent_author_signature);
2269 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2270 logger('diaspora_signed_retraction: top-level post owner verification failed');
2277 $sig_decode = base64_decode($sig);
2279 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2280 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2285 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2286 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2288 intval($importer['uid'])
2291 if(link_compare($r[0]['author-link'],$contact['url'])) {
2292 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2293 dbesc(datetime_convert()),
2294 dbesc(datetime_convert()),
2297 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2299 // Now check if the retraction needs to be relayed by us
2301 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2302 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2303 // The only item with `parent` and `id` as the parent id is the parent item.
2304 $p = q("select origin from item where parent = %d and id = %d limit 1",
2309 if(($p[0]['origin']) && (! $parent_author_signature)) {
2310 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2312 dbesc($signed_data),
2314 dbesc($diaspora_handle)
2317 // the existence of parent_author_signature would have meant the parent_author or owner
2318 // is already relaying.
2319 logger('diaspora_signed_retraction: relaying relayable_retraction');
2321 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2328 logger('diaspora_signed_retraction: unknown type: ' . $type);
2334 function diaspora_profile($importer,$xml,$msg) {
2337 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2340 if($diaspora_handle != $msg['author']) {
2341 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2345 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2349 if($contact['blocked']) {
2350 logger('diaspora_post: Ignoring this author.');
2354 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2355 $image_url = unxmlify($xml->image_url);
2356 $birthday = unxmlify($xml->birthday);
2357 $location = diaspora2bb(unxmlify($xml->location));
2358 $about = diaspora2bb(unxmlify($xml->bio));
2359 $gender = unxmlify($xml->gender);
2360 $tags = unxmlify($xml->tag_string);
2362 $tags = explode("#", $tags);
2364 $keywords = array();
2365 foreach ($tags as $tag) {
2366 $tag = trim(strtolower($tag));
2371 $keywords = implode(", ", $keywords);
2373 $handle_parts = explode("@", $diaspora_handle);
2375 $name = $handle_parts[0];
2378 if( preg_match("|^https?://|", $image_url) === 0) {
2379 $image_url = "http://" . $handle_parts[1] . $image_url;
2382 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2383 intval($importer['uid']),
2384 intval($contact['id'])
2386 $oldphotos = ((count($r)) ? $r : null);*/
2388 require_once('include/Photo.php');
2390 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2392 // Generic birthday. We don't know the timezone. The year is irrelevant.
2394 $birthday = str_replace('1000','1901',$birthday);
2396 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2398 // this is to prevent multiple birthday notifications in a single year
2399 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2401 if(substr($birthday,5) === substr($contact['bd'],5))
2402 $birthday = $contact['bd'];
2404 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2405 // Not doing this currently because D* protocol is scheduled for revision soon.
2407 $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",
2409 dbesc(datetime_convert()),
2413 dbesc(datetime_convert()),
2419 intval($contact['id']),
2420 intval($importer['uid'])
2423 if (unxmlify($xml->searchable) == "true") {
2424 require_once('include/socgraph.php');
2425 poco_check($contact['url'], $name, NETWORK_DIASPORA, $images[0], $about, $location, $gender, $keywords, "",
2426 datetime_convert(), 2, $contact['id'], $importer['uid']);
2430 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
2431 dbesc(normalise_link($contact['url'])));
2433 if (count($author) == 0) {
2434 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`, `location`, `about`) VALUES ('%s', '%s', '%s', '%s', '%s')",
2435 dbesc(normalise_link($contact['url'])), dbesc($name), dbesc($location), dbesc($about), dbesc($images[0]));
2437 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
2438 dbesc(normalise_link($contact['url'])));
2439 } else if (normalise_link($contact['url']).$name.$location.$about != normalise_link($author[0]["url"]).$author[0]["name"].$author[0]["location"].$author[0]["about"]) {
2440 q("UPDATE unique_contacts SET name = '%s', avatar = '%s', `location` = '%s', `about` = '%s' WHERE url = '%s'",
2441 dbesc($name), dbesc($images[0]), dbesc($location), dbesc($about), dbesc(normalise_link($contact['url'])));
2446 foreach($oldphotos as $ph) {
2447 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2448 intval($importer['uid']),
2449 intval($contact['id']),
2450 dbesc($ph['resource-id'])
2460 function diaspora_share($me,$contact) {
2462 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2463 $theiraddr = $contact['addr'];
2465 $tpl = get_markup_template('diaspora_share.tpl');
2466 $msg = replace_macros($tpl, array(
2467 '$sender' => $myaddr,
2468 '$recipient' => $theiraddr
2471 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2472 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2474 return(diaspora_transmit($owner,$contact,$slap, false));
2477 function diaspora_unshare($me,$contact) {
2480 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2482 $tpl = get_markup_template('diaspora_retract.tpl');
2483 $msg = replace_macros($tpl, array(
2484 '$guid' => $me['guid'],
2485 '$type' => 'Person',
2486 '$handle' => $myaddr
2489 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2490 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2492 return(diaspora_transmit($owner,$contact,$slap, false));
2497 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2500 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2501 $theiraddr = $contact['addr'];
2505 $title = $item['title'];
2506 $body = $item['body'];
2509 // We're trying to match Diaspora's split message/photo protocol but
2510 // all the photos are displayed on D* as links and not img's - even
2511 // though we're sending pretty much precisely what they send us when
2512 // doing the same operation.
2513 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2514 // which seems to get through intact.
2516 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2518 foreach($matches as $mtch) {
2520 $detail['str'] = $mtch[0];
2521 $detail['path'] = dirname($mtch[1]) . '/';
2522 $detail['file'] = basename($mtch[1]);
2523 $detail['guid'] = $item['guid'];
2524 $detail['handle'] = $myaddr;
2525 $images[] = $detail;
2526 $body = str_replace($detail['str'],$mtch[1],$body);
2531 //if(strlen($title))
2532 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2534 // convert to markdown
2535 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2536 //$body = bb2diaspora($body);
2540 $body = "## ".html_entity_decode($title)."\n\n".$body;
2542 if($item['attach']) {
2543 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2545 $body .= "\n" . t('Attachments:') . "\n";
2546 foreach($matches as $mtch) {
2547 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2553 $public = (($item['private']) ? 'false' : 'true');
2555 require_once('include/datetime.php');
2556 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2558 // Detect a share element and do a reshare
2559 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2560 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2561 $tpl = get_markup_template('diaspora_reshare.tpl');
2562 $msg = replace_macros($tpl, array(
2563 '$root_handle' => xmlify($ret['root_handle']),
2564 '$root_guid' => $ret['root_guid'],
2565 '$guid' => $item['guid'],
2566 '$handle' => xmlify($myaddr),
2567 '$public' => $public,
2568 '$created' => $created,
2569 '$provider' => $item["app"]
2572 $tpl = get_markup_template('diaspora_post.tpl');
2573 $msg = replace_macros($tpl, array(
2575 '$guid' => $item['guid'],
2576 '$handle' => xmlify($myaddr),
2577 '$public' => $public,
2578 '$created' => $created,
2579 '$provider' => $item["app"]
2583 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2585 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2586 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2588 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2590 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2592 if(count($images)) {
2593 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2596 return $return_code;
2599 function diaspora_is_reshare($body) {
2600 $body = trim($body);
2602 // Skip if it isn't a pure repeated messages
2603 // Does it start with a share?
2604 if (strpos($body, "[share") > 0)
2607 // Does it end with a share?
2608 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2611 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2612 // Skip if there is no shared message in there
2613 if ($body == $attributes)
2617 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2618 if ($matches[1] != "")
2619 $guid = $matches[1];
2621 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2622 if ($matches[1] != "")
2623 $guid = $matches[1];
2626 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2627 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2630 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2631 $ret["root_guid"] = $guid;
2637 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2638 if ($matches[1] != "")
2639 $profile = $matches[1];
2641 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2642 if ($matches[1] != "")
2643 $profile = $matches[1];
2647 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2648 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2652 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2653 if ($matches[1] != "")
2654 $link = $matches[1];
2656 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2657 if ($matches[1] != "")
2658 $link = $matches[1];
2660 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2661 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2667 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2669 if(! count($images))
2671 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2673 $tpl = get_markup_template('diaspora_photo.tpl');
2674 foreach($images as $image) {
2675 if(! stristr($image['path'],$mysite))
2677 $resource = str_replace('.jpg','',$image['file']);
2678 $resource = substr($resource,0,strpos($resource,'-'));
2680 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2682 intval($owner['uid'])
2686 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2687 $msg = replace_macros($tpl,array(
2688 '$path' => xmlify($image['path']),
2689 '$filename' => xmlify($image['file']),
2690 '$msg_guid' => xmlify($image['guid']),
2691 '$guid' => xmlify($r[0]['guid']),
2692 '$handle' => xmlify($image['handle']),
2693 '$public' => xmlify($public),
2694 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2698 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2699 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2700 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2702 diaspora_transmit($owner,$contact,$slap,$public_batch);
2707 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2710 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2711 // $theiraddr = $contact['addr'];
2713 // Diaspora doesn't support threaded comments, but some
2714 // versions of Diaspora (i.e. Diaspora-pistos) support
2715 // likes on comments
2716 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2717 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2718 dbesc($item['thr-parent'])
2722 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2723 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2724 // The only item with `parent` and `id` as the parent id is the parent item.
2725 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2726 intval($item['parent']),
2727 intval($item['parent'])
2735 if($item['verb'] === ACTIVITY_LIKE) {
2736 $tpl = get_markup_template('diaspora_like.tpl');
2738 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2739 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2740 // $positive = (($item['deleted']) ? 'false' : 'true');
2743 if(($item['deleted']))
2744 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2747 $tpl = get_markup_template('diaspora_comment.tpl');
2751 $text = html_entity_decode(bb2diaspora($item['body']));
2756 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2758 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2760 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2762 $msg = replace_macros($tpl,array(
2763 '$guid' => xmlify($item['guid']),
2764 '$parent_guid' => xmlify($parent['guid']),
2765 '$target_type' =>xmlify($target_type),
2766 '$authorsig' => xmlify($authorsig),
2767 '$body' => xmlify($text),
2768 '$positive' => xmlify($positive),
2769 '$handle' => xmlify($myaddr)
2772 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2774 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2775 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2777 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2781 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2785 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2786 // $theiraddr = $contact['addr'];
2788 $body = $item['body'];
2789 $text = html_entity_decode(bb2diaspora($body));
2791 // Diaspora doesn't support threaded comments, but some
2792 // versions of Diaspora (i.e. Diaspora-pistos) support
2793 // likes on comments
2794 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2795 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2796 dbesc($item['thr-parent'])
2800 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2801 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2802 // The only item with `parent` and `id` as the parent id is the parent item.
2803 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2804 intval($item['parent']),
2805 intval($item['parent'])
2814 $relay_retract = false;
2815 $sql_sign_id = 'iid';
2816 if( $item['deleted']) {
2817 $relay_retract = true;
2819 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2821 $sql_sign_id = 'retract_iid';
2822 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2824 elseif($item['verb'] === ACTIVITY_LIKE) {
2827 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2828 // $positive = (($item['deleted']) ? 'false' : 'true');
2831 $tpl = get_markup_template('diaspora_like_relay.tpl');
2833 else { // item is a comment
2834 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2838 // fetch the original signature if the relayable was created by a Diaspora
2839 // or DFRN user. Relayables for other networks are not supported.
2841 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2846 $signed_text = $orig_sign['signed_text'];
2847 $authorsig = $orig_sign['signature'];
2848 $handle = $orig_sign['signer'];
2852 // Author signature information (for likes, comments, and retractions of likes or comments,
2853 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2854 // function is called
2855 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2859 /* Since the author signature is only checked by the parent, not by the relay recipients,
2860 * I think it may not be necessary for us to do so much work to preserve all the original
2861 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2862 * Let's just generate that and forget about all the original author signature stuff.
2864 * Note: this might be more of an problem if we want to support likes on comments for older
2865 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2866 * doing that, let's ignore it for now.
2868 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2872 $handle = diaspora_handle_from_contact($item['contact-id']);
2878 $sender_signed_text = $item['guid'] . ';' . $target_type;
2880 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2882 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2884 // Sign the relayable with the top-level owner's signature
2886 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2887 // stored in the database, because that provides the best chance that Diaspora will
2888 // be able to reconstruct the signed text the same way we did. This is particularly a
2889 // concern for the comment, whose signed text includes the text of the comment. The
2890 // smallest change in the text of the comment, including removing whitespace, will
2891 // make the signature verification fail. Since we translate from BB code to Diaspora's
2892 // markup at the top of this function, which is AFTER we placed the original $signed_text
2893 // in the database, it's hazardous to trust the original $signed_text.
2895 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2897 $msg = replace_macros($tpl,array(
2898 '$guid' => xmlify($item['guid']),
2899 '$parent_guid' => xmlify($parent['guid']),
2900 '$target_type' =>xmlify($target_type),
2901 '$authorsig' => xmlify($authorsig),
2902 '$parentsig' => xmlify($parentauthorsig),
2903 '$body' => xmlify($text),
2904 '$positive' => xmlify($positive),
2905 '$handle' => xmlify($handle)
2908 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2911 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2912 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2914 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2920 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2923 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2925 // Check whether the retraction is for a top-level post or whether it's a relayable
2926 if( $item['uri'] !== $item['parent-uri'] ) {
2928 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2929 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2933 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2934 $target_type = 'StatusMessage';
2937 $signed_text = $item['guid'] . ';' . $target_type;
2939 $msg = replace_macros($tpl, array(
2940 '$guid' => xmlify($item['guid']),
2941 '$type' => xmlify($target_type),
2942 '$handle' => xmlify($myaddr),
2943 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2946 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2947 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2949 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2952 function diaspora_send_mail($item,$owner,$contact) {
2955 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2957 $r = q("select * from conv where id = %d and uid = %d limit 1",
2958 intval($item['convid']),
2959 intval($item['uid'])
2963 logger('diaspora_send_mail: conversation not found.');
2969 'guid' => xmlify($cnv['guid']),
2970 'subject' => xmlify($cnv['subject']),
2971 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2972 'diaspora_handle' => xmlify($cnv['creator']),
2973 'participant_handles' => xmlify($cnv['recips'])
2976 $body = bb2diaspora($item['body']);
2977 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2979 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2980 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2982 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2985 'guid' => xmlify($item['guid']),
2986 'parent_guid' => xmlify($cnv['guid']),
2987 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2988 'author_signature' => xmlify($sig),
2989 'text' => xmlify($body),
2990 'created_at' => xmlify($created),
2991 'diaspora_handle' => xmlify($myaddr),
2992 'conversation_guid' => xmlify($cnv['guid'])
2995 if($item['reply']) {
2996 $tpl = get_markup_template('diaspora_message.tpl');
2997 $xmsg = replace_macros($tpl, array('$msg' => $msg));
3000 $conv['messages'] = array($msg);
3001 $tpl = get_markup_template('diaspora_conversation.tpl');
3002 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3005 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3007 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3008 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3010 return(diaspora_transmit($owner,$contact,$slap,false));
3015 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
3017 $enabled = intval(get_config('system','diaspora_enabled'));
3023 $logid = random_string(4);
3024 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3026 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3030 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
3032 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3036 if (!intval(get_config('system','diaspora_test'))) {
3037 post_url($dest_url . '/', $slap);
3038 $return_code = $a->get_curl_code();
3040 logger('diaspora_transmit: test_mode');
3045 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
3047 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3048 logger('diaspora_transmit: queue message');
3050 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3051 intval($contact['id']),
3052 dbesc(NETWORK_DIASPORA),
3054 intval($public_batch)
3057 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3060 // queue message for redelivery
3061 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3066 return(($return_code) ? $return_code : (-1));