3 require_once('include/crypto.php');
4 require_once('include/items.php');
5 require_once('include/bb2diaspora.php');
6 require_once('include/contact_selectors.php');
7 require_once('include/queue_fn.php');
8 require_once('include/lock.php');
9 require_once('include/threads.php');
11 function diaspora_dispatch_public($msg) {
13 $enabled = intval(get_config('system','diaspora_enabled'));
15 logger('mod-diaspora: disabled');
19 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
20 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
21 AND `account_expired` = 0 AND `account_removed` = 0 ",
22 dbesc(NETWORK_DIASPORA),
27 logger('diaspora_public: delivering to: ' . $rr['username']);
28 diaspora_dispatch($rr,$msg);
32 logger('diaspora_public: no subscribers');
37 function diaspora_dispatch($importer,$msg,$attempt=1) {
41 $enabled = intval(get_config('system','diaspora_enabled'));
43 logger('mod-diaspora: disabled');
47 // php doesn't like dashes in variable names
49 $msg['message'] = str_replace(
50 array('<activity_streams-photo>','</activity_streams-photo>'),
51 array('<asphoto>','</asphoto>'),
55 $parsed_xml = parse_xml_string($msg['message'],false);
57 $xmlbase = $parsed_xml->post;
59 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
62 if($xmlbase->request) {
63 $ret = diaspora_request($importer,$xmlbase->request);
65 elseif($xmlbase->status_message) {
66 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
68 elseif($xmlbase->profile) {
69 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
71 elseif($xmlbase->comment) {
72 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
74 elseif($xmlbase->like) {
75 $ret = diaspora_like($importer,$xmlbase->like,$msg);
77 elseif($xmlbase->asphoto) {
78 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
80 elseif($xmlbase->reshare) {
81 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
83 elseif($xmlbase->retraction) {
84 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
86 elseif($xmlbase->signed_retraction) {
87 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
89 elseif($xmlbase->relayable_retraction) {
90 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
92 elseif($xmlbase->photo) {
93 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
95 elseif($xmlbase->conversation) {
96 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
98 elseif($xmlbase->message) {
99 $ret = diaspora_message($importer,$xmlbase->message,$msg);
102 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
107 function diaspora_handle_from_contact($contact_id) {
110 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
112 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
118 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
120 if($contact['network'] === NETWORK_DIASPORA) {
121 $handle = $contact['addr'];
123 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
125 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
126 $baseurl_start = strpos($contact['url'],'://') + 3;
127 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
128 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
129 $handle = $contact['nick'] . '@' . $baseurl;
131 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
138 function diaspora_get_contact_by_handle($uid,$handle) {
139 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
140 dbesc(NETWORK_DIASPORA),
147 $handle_parts = explode("@", $handle);
148 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
149 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
160 function find_diaspora_person_by_handle($handle) {
170 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
171 dbesc(NETWORK_DIASPORA),
176 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
178 // update record occasionally so it doesn't get stale
179 $d = strtotime($person['updated'] . ' +00:00');
180 if($d < strtotime('now - 14 days'))
185 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
187 // If the person isn't in our 'fcontact' table, or if he/she is but
188 // his/her information hasn't been updated for more than 14 days, then
189 // we want to fetch the person's information from the remote server.
191 // Note that $person isn't changed by this block of code unless the
192 // person's information has been successfully fetched from the remote
193 // server. So if $person was 'false' to begin with (because he/she wasn't
194 // in the local cache), it'll stay false, and if $person held the local
195 // cache information to begin with, it'll keep that information. That way
196 // if there's a problem with the remote fetch, we can at least use our
197 // cached information--it's better than nothing.
199 if((! $person) || ($update)) {
200 // Lock the function to prevent race conditions if multiple items
201 // come in at the same time from a person who doesn't exist in
204 // Don't loop forever. On the last loop, try to create the contact
205 // whether the function is locked or not. Maybe the locking thread
206 // has died or something. At any rate, a duplicate in 'fcontact'
207 // is a much smaller problem than a deadlocked thread
208 $got_lock = lock_function('find_diaspora_person_by_handle', false);
209 if(($endlessloop + 1) >= $maxloops)
213 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
214 require_once('include/Scrape.php');
215 $r = probe_url($handle, PROBE_DIASPORA);
217 // Note that Friendica contacts can return a "Diaspora person"
218 // if Diaspora connectivity is enabled on their server
219 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
220 add_fcontact($r,$update);
224 unlock_function('find_diaspora_person_by_handle');
227 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
229 block_on_function_lock('find_diaspora_person_by_handle');
232 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
233 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
234 // The fact that the function was locked may mean that another process was creating the
235 // person's record. It could also mean another process was creating or updating an unrelated
238 // At any rate, we need to keep trying until we've either got the person or had a chance to
239 // try to fetch his/her remote information. But we don't want to block on locking the
240 // function, because if the other process is creating the record, then when we acquire the lock
241 // we'll dive right into creating another, duplicate record. We DO want to at least wait
242 // until the lock is released, so we don't flood the database with requests.
244 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
245 // we do have some information for the person
251 function get_diaspora_key($uri) {
252 logger('Fetching diaspora key for: ' . $uri);
254 $r = find_diaspora_person_by_handle($uri);
261 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
264 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
267 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
269 // $b64_data = base64_encode($msg);
270 // $b64url_data = base64url_encode($b64_data);
272 $b64url_data = base64url_encode($msg);
274 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
276 $type = 'application/xml';
277 $encoding = 'base64url';
280 $signable_data = $data . '.' . base64url_encode($type) . '.'
281 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
283 $signature = rsa_sign($signable_data,$prvkey);
284 $sig = base64url_encode($signature);
287 <?xml version='1.0' encoding='UTF-8'?>
288 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
290 <author_id>$handle</author_id>
293 <me:encoding>base64url</me:encoding>
294 <me:alg>RSA-SHA256</me:alg>
295 <me:data type="application/xml">$data</me:data>
296 <me:sig>$sig</me:sig>
301 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
309 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
313 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
315 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
317 // without a public key nothing will work
320 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
324 $inner_aes_key = random_string(32);
325 $b_inner_aes_key = base64_encode($inner_aes_key);
326 $inner_iv = random_string(16);
327 $b_inner_iv = base64_encode($inner_iv);
329 $outer_aes_key = random_string(32);
330 $b_outer_aes_key = base64_encode($outer_aes_key);
331 $outer_iv = random_string(16);
332 $b_outer_iv = base64_encode($outer_iv);
334 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
336 $padded_data = pkcs5_pad($msg,16);
337 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
339 $b64_data = base64_encode($inner_encrypted);
342 $b64url_data = base64url_encode($b64_data);
343 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
345 $type = 'application/xml';
346 $encoding = 'base64url';
349 $signable_data = $data . '.' . base64url_encode($type) . '.'
350 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
352 $signature = rsa_sign($signable_data,$prvkey);
353 $sig = base64url_encode($signature);
355 $decrypted_header = <<< EOT
358 <aes_key>$b_inner_aes_key</aes_key>
359 <author_id>$handle</author_id>
363 $decrypted_header = pkcs5_pad($decrypted_header,16);
365 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
367 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
369 $encrypted_outer_key_bundle = '';
370 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
372 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
374 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
376 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
377 'ciphertext' => base64_encode($ciphertext)));
378 $cipher_json = base64_encode($encrypted_header_json_object);
380 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
383 <?xml version='1.0' encoding='UTF-8'?>
384 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
387 <me:encoding>base64url</me:encoding>
388 <me:alg>RSA-SHA256</me:alg>
389 <me:data type="application/xml">$data</me:data>
390 <me:sig>$sig</me:sig>
395 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
402 * diaspora_decode($importer,$xml)
403 * array $importer -> from user table
404 * string $xml -> urldecoded Diaspora salmon
407 * 'message' -> decoded Diaspora XML message
408 * 'author' -> author diaspora handle
409 * 'key' -> author public key (converted to pkcs#8)
411 * Author and key are used elsewhere to save a lookup for verifying replies and likes
415 function diaspora_decode($importer,$xml) {
418 $basedom = parse_xml_string($xml);
420 $children = $basedom->children('https://joindiaspora.com/protocol');
422 if($children->header) {
424 $author_link = str_replace('acct:','',$children->header->author_id);
428 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
430 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
431 $ciphertext = base64_decode($encrypted_header->ciphertext);
433 $outer_key_bundle = '';
434 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
436 $j_outer_key_bundle = json_decode($outer_key_bundle);
438 $outer_iv = base64_decode($j_outer_key_bundle->iv);
439 $outer_key = base64_decode($j_outer_key_bundle->key);
441 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
444 $decrypted = pkcs5_unpad($decrypted);
447 * $decrypted now contains something like
450 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
451 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
456 * <name>Ryan Hughes</name>
457 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
462 * <author_id>galaxor@diaspora.priateship.org</author_id>
466 * </decrypted_header>
469 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
470 $idom = parse_xml_string($decrypted,false);
472 $inner_iv = base64_decode($idom->iv);
473 $inner_aes_key = base64_decode($idom->aes_key);
475 $author_link = str_replace('acct:','',$idom->author_id);
479 $dom = $basedom->children(NAMESPACE_SALMON_ME);
481 // figure out where in the DOM tree our data is hiding
483 if($dom->provenance->data)
484 $base = $dom->provenance;
485 elseif($dom->env->data)
491 logger('mod-diaspora: unable to locate salmon data in xml ');
492 http_status_exit(400);
496 // Stash the signature away for now. We have to find their key or it won't be good for anything.
497 $signature = base64url_decode($base->sig);
501 // strip whitespace so our data element will return to one big base64 blob
502 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
505 // stash away some other stuff for later
507 $type = $base->data[0]->attributes()->type[0];
508 $keyhash = $base->sig[0]->attributes()->keyhash[0];
509 $encoding = $base->encoding;
513 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
517 $data = base64url_decode($data);
521 $inner_decrypted = $data;
525 // Decode the encrypted blob
527 $inner_encrypted = base64_decode($data);
528 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
529 $inner_decrypted = pkcs5_unpad($inner_decrypted);
533 logger('mod-diaspora: Could not retrieve author URI.');
534 http_status_exit(400);
537 // Once we have the author URI, go to the web and try to find their public key
538 // (first this will look it up locally if it is in the fcontact cache)
539 // This will also convert diaspora public key from pkcs#1 to pkcs#8
541 logger('mod-diaspora: Fetching key for ' . $author_link );
542 $key = get_diaspora_key($author_link);
545 logger('mod-diaspora: Could not retrieve author key.');
546 http_status_exit(400);
549 $verify = rsa_verify($signed_data,$signature,$key);
552 logger('mod-diaspora: Message did not verify. Discarding.');
553 http_status_exit(400);
556 logger('mod-diaspora: Message verified.');
558 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
563 function diaspora_request($importer,$xml) {
567 $sender_handle = unxmlify($xml->sender_handle);
568 $recipient_handle = unxmlify($xml->recipient_handle);
570 if(! $sender_handle || ! $recipient_handle)
573 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
577 // perhaps we were already sharing with this person. Now they're sharing with us.
578 // That makes us friends.
580 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
581 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
582 intval(CONTACT_IS_FRIEND),
583 intval($contact['id']),
584 intval($importer['uid'])
589 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
590 intval($importer['uid'])
593 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
594 require_once('include/items.php');
596 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
597 intval($importer['uid'])
600 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
602 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
605 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
606 $arr['uid'] = $importer['uid'];
607 $arr['contact-id'] = $self[0]['id'];
609 $arr['type'] = 'wall';
612 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
613 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
614 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
615 $arr['verb'] = ACTIVITY_FRIEND;
616 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
618 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
619 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
620 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
621 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
623 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
624 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
625 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
626 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
627 $arr['object'] .= '</link></object>' . "\n";
628 $arr['last-child'] = 1;
630 $arr['allow_cid'] = $user[0]['allow_cid'];
631 $arr['allow_gid'] = $user[0]['allow_gid'];
632 $arr['deny_cid'] = $user[0]['deny_cid'];
633 $arr['deny_gid'] = $user[0]['deny_gid'];
635 $i = item_store($arr);
637 proc_run('php',"include/notifier.php","activity","$i");
646 $ret = find_diaspora_person_by_handle($sender_handle);
649 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
650 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
654 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
658 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
659 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
660 intval($importer['uid']),
661 dbesc($ret['network']),
665 dbesc(normalise_link($ret['url'])),
669 dbesc($ret['photo']),
670 dbesc($ret['pubkey']),
671 dbesc($ret['notify']),
677 // find the contact record we just created
679 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
681 if(! $contact_record) {
682 logger('diaspora_request: unable to locate newly created contact record.');
686 $g = q("select def_gid from user where uid = %d limit 1",
687 intval($importer['uid'])
689 if($g && intval($g[0]['def_gid'])) {
690 require_once('include/group.php');
691 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
694 if($importer['page-flags'] == PAGE_NORMAL) {
696 $hash = random_string() . (string) time(); // Generate a confirm_key
698 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
699 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
700 intval($importer['uid']),
701 intval($contact_record['id']),
704 dbesc( t('Sharing notification from Diaspora network')),
706 dbesc(datetime_convert())
711 // automatic friend approval
713 require_once('include/Photo.php');
715 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
717 // technically they are sharing with us (CONTACT_IS_SHARING),
718 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
719 // we are going to change the relationship and make them a follower.
721 if($importer['page-flags'] == PAGE_FREELOVE)
722 $new_relation = CONTACT_IS_FRIEND;
724 $new_relation = CONTACT_IS_FOLLOWER;
726 $r = q("UPDATE `contact` SET
733 `avatar-date` = '%s',
741 intval($new_relation),
742 dbesc(datetime_convert()),
743 dbesc(datetime_convert()),
744 dbesc(datetime_convert()),
745 intval($contact_record['id'])
748 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
750 $ret = diaspora_share($u[0],$contact_record);
756 function diaspora_post_allow($importer,$contact) {
758 // perhaps we were already sharing with this person. Now they're sharing with us.
759 // That makes us friends.
760 // Normally this should have handled by getting a request - but this could get lost
761 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
762 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
763 intval(CONTACT_IS_FRIEND),
764 intval($contact['id']),
765 intval($importer['uid'])
767 $contact['rel'] = CONTACT_IS_FRIEND;
768 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
771 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
773 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
775 if($contact['rel'] == CONTACT_IS_FOLLOWER)
776 if($importer['page-flags'] == PAGE_COMMUNITY)
782 function diaspora_post($importer,$xml,$msg) {
785 $guid = notags(unxmlify($xml->guid));
786 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
788 if($diaspora_handle != $msg['author']) {
789 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
793 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
797 if(! diaspora_post_allow($importer,$contact)) {
798 logger('diaspora_post: Ignoring this author.');
802 $message_id = $diaspora_handle . ':' . $guid;
803 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
804 intval($importer['uid']),
809 logger('diaspora_post: message exists: ' . $guid);
813 // allocate a guid on our system - we aren't fixing any collisions.
814 // we're ignoring them
816 $g = q("select * from guid where guid = '%s' limit 1",
820 q("insert into guid ( guid ) values ( '%s' )",
825 $created = unxmlify($xml->created_at);
826 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
828 $body = diaspora2bb($xml->raw_message);
830 // Add OEmbed and other information to the body
831 $body = add_page_info_to_body($body, false, true);
837 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
839 foreach($matches as $mtch) {
840 if(strlen($str_tags))
842 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
846 $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
848 $datarray['uid'] = $importer['uid'];
849 $datarray['contact-id'] = $contact['id'];
850 $datarray['wall'] = 0;
851 $datarray['network'] = NETWORK_DIASPORA;
852 $datarray['verb'] = ACTIVITY_POST;
853 $datarray['guid'] = $guid;
854 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
855 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
856 $datarray['private'] = $private;
857 $datarray['parent'] = 0;
858 $datarray['plink'] = $plink;
859 $datarray['owner-name'] = $contact['name'];
860 $datarray['owner-link'] = $contact['url'];
861 //$datarray['owner-avatar'] = $contact['thumb'];
862 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
863 $datarray['author-name'] = $contact['name'];
864 $datarray['author-link'] = $contact['url'];
865 $datarray['author-avatar'] = $contact['thumb'];
866 $datarray['body'] = $body;
867 $datarray['tag'] = $str_tags;
868 $datarray['app'] = 'Diaspora';
870 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
872 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
874 DiasporaFetchGuid($datarray);
875 $message_id = item_store($datarray);
881 function DiasporaFetchGuid($item) {
882 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
883 function ($match) use ($item){
884 return(DiasporaFetchGuidSub($match, $item));
888 function DiasporaFetchGuidSub($match, $item) {
891 $author = parse_url($item["author-link"]);
892 $authorserver = $author["scheme"]."://".$author["host"];
894 $owner = parse_url($item["owner-link"]);
895 $ownerserver = $owner["scheme"]."://".$owner["host"];
897 if (!diaspora_store_by_guid($match[1], $authorserver))
898 diaspora_store_by_guid($match[1], $ownerserver);
901 function diaspora_store_by_guid($guid, $server) {
902 require_once("include/Contact.php");
904 logger("fetching item ".$guid." from ".$server, LOGGER_DEBUG);
906 $item = diaspora_fetch_message($guid, $server);
911 $body = $item["body"];
912 $str_tags = $item["tag"];
914 $created = $item["created"];
915 $author = $item["author"];
916 $guid = $item["guid"];
917 $private = $item["private"];
919 $message_id = $author.':'.$guid;
920 $r = q("SELECT `id` FROM `item` WHERE `uid` = 0 AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
927 $person = find_diaspora_person_by_handle($author);
930 $datarray['uid'] = 0;
931 $datarray['contact-id'] = get_contact($person['url'], 0);
932 $datarray['wall'] = 0;
933 $datarray['network'] = NETWORK_DIASPORA;
934 $datarray['guid'] = $guid;
935 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
936 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
937 $datarray['private'] = $private;
938 $datarray['parent'] = 0;
939 $datarray['plink'] = 'https://'.substr($author,strpos($author,'@')+1).'/posts/'.$guid;
940 $datarray['author-name'] = $person['name'];
941 $datarray['author-link'] = $person['url'];
942 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
943 $datarray['owner-name'] = $datarray['author-name'];
944 $datarray['owner-link'] = $datarray['author-link'];
945 $datarray['owner-avatar'] = $datarray['author-avatar'];
946 $datarray['body'] = $body;
947 $datarray['tag'] = $str_tags;
948 $datarray['app'] = $app;
949 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
951 DiasporaFetchGuid($datarray);
952 $message_id = item_store($datarray);
955 // Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
960 function diaspora_fetch_message($guid, $server, $level = 0) {
967 // This will not work if the server is not a Diaspora server
968 $source_url = $server.'/p/'.$guid.'.xml';
969 $x = fetch_url($source_url);
973 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
974 $source_xml = parse_xml_string($x,false);
977 $item["app"] = 'Diaspora';
978 $item["guid"] = $guid;
981 if ($source_xml->post->status_message->created_at)
982 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
984 if ($source_xml->post->status_message->provider_display_name)
985 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
987 if ($source_xml->post->status_message->diaspora_handle)
988 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
990 if ($source_xml->post->status_message->guid)
991 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
993 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
995 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
996 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
997 $body = scale_external_images($body,false);
998 } elseif($source_xml->post->asphoto->image_url) {
999 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1000 $body = scale_external_images($body);
1001 } elseif($source_xml->post->status_message) {
1002 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1004 // Checking for embedded pictures
1005 if($source_xml->post->status_message->photo->remote_photo_path AND
1006 $source_xml->post->status_message->photo->remote_photo_name) {
1008 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1009 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1011 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1013 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1016 $body = scale_external_images($body);
1018 // Add OEmbed and other information to the body
1019 $body = add_page_info_to_body($body, false, true);
1020 } elseif($source_xml->post->reshare) {
1021 // Reshare of a reshare
1022 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1024 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1025 logger('no content found: '.print_r($source_xml,true));
1033 $item["body"] = $body;
1038 function diaspora_reshare($importer,$xml,$msg) {
1040 logger('diaspora_reshare: init: ' . print_r($xml,true));
1043 $guid = notags(unxmlify($xml->guid));
1044 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1047 if($diaspora_handle != $msg['author']) {
1048 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1052 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1056 if(! diaspora_post_allow($importer,$contact)) {
1057 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1061 $message_id = $diaspora_handle . ':' . $guid;
1062 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1063 intval($importer['uid']),
1068 logger('diaspora_reshare: message exists: ' . $guid);
1072 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1073 $orig_guid = notags(unxmlify($xml->root_guid));
1075 $create_original_post = false;
1077 // Do we already have this item?
1078 $r = q("SELECT `body`, `tag`, `app`, `created`, `author-link`, `plink` FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1080 dbesc(NETWORK_DIASPORA)
1083 logger('reshared message '.orig_guid." reshared by ".$guid.' already exists on system: '.$orig_url);
1085 // Maybe it is already a reshared item?
1086 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1087 require_once('include/api.php');
1088 if (api_share_as_retweet($r[0]))
1091 $body = $r[0]["body"];
1092 $str_tags = $r[0]["tag"];
1093 $app = $r[0]["app"];
1094 $orig_created = $r[0]["created"];
1095 $orig_author = $r[0]["author-link"];
1096 $create_original_post = ($body != "");
1097 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1106 $orig_url = 'https://'.substr($orig_author,strpos($orig_author,'@')+1).'/posts/'.$orig_guid;
1108 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1109 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1110 $item = diaspora_fetch_message($orig_guid, $server);
1113 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1114 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1115 $item = diaspora_fetch_message($orig_guid, $server);
1118 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1119 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1120 $item = diaspora_fetch_message($orig_guid, $server);
1123 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1124 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1125 $item = diaspora_fetch_message($orig_guid, $server);
1129 $body = $item["body"];
1130 $str_tags = $item["tag"];
1131 $app = $item["app"];
1132 $orig_created = $item["created"];
1133 $orig_author = $item["author"];
1134 $orig_guid = $item["guid"];
1135 $create_original_post = ($body != "");
1136 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1140 $person = find_diaspora_person_by_handle($orig_author);
1142 // allocate a guid on our system - we aren't fixing any collisions.
1143 // we're ignoring them
1145 $g = q("select * from guid where guid = '%s' limit 1",
1149 q("insert into guid ( guid ) values ( '%s' )",
1154 $created = unxmlify($xml->created_at);
1155 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1157 $datarray = array();
1159 $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
1161 $datarray['uid'] = $importer['uid'];
1162 $datarray['contact-id'] = $contact['id'];
1163 $datarray['wall'] = 0;
1164 $datarray['network'] = NETWORK_DIASPORA;
1165 $datarray['guid'] = $guid;
1166 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1167 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1168 $datarray['private'] = $private;
1169 $datarray['parent'] = 0;
1170 $datarray['plink'] = $plink;
1171 $datarray['owner-name'] = $contact['name'];
1172 $datarray['owner-link'] = $contact['url'];
1173 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1174 if (!intval(get_config('system','wall-to-wall_share'))) {
1175 $prefix = "[share author='".str_replace(array("'", "[", "]"), array("'", "[", "]"),$person['name']).
1176 "' profile='".$person['url'].
1177 "' avatar='".((x($person,'thumb')) ? $person['thumb'] : $person['photo']).
1178 "' guid='".$orig_guid.
1179 "' posted='".$orig_created.
1180 "' link='".str_replace(array("'", "[", "]"), array("'", "[", "]"),$orig_url)."']";
1181 $datarray['author-name'] = $contact['name'];
1182 $datarray['author-link'] = $contact['url'];
1183 $datarray['author-avatar'] = $contact['thumb'];
1184 $datarray['body'] = $prefix.$body."[/share]";
1186 // Let reshared messages look like wall-to-wall posts
1187 $datarray['author-name'] = $person['name'];
1188 $datarray['author-link'] = $person['url'];
1189 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1190 $datarray['body'] = $body;
1193 $datarray['tag'] = $str_tags;
1194 $datarray['app'] = $app;
1196 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1197 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1199 // Store the original item of a reshare
1200 if ($create_original_post) {
1201 require_once("include/Contact.php");
1203 $datarray2 = $datarray;
1205 $datarray2['uid'] = 0;
1206 $datarray2['contact-id'] = get_contact($person['url'], 0);
1207 $datarray2['guid'] = $orig_guid;
1208 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_author.':'.$orig_guid;
1209 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = datetime_convert('UTC','UTC',$orig_created);
1210 $datarray2['plink'] = 'https://'.substr($orig_author,strpos($orig_author,'@')+1).'/posts/'.$orig_guid;
1212 $datarray2['author-name'] = $person['name'];
1213 $datarray2['author-link'] = $person['url'];
1214 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1215 $datarray2['owner-name'] = $datarray2['author-name'];
1216 $datarray2['owner-link'] = $datarray2['author-link'];
1217 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1218 $datarray2['body'] = $body;
1220 DiasporaFetchGuid($datarray2);
1221 $message_id = item_store($datarray2);
1223 logger("Store original item ".$orig_guid." under message id ".$message_id);
1226 DiasporaFetchGuid($datarray);
1227 $message_id = item_store($datarray);
1234 function diaspora_asphoto($importer,$xml,$msg) {
1235 logger('diaspora_asphoto called');
1238 $guid = notags(unxmlify($xml->guid));
1239 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1241 if($diaspora_handle != $msg['author']) {
1242 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1246 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1250 if(! diaspora_post_allow($importer,$contact)) {
1251 logger('diaspora_asphoto: Ignoring this author.');
1255 $message_id = $diaspora_handle . ':' . $guid;
1256 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1257 intval($importer['uid']),
1262 logger('diaspora_asphoto: message exists: ' . $guid);
1266 // allocate a guid on our system - we aren't fixing any collisions.
1267 // we're ignoring them
1269 $g = q("select * from guid where guid = '%s' limit 1",
1273 q("insert into guid ( guid ) values ( '%s' )",
1278 $created = unxmlify($xml->created_at);
1279 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1281 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1282 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1283 $body = scale_external_images($body,false);
1285 elseif($xml->image_url) {
1286 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1287 $body = scale_external_images($body);
1290 logger('diaspora_asphoto: no photo url found.');
1294 $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
1296 $datarray = array();
1298 $datarray['uid'] = $importer['uid'];
1299 $datarray['contact-id'] = $contact['id'];
1300 $datarray['wall'] = 0;
1301 $datarray['network'] = NETWORK_DIASPORA;
1302 $datarray['guid'] = $guid;
1303 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1304 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1305 $datarray['private'] = $private;
1306 $datarray['parent'] = 0;
1307 $datarray['plink'] = $plink;
1308 $datarray['owner-name'] = $contact['name'];
1309 $datarray['owner-link'] = $contact['url'];
1310 //$datarray['owner-avatar'] = $contact['thumb'];
1311 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1312 $datarray['author-name'] = $contact['name'];
1313 $datarray['author-link'] = $contact['url'];
1314 $datarray['author-avatar'] = $contact['thumb'];
1315 $datarray['body'] = $body;
1317 $datarray['app'] = 'Diaspora/Cubbi.es';
1319 DiasporaFetchGuid($datarray);
1320 $message_id = item_store($datarray);
1323 // q("update item set plink = '%s' where id = %d",
1324 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1325 // intval($message_id)
1338 function diaspora_comment($importer,$xml,$msg) {
1341 $guid = notags(unxmlify($xml->guid));
1342 $parent_guid = notags(unxmlify($xml->parent_guid));
1343 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1344 $target_type = notags(unxmlify($xml->target_type));
1345 $text = unxmlify($xml->text);
1346 $author_signature = notags(unxmlify($xml->author_signature));
1348 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1350 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1352 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1356 if(! diaspora_post_allow($importer,$contact)) {
1357 logger('diaspora_comment: Ignoring this author.');
1361 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1362 intval($importer['uid']),
1366 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1370 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1371 intval($importer['uid']),
1375 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1378 $parent_item = $r[0];
1381 /* How Diaspora performs comment signature checking:
1383 - If an item has been sent by the comment author to the top-level post owner to relay on
1384 to the rest of the contacts on the top-level post, the top-level post owner should check
1385 the author_signature, then create a parent_author_signature before relaying the comment on
1386 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1387 check only the parent_author_signature. Basically, they trust that the top-level post
1388 owner has already verified the authenticity of anything he/she sends out
1389 - In either case, the signature that get checked is the signature created by the person
1393 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1396 if($parent_author_signature) {
1397 // If a parent_author_signature exists, then we've received the comment
1398 // relayed from the top-level post owner. There's no need to check the
1399 // author_signature if the parent_author_signature is valid
1401 $parent_author_signature = base64_decode($parent_author_signature);
1403 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1404 logger('diaspora_comment: top-level owner verification failed.');
1409 // If there's no parent_author_signature, then we've received the comment
1410 // from the comment creator. In that case, the person is commenting on
1411 // our post, so he/she must be a contact of ours and his/her public key
1412 // should be in $msg['key']
1414 $author_signature = base64_decode($author_signature);
1416 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1417 logger('diaspora_comment: comment author verification failed.');
1422 // Phew! Everything checks out. Now create an item.
1424 // Find the original comment author information.
1425 // We need this to make sure we display the comment author
1426 // information (name and avatar) correctly.
1427 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1430 $person = find_diaspora_person_by_handle($diaspora_handle);
1432 if(! is_array($person)) {
1433 logger('diaspora_comment: unable to find author details');
1438 $body = diaspora2bb($text);
1439 $message_id = $diaspora_handle . ':' . $guid;
1441 $datarray = array();
1443 $datarray['uid'] = $importer['uid'];
1444 $datarray['contact-id'] = $contact['id'];
1445 $datarray['type'] = 'remote-comment';
1446 $datarray['wall'] = $parent_item['wall'];
1447 $datarray['network'] = NETWORK_DIASPORA;
1448 $datarray['verb'] = ACTIVITY_POST;
1449 $datarray['gravity'] = GRAVITY_COMMENT;
1450 $datarray['guid'] = $guid;
1451 $datarray['uri'] = $message_id;
1452 $datarray['parent-uri'] = $parent_item['uri'];
1454 // No timestamps for comments? OK, we'll the use current time.
1455 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1456 $datarray['private'] = $parent_item['private'];
1458 $datarray['owner-name'] = $parent_item['owner-name'];
1459 $datarray['owner-link'] = $parent_item['owner-link'];
1460 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1462 $datarray['author-name'] = $person['name'];
1463 $datarray['author-link'] = $person['url'];
1464 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1465 $datarray['body'] = $body;
1467 // We can't be certain what the original app is if the message is relayed.
1468 if(($parent_item['origin']) && (! $parent_author_signature))
1469 $datarray['app'] = 'Diaspora';
1471 DiasporaFetchGuid($datarray);
1472 $message_id = item_store($datarray);
1475 //q("update item set plink = '%s' where id = %d",
1476 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1477 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1478 // intval($message_id)
1482 if(($parent_item['origin']) && (! $parent_author_signature)) {
1483 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1484 intval($message_id),
1485 dbesc($signed_data),
1486 dbesc(base64_encode($author_signature)),
1487 dbesc($diaspora_handle)
1490 // if the message isn't already being relayed, notify others
1491 // the existence of parent_author_signature means the parent_author or owner
1492 // is already relaying.
1494 proc_run('php','include/notifier.php','comment-import',$message_id);
1497 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1498 dbesc($parent_item['uri']),
1499 intval($importer['uid'])
1502 if(count($myconv)) {
1503 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1505 foreach($myconv as $conv) {
1507 // now if we find a match, it means we're in this conversation
1509 if(! link_compare($conv['author-link'],$importer_url))
1512 require_once('include/enotify.php');
1514 $conv_parent = $conv['parent'];
1517 'type' => NOTIFY_COMMENT,
1518 'notify_flags' => $importer['notify-flags'],
1519 'language' => $importer['language'],
1520 'to_name' => $importer['username'],
1521 'to_email' => $importer['email'],
1522 'uid' => $importer['uid'],
1523 'item' => $datarray,
1524 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1525 'source_name' => $datarray['author-name'],
1526 'source_link' => $datarray['author-link'],
1527 'source_photo' => $datarray['author-avatar'],
1528 'verb' => ACTIVITY_POST,
1530 'parent' => $conv_parent,
1531 'parent_uri' => $parent_uri
1534 // only send one notification
1544 function diaspora_conversation($importer,$xml,$msg) {
1548 $guid = notags(unxmlify($xml->guid));
1549 $subject = notags(unxmlify($xml->subject));
1550 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1551 $participant_handles = notags(unxmlify($xml->participant_handles));
1552 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1554 $parent_uri = $diaspora_handle . ':' . $guid;
1556 $messages = $xml->message;
1558 if(! count($messages)) {
1559 logger('diaspora_conversation: empty conversation');
1563 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1565 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1569 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1570 logger('diaspora_conversation: Ignoring this author.');
1574 $conversation = null;
1576 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1577 intval($importer['uid']),
1581 $conversation = $c[0];
1583 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1584 intval($importer['uid']),
1586 dbesc($diaspora_handle),
1587 dbesc(datetime_convert('UTC','UTC',$created_at)),
1588 dbesc(datetime_convert()),
1590 dbesc($participant_handles)
1593 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1594 intval($importer['uid']),
1598 $conversation = $c[0];
1600 if(! $conversation) {
1601 logger('diaspora_conversation: unable to create conversation.');
1605 foreach($messages as $mesg) {
1609 $msg_guid = notags(unxmlify($mesg->guid));
1610 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1611 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1612 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1613 $msg_text = unxmlify($mesg->text);
1614 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1615 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1616 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1617 if($msg_conversation_guid != $guid) {
1618 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1622 $body = diaspora2bb($msg_text);
1623 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1625 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1627 $author_signature = base64_decode($msg_author_signature);
1629 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1634 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1636 if(is_array($person) && x($person,'pubkey'))
1637 $key = $person['pubkey'];
1639 logger('diaspora_conversation: unable to find author details');
1644 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1645 logger('diaspora_conversation: verification failed.');
1649 if($msg_parent_author_signature) {
1650 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1652 $parent_author_signature = base64_decode($msg_parent_author_signature);
1656 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1657 logger('diaspora_conversation: owner verification failed.');
1662 $r = q("select id from mail where `uri` = '%s' limit 1",
1666 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1670 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')",
1671 intval($importer['uid']),
1673 intval($conversation['id']),
1674 dbesc($person['name']),
1675 dbesc($person['photo']),
1676 dbesc($person['url']),
1677 intval($contact['id']),
1684 dbesc($msg_created_at)
1687 q("update conv set updated = '%s' where id = %d",
1688 dbesc(datetime_convert()),
1689 intval($conversation['id'])
1692 require_once('include/enotify.php');
1694 'type' => NOTIFY_MAIL,
1695 'notify_flags' => $importer['notify-flags'],
1696 'language' => $importer['language'],
1697 'to_name' => $importer['username'],
1698 'to_email' => $importer['email'],
1699 'uid' =>$importer['importer_uid'],
1700 'item' => array('subject' => $subject, 'body' => $body),
1701 'source_name' => $person['name'],
1702 'source_link' => $person['url'],
1703 'source_photo' => $person['thumb'],
1704 'verb' => ACTIVITY_POST,
1712 function diaspora_message($importer,$xml,$msg) {
1716 $msg_guid = notags(unxmlify($xml->guid));
1717 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1718 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1719 $msg_author_signature = notags(unxmlify($xml->author_signature));
1720 $msg_text = unxmlify($xml->text);
1721 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1722 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1723 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1725 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1727 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1729 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1733 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1734 logger('diaspora_message: Ignoring this author.');
1738 $conversation = null;
1740 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1741 intval($importer['uid']),
1742 dbesc($msg_conversation_guid)
1745 $conversation = $c[0];
1747 logger('diaspora_message: conversation not available.');
1753 $body = diaspora2bb($msg_text);
1754 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1756 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1759 $author_signature = base64_decode($msg_author_signature);
1761 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1762 if(is_array($person) && x($person,'pubkey'))
1763 $key = $person['pubkey'];
1765 logger('diaspora_message: unable to find author details');
1769 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1770 logger('diaspora_message: verification failed.');
1774 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1776 intval($importer['uid'])
1779 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1783 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')",
1784 intval($importer['uid']),
1786 intval($conversation['id']),
1787 dbesc($person['name']),
1788 dbesc($person['photo']),
1789 dbesc($person['url']),
1790 intval($contact['id']),
1791 dbesc($conversation['subject']),
1797 dbesc($msg_created_at)
1800 q("update conv set updated = '%s' where id = %d",
1801 dbesc(datetime_convert()),
1802 intval($conversation['id'])
1809 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1813 logger('diaspora_photo: init',LOGGER_DEBUG);
1815 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1817 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1819 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1821 $guid = notags(unxmlify($xml->guid));
1823 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1825 $public = notags(unxmlify($xml->public));
1827 $created_at = notags(unxmlify($xml_created_at));
1829 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1831 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1833 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1837 if(! diaspora_post_allow($importer,$contact)) {
1838 logger('diaspora_photo: Ignoring this author.');
1842 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1843 intval($importer['uid']),
1844 dbesc($status_message_guid)
1848 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1849 intval($importer['uid']),
1850 dbesc(serialize($msg)),
1851 intval($attempt + 1)
1854 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1858 $parent_item = $r[0];
1860 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1862 $link_text = scale_external_images($link_text, true,
1863 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1865 if(strpos($parent_item['body'],$link_text) === false) {
1866 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1867 dbesc($link_text . $parent_item['body']),
1868 intval($parent_item['id']),
1869 intval($parent_item['uid'])
1871 update_thread($parent_item['id']);
1880 function diaspora_like($importer,$xml,$msg) {
1883 $guid = notags(unxmlify($xml->guid));
1884 $parent_guid = notags(unxmlify($xml->parent_guid));
1885 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1886 $target_type = notags(unxmlify($xml->target_type));
1887 $positive = notags(unxmlify($xml->positive));
1888 $author_signature = notags(unxmlify($xml->author_signature));
1890 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1892 // likes on comments not supported here and likes on photos not supported by Diaspora
1894 // if($target_type !== 'Post')
1897 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1899 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1903 if(! diaspora_post_allow($importer,$contact)) {
1904 logger('diaspora_like: Ignoring this author.');
1908 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1909 intval($importer['uid']),
1913 logger('diaspora_like: parent item not found: ' . $guid);
1917 $parent_item = $r[0];
1919 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1920 intval($importer['uid']),
1924 if($positive === 'true') {
1925 logger('diaspora_like: duplicate like: ' . $guid);
1928 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1929 // It looks like "RelayableRetractions" are used for "unlike" instead
1930 if($positive === 'false') {
1931 logger('diaspora_like: received a like with positive set to "false"...ignoring');
1932 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
1933 intval($r[0]['id']),
1934 intval($importer['uid'])
1936 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1937 // send notification via proc_run()
1941 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1942 // It looks like "RelayableRetractions" are used for "unlike" instead
1943 if($positive === 'false') {
1944 logger('diaspora_like: received a like with positive set to "false"');
1945 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1950 /* How Diaspora performs "like" signature checking:
1952 - If an item has been sent by the like author to the top-level post owner to relay on
1953 to the rest of the contacts on the top-level post, the top-level post owner should check
1954 the author_signature, then create a parent_author_signature before relaying the like on
1955 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1956 check only the parent_author_signature. Basically, they trust that the top-level post
1957 owner has already verified the authenticity of anything he/she sends out
1958 - In either case, the signature that get checked is the signature created by the person
1962 // Diaspora has changed the way they are signing the likes.
1963 // Just to make sure that we don't miss any likes we will check the old and the current way.
1964 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1966 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
1970 if ($parent_author_signature) {
1971 // If a parent_author_signature exists, then we've received the like
1972 // relayed from the top-level post owner. There's no need to check the
1973 // author_signature if the parent_author_signature is valid
1975 $parent_author_signature = base64_decode($parent_author_signature);
1977 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
1978 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
1980 logger('diaspora_like: top-level owner verification failed.');
1984 // If there's no parent_author_signature, then we've received the like
1985 // from the like creator. In that case, the person is "like"ing
1986 // our post, so he/she must be a contact of ours and his/her public key
1987 // should be in $msg['key']
1989 $author_signature = base64_decode($author_signature);
1991 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
1992 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
1994 logger('diaspora_like: like creator verification failed.');
1999 // Phew! Everything checks out. Now create an item.
2001 // Find the original comment author information.
2002 // We need this to make sure we display the comment author
2003 // information (name and avatar) correctly.
2004 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2007 $person = find_diaspora_person_by_handle($diaspora_handle);
2009 if(! is_array($person)) {
2010 logger('diaspora_like: unable to find author details');
2015 $uri = $diaspora_handle . ':' . $guid;
2017 $activity = ACTIVITY_LIKE;
2018 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2019 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2020 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2021 $body = $parent_item['body'];
2026 <type>$objtype</type>
2028 <id>{$parent_item['uri']}</id>
2031 <content>$body</content>
2034 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2039 $arr['uid'] = $importer['uid'];
2040 $arr['guid'] = $guid;
2041 $arr['network'] = NETWORK_DIASPORA;
2042 $arr['contact-id'] = $contact['id'];
2043 $arr['type'] = 'activity';
2044 $arr['wall'] = $parent_item['wall'];
2045 $arr['gravity'] = GRAVITY_LIKE;
2046 $arr['parent'] = $parent_item['id'];
2047 $arr['parent-uri'] = $parent_item['uri'];
2049 $arr['owner-name'] = $parent_item['name'];
2050 $arr['owner-link'] = $parent_item['url'];
2051 //$arr['owner-avatar'] = $parent_item['thumb'];
2052 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2054 $arr['author-name'] = $person['name'];
2055 $arr['author-link'] = $person['url'];
2056 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2058 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2059 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2060 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2061 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2062 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2064 $arr['app'] = 'Diaspora';
2066 $arr['private'] = $parent_item['private'];
2067 $arr['verb'] = $activity;
2068 $arr['object-type'] = $objtype;
2069 $arr['object'] = $obj;
2070 $arr['visible'] = 1;
2072 $arr['last-child'] = 0;
2074 $message_id = item_store($arr);
2078 // q("update item set plink = '%s' where id = %d",
2079 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2080 // dbesc($a->get_baseurl().'/display/'.$guid),
2081 // intval($message_id)
2085 if(! $parent_author_signature) {
2086 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2087 intval($message_id),
2088 dbesc($signed_data),
2089 dbesc(base64_encode($author_signature)),
2090 dbesc($diaspora_handle)
2094 // if the message isn't already being relayed, notify others
2095 // the existence of parent_author_signature means the parent_author or owner
2096 // is already relaying. The parent_item['origin'] indicates the message was created on our system
2098 if(($parent_item['origin']) && (! $parent_author_signature))
2099 proc_run('php','include/notifier.php','comment-import',$message_id);
2104 function diaspora_retraction($importer,$xml) {
2107 $guid = notags(unxmlify($xml->guid));
2108 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2109 $type = notags(unxmlify($xml->type));
2111 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2115 if($type === 'Person') {
2116 require_once('include/Contact.php');
2117 contact_remove($contact['id']);
2119 elseif($type === 'Post') {
2120 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2122 intval($importer['uid'])
2125 if(link_compare($r[0]['author-link'],$contact['url'])) {
2126 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2127 dbesc(datetime_convert()),
2130 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2139 function diaspora_signed_retraction($importer,$xml,$msg) {
2142 $guid = notags(unxmlify($xml->target_guid));
2143 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2144 $type = notags(unxmlify($xml->target_type));
2145 $sig = notags(unxmlify($xml->target_author_signature));
2147 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2149 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2151 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2156 $signed_data = $guid . ';' . $type ;
2159 /* How Diaspora performs relayable_retraction signature checking:
2161 - If an item has been sent by the item author to the top-level post owner to relay on
2162 to the rest of the contacts on the top-level post, the top-level post owner checks
2163 the author_signature, then creates a parent_author_signature before relaying the item on
2164 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2165 check only the parent_author_signature. Basically, they trust that the top-level post
2166 owner has already verified the authenticity of anything he/she sends out
2167 - In either case, the signature that get checked is the signature created by the person
2171 if($parent_author_signature) {
2173 $parent_author_signature = base64_decode($parent_author_signature);
2175 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2176 logger('diaspora_signed_retraction: top-level post owner verification failed');
2183 $sig_decode = base64_decode($sig);
2185 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2186 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2191 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2192 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2194 intval($importer['uid'])
2197 if(link_compare($r[0]['author-link'],$contact['url'])) {
2198 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2199 dbesc(datetime_convert()),
2200 dbesc(datetime_convert()),
2203 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2205 // Now check if the retraction needs to be relayed by us
2207 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2208 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2209 // The only item with `parent` and `id` as the parent id is the parent item.
2210 $p = q("select origin from item where parent = %d and id = %d limit 1",
2215 if(($p[0]['origin']) && (! $parent_author_signature)) {
2216 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2218 dbesc($signed_data),
2220 dbesc($diaspora_handle)
2223 // the existence of parent_author_signature would have meant the parent_author or owner
2224 // is already relaying.
2225 logger('diaspora_signed_retraction: relaying relayable_retraction');
2227 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2234 logger('diaspora_signed_retraction: unknown type: ' . $type);
2240 function diaspora_profile($importer,$xml,$msg) {
2243 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2246 if($diaspora_handle != $msg['author']) {
2247 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2251 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2255 if($contact['blocked']) {
2256 logger('diaspora_post: Ignoring this author.');
2260 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2261 $image_url = unxmlify($xml->image_url);
2262 $birthday = unxmlify($xml->birthday);
2263 $location = diaspora2bb(unxmlify($xml->location));
2264 $about = diaspora2bb(unxmlify($xml->bio));
2265 $gender = unxmlify($xml->gender);
2266 $tags = unxmlify($xml->tag_string);
2268 $tags = explode("#", $tags);
2270 $keywords = array();
2271 foreach ($tags as $tag) {
2272 $tag = trim(strtolower($tag));
2277 $keywords = implode(", ", $keywords);
2279 $handle_parts = explode("@", $diaspora_handle);
2281 $name = $handle_parts[0];
2284 if( preg_match("|^https?://|", $image_url) === 0) {
2285 $image_url = "http://" . $handle_parts[1] . $image_url;
2288 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2289 intval($importer['uid']),
2290 intval($contact['id'])
2292 $oldphotos = ((count($r)) ? $r : null);*/
2294 require_once('include/Photo.php');
2296 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2298 // Generic birthday. We don't know the timezone. The year is irrelevant.
2300 $birthday = str_replace('1000','1901',$birthday);
2302 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2304 // this is to prevent multiple birthday notifications in a single year
2305 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2307 if(substr($birthday,5) === substr($contact['bd'],5))
2308 $birthday = $contact['bd'];
2310 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2311 // Not doing this currently because D* protocol is scheduled for revision soon.
2313 $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",
2315 dbesc(datetime_convert()),
2319 dbesc(datetime_convert()),
2325 intval($contact['id']),
2326 intval($importer['uid'])
2329 if (unxmlify($xml->searchable) == "true") {
2330 require_once('include/socgraph.php');
2331 poco_check($contact['url'], $name, NETWORK_DIASPORA, $images[0], $about, $location, $gender, $keywords, "",
2332 datetime_convert(), 2, $contact['id'], $importer['uid']);
2336 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
2337 dbesc(normalise_link($contact['url'])));
2339 if (count($author) == 0) {
2340 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`, `location`, `about`) VALUES ('%s', '%s', '%s', '%s', '%s')",
2341 dbesc(normalise_link($contact['url'])), dbesc($name), dbesc($location), dbesc($about), dbesc($images[0]));
2343 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
2344 dbesc(normalise_link($contact['url'])));
2345 } else if (normalise_link($contact['url']).$name.$location.$about != normalise_link($author[0]["url"]).$author[0]["name"].$author[0]["location"].$author[0]["about"]) {
2346 q("UPDATE unique_contacts SET name = '%s', avatar = '%s', `location` = '%s', `about` = '%s' WHERE url = '%s'",
2347 dbesc($name), dbesc($images[0]), dbesc($location), dbesc($about), dbesc(normalise_link($contact['url'])));
2352 foreach($oldphotos as $ph) {
2353 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2354 intval($importer['uid']),
2355 intval($contact['id']),
2356 dbesc($ph['resource-id'])
2366 function diaspora_share($me,$contact) {
2368 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2369 $theiraddr = $contact['addr'];
2371 $tpl = get_markup_template('diaspora_share.tpl');
2372 $msg = replace_macros($tpl, array(
2373 '$sender' => $myaddr,
2374 '$recipient' => $theiraddr
2377 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2378 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2380 return(diaspora_transmit($owner,$contact,$slap, false));
2383 function diaspora_unshare($me,$contact) {
2386 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2388 $tpl = get_markup_template('diaspora_retract.tpl');
2389 $msg = replace_macros($tpl, array(
2390 '$guid' => $me['guid'],
2391 '$type' => 'Person',
2392 '$handle' => $myaddr
2395 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2396 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2398 return(diaspora_transmit($owner,$contact,$slap, false));
2403 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2406 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2407 $theiraddr = $contact['addr'];
2411 $title = $item['title'];
2412 $body = $item['body'];
2415 // We're trying to match Diaspora's split message/photo protocol but
2416 // all the photos are displayed on D* as links and not img's - even
2417 // though we're sending pretty much precisely what they send us when
2418 // doing the same operation.
2419 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2420 // which seems to get through intact.
2422 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2424 foreach($matches as $mtch) {
2426 $detail['str'] = $mtch[0];
2427 $detail['path'] = dirname($mtch[1]) . '/';
2428 $detail['file'] = basename($mtch[1]);
2429 $detail['guid'] = $item['guid'];
2430 $detail['handle'] = $myaddr;
2431 $images[] = $detail;
2432 $body = str_replace($detail['str'],$mtch[1],$body);
2437 //if(strlen($title))
2438 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2440 // convert to markdown
2441 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2442 //$body = bb2diaspora($body);
2446 $body = "## ".html_entity_decode($title)."\n\n".$body;
2448 if($item['attach']) {
2449 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2451 $body .= "\n" . t('Attachments:') . "\n";
2452 foreach($matches as $mtch) {
2453 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2459 $public = (($item['private']) ? 'false' : 'true');
2461 require_once('include/datetime.php');
2462 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2464 // Detect a share element and do a reshare
2465 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2466 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2467 $tpl = get_markup_template('diaspora_reshare.tpl');
2468 $msg = replace_macros($tpl, array(
2469 '$root_handle' => xmlify($ret['root_handle']),
2470 '$root_guid' => $ret['root_guid'],
2471 '$guid' => $item['guid'],
2472 '$handle' => xmlify($myaddr),
2473 '$public' => $public,
2474 '$created' => $created,
2475 '$provider' => $item["app"]
2478 $tpl = get_markup_template('diaspora_post.tpl');
2479 $msg = replace_macros($tpl, array(
2481 '$guid' => $item['guid'],
2482 '$handle' => xmlify($myaddr),
2483 '$public' => $public,
2484 '$created' => $created,
2485 '$provider' => $item["app"]
2489 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2491 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2492 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2494 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2496 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2498 if(count($images)) {
2499 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2502 return $return_code;
2505 function diaspora_is_reshare($body) {
2506 $body = trim($body);
2508 // Skip if it isn't a pure repeated messages
2509 // Does it start with a share?
2510 if (strpos($body, "[share") > 0)
2513 // Does it end with a share?
2514 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2517 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2518 // Skip if there is no shared message in there
2519 if ($body == $attributes)
2523 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2524 if ($matches[1] != "")
2525 $guid = $matches[1];
2527 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2528 if ($matches[1] != "")
2529 $guid = $matches[1];
2532 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2533 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2536 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2537 $ret["root_guid"] = $guid;
2543 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2544 if ($matches[1] != "")
2545 $profile = $matches[1];
2547 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2548 if ($matches[1] != "")
2549 $profile = $matches[1];
2553 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2554 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2558 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2559 if ($matches[1] != "")
2560 $link = $matches[1];
2562 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2563 if ($matches[1] != "")
2564 $link = $matches[1];
2566 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2567 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2573 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2575 if(! count($images))
2577 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2579 $tpl = get_markup_template('diaspora_photo.tpl');
2580 foreach($images as $image) {
2581 if(! stristr($image['path'],$mysite))
2583 $resource = str_replace('.jpg','',$image['file']);
2584 $resource = substr($resource,0,strpos($resource,'-'));
2586 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2588 intval($owner['uid'])
2592 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2593 $msg = replace_macros($tpl,array(
2594 '$path' => xmlify($image['path']),
2595 '$filename' => xmlify($image['file']),
2596 '$msg_guid' => xmlify($image['guid']),
2597 '$guid' => xmlify($r[0]['guid']),
2598 '$handle' => xmlify($image['handle']),
2599 '$public' => xmlify($public),
2600 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2604 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2605 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2606 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2608 diaspora_transmit($owner,$contact,$slap,$public_batch);
2613 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2616 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2617 // $theiraddr = $contact['addr'];
2619 // Diaspora doesn't support threaded comments, but some
2620 // versions of Diaspora (i.e. Diaspora-pistos) support
2621 // likes on comments
2622 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2623 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2624 dbesc($item['thr-parent'])
2628 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2629 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2630 // The only item with `parent` and `id` as the parent id is the parent item.
2631 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2632 intval($item['parent']),
2633 intval($item['parent'])
2641 if($item['verb'] === ACTIVITY_LIKE) {
2642 $tpl = get_markup_template('diaspora_like.tpl');
2644 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2645 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2646 // $positive = (($item['deleted']) ? 'false' : 'true');
2649 if(($item['deleted']))
2650 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2653 $tpl = get_markup_template('diaspora_comment.tpl');
2657 $text = html_entity_decode(bb2diaspora($item['body']));
2662 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2664 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2666 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2668 $msg = replace_macros($tpl,array(
2669 '$guid' => xmlify($item['guid']),
2670 '$parent_guid' => xmlify($parent['guid']),
2671 '$target_type' =>xmlify($target_type),
2672 '$authorsig' => xmlify($authorsig),
2673 '$body' => xmlify($text),
2674 '$positive' => xmlify($positive),
2675 '$handle' => xmlify($myaddr)
2678 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2680 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2681 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2683 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2687 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2691 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2692 // $theiraddr = $contact['addr'];
2694 $body = $item['body'];
2695 $text = html_entity_decode(bb2diaspora($body));
2697 // Diaspora doesn't support threaded comments, but some
2698 // versions of Diaspora (i.e. Diaspora-pistos) support
2699 // likes on comments
2700 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2701 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2702 dbesc($item['thr-parent'])
2706 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2707 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2708 // The only item with `parent` and `id` as the parent id is the parent item.
2709 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2710 intval($item['parent']),
2711 intval($item['parent'])
2720 $relay_retract = false;
2721 $sql_sign_id = 'iid';
2722 if( $item['deleted']) {
2723 $relay_retract = true;
2725 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2727 $sql_sign_id = 'retract_iid';
2728 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2730 elseif($item['verb'] === ACTIVITY_LIKE) {
2733 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2734 // $positive = (($item['deleted']) ? 'false' : 'true');
2737 $tpl = get_markup_template('diaspora_like_relay.tpl');
2739 else { // item is a comment
2740 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2744 // fetch the original signature if the relayable was created by a Diaspora
2745 // or DFRN user. Relayables for other networks are not supported.
2747 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2752 $signed_text = $orig_sign['signed_text'];
2753 $authorsig = $orig_sign['signature'];
2754 $handle = $orig_sign['signer'];
2758 // Author signature information (for likes, comments, and retractions of likes or comments,
2759 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2760 // function is called
2761 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2765 /* Since the author signature is only checked by the parent, not by the relay recipients,
2766 * I think it may not be necessary for us to do so much work to preserve all the original
2767 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2768 * Let's just generate that and forget about all the original author signature stuff.
2770 * Note: this might be more of an problem if we want to support likes on comments for older
2771 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2772 * doing that, let's ignore it for now.
2774 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2778 $handle = diaspora_handle_from_contact($item['contact-id']);
2784 $sender_signed_text = $item['guid'] . ';' . $target_type;
2786 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2788 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2790 // Sign the relayable with the top-level owner's signature
2792 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2793 // stored in the database, because that provides the best chance that Diaspora will
2794 // be able to reconstruct the signed text the same way we did. This is particularly a
2795 // concern for the comment, whose signed text includes the text of the comment. The
2796 // smallest change in the text of the comment, including removing whitespace, will
2797 // make the signature verification fail. Since we translate from BB code to Diaspora's
2798 // markup at the top of this function, which is AFTER we placed the original $signed_text
2799 // in the database, it's hazardous to trust the original $signed_text.
2801 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2803 $msg = replace_macros($tpl,array(
2804 '$guid' => xmlify($item['guid']),
2805 '$parent_guid' => xmlify($parent['guid']),
2806 '$target_type' =>xmlify($target_type),
2807 '$authorsig' => xmlify($authorsig),
2808 '$parentsig' => xmlify($parentauthorsig),
2809 '$body' => xmlify($text),
2810 '$positive' => xmlify($positive),
2811 '$handle' => xmlify($handle)
2814 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2817 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2818 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2820 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2826 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2829 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2831 // Check whether the retraction is for a top-level post or whether it's a relayable
2832 if( $item['uri'] !== $item['parent-uri'] ) {
2834 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2835 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2839 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2840 $target_type = 'StatusMessage';
2843 $signed_text = $item['guid'] . ';' . $target_type;
2845 $msg = replace_macros($tpl, array(
2846 '$guid' => xmlify($item['guid']),
2847 '$type' => xmlify($target_type),
2848 '$handle' => xmlify($myaddr),
2849 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2852 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2853 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2855 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2858 function diaspora_send_mail($item,$owner,$contact) {
2861 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2863 $r = q("select * from conv where id = %d and uid = %d limit 1",
2864 intval($item['convid']),
2865 intval($item['uid'])
2869 logger('diaspora_send_mail: conversation not found.');
2875 'guid' => xmlify($cnv['guid']),
2876 'subject' => xmlify($cnv['subject']),
2877 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2878 'diaspora_handle' => xmlify($cnv['creator']),
2879 'participant_handles' => xmlify($cnv['recips'])
2882 $body = bb2diaspora($item['body']);
2883 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2885 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2886 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2888 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2891 'guid' => xmlify($item['guid']),
2892 'parent_guid' => xmlify($cnv['guid']),
2893 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2894 'author_signature' => xmlify($sig),
2895 'text' => xmlify($body),
2896 'created_at' => xmlify($created),
2897 'diaspora_handle' => xmlify($myaddr),
2898 'conversation_guid' => xmlify($cnv['guid'])
2901 if($item['reply']) {
2902 $tpl = get_markup_template('diaspora_message.tpl');
2903 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2906 $conv['messages'] = array($msg);
2907 $tpl = get_markup_template('diaspora_conversation.tpl');
2908 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2911 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2913 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2914 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2916 return(diaspora_transmit($owner,$contact,$slap,false));
2921 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2923 $enabled = intval(get_config('system','diaspora_enabled'));
2929 $logid = random_string(4);
2930 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2932 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2936 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2938 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2942 if (!intval(get_config('system','diaspora_test'))) {
2943 post_url($dest_url . '/', $slap);
2944 $return_code = $a->get_curl_code();
2946 logger('diaspora_transmit: test_mode');
2951 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2953 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2954 logger('diaspora_transmit: queue message');
2956 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2957 intval($contact['id']),
2958 dbesc(NETWORK_DIASPORA),
2960 intval($public_batch)
2963 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2966 // queue message for redelivery
2967 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2972 return(($return_code) ? $return_code : (-1));