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');
10 function diaspora_dispatch_public($msg) {
12 $enabled = intval(get_config('system','diaspora_enabled'));
14 logger('mod-diaspora: disabled');
18 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
19 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
20 AND `account_expired` = 0 AND `account_removed` = 0 ",
21 dbesc(NETWORK_DIASPORA),
26 logger('diaspora_public: delivering to: ' . $rr['username']);
27 diaspora_dispatch($rr,$msg);
31 logger('diaspora_public: no subscribers');
36 function diaspora_dispatch($importer,$msg,$attempt=1) {
40 $enabled = intval(get_config('system','diaspora_enabled'));
42 logger('mod-diaspora: disabled');
46 // php doesn't like dashes in variable names
48 $msg['message'] = str_replace(
49 array('<activity_streams-photo>','</activity_streams-photo>'),
50 array('<asphoto>','</asphoto>'),
54 $parsed_xml = parse_xml_string($msg['message'],false);
56 $xmlbase = $parsed_xml->post;
58 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
61 if($xmlbase->request) {
62 $ret = diaspora_request($importer,$xmlbase->request);
64 elseif($xmlbase->status_message) {
65 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
67 elseif($xmlbase->profile) {
68 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
70 elseif($xmlbase->comment) {
71 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
73 elseif($xmlbase->like) {
74 $ret = diaspora_like($importer,$xmlbase->like,$msg);
76 elseif($xmlbase->asphoto) {
77 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
79 elseif($xmlbase->reshare) {
80 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
82 elseif($xmlbase->retraction) {
83 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
85 elseif($xmlbase->signed_retraction) {
86 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
88 elseif($xmlbase->relayable_retraction) {
89 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
91 elseif($xmlbase->photo) {
92 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
94 elseif($xmlbase->conversation) {
95 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
97 elseif($xmlbase->message) {
98 $ret = diaspora_message($importer,$xmlbase->message,$msg);
101 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
106 function diaspora_handle_from_contact($contact_id) {
109 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
111 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
117 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
119 if($contact['network'] === NETWORK_DIASPORA) {
120 $handle = $contact['addr'];
122 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
124 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
125 $baseurl_start = strpos($contact['url'],'://') + 3;
126 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
127 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
128 $handle = $contact['nick'] . '@' . $baseurl;
130 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
137 function diaspora_get_contact_by_handle($uid,$handle) {
138 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
139 dbesc(NETWORK_DIASPORA),
146 $handle_parts = explode("@", $handle);
147 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
148 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
159 function find_diaspora_person_by_handle($handle) {
169 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
170 dbesc(NETWORK_DIASPORA),
175 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
177 // update record occasionally so it doesn't get stale
178 $d = strtotime($person['updated'] . ' +00:00');
179 if($d < strtotime('now - 14 days'))
184 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
186 // If the person isn't in our 'fcontact' table, or if he/she is but
187 // his/her information hasn't been updated for more than 14 days, then
188 // we want to fetch the person's information from the remote server.
190 // Note that $person isn't changed by this block of code unless the
191 // person's information has been successfully fetched from the remote
192 // server. So if $person was 'false' to begin with (because he/she wasn't
193 // in the local cache), it'll stay false, and if $person held the local
194 // cache information to begin with, it'll keep that information. That way
195 // if there's a problem with the remote fetch, we can at least use our
196 // cached information--it's better than nothing.
198 if((! $person) || ($update)) {
199 // Lock the function to prevent race conditions if multiple items
200 // come in at the same time from a person who doesn't exist in
203 // Don't loop forever. On the last loop, try to create the contact
204 // whether the function is locked or not. Maybe the locking thread
205 // has died or something. At any rate, a duplicate in 'fcontact'
206 // is a much smaller problem than a deadlocked thread
207 $got_lock = lock_function('find_diaspora_person_by_handle', false);
208 if(($endlessloop + 1) >= $maxloops)
212 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
213 require_once('include/Scrape.php');
214 $r = probe_url($handle, PROBE_DIASPORA);
216 // Note that Friendica contacts can return a "Diaspora person"
217 // if Diaspora connectivity is enabled on their server
218 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
219 add_fcontact($r,$update);
223 unlock_function('find_diaspora_person_by_handle');
226 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
228 block_on_function_lock('find_diaspora_person_by_handle');
231 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
232 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
233 // The fact that the function was locked may mean that another process was creating the
234 // person's record. It could also mean another process was creating or updating an unrelated
237 // At any rate, we need to keep trying until we've either got the person or had a chance to
238 // try to fetch his/her remote information. But we don't want to block on locking the
239 // function, because if the other process is creating the record, then when we acquire the lock
240 // we'll dive right into creating another, duplicate record. We DO want to at least wait
241 // until the lock is released, so we don't flood the database with requests.
243 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
244 // we do have some information for the person
250 function get_diaspora_key($uri) {
251 logger('Fetching diaspora key for: ' . $uri);
253 $r = find_diaspora_person_by_handle($uri);
260 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
263 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
266 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
268 // $b64_data = base64_encode($msg);
269 // $b64url_data = base64url_encode($b64_data);
271 $b64url_data = base64url_encode($msg);
273 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
275 $type = 'application/xml';
276 $encoding = 'base64url';
279 $signable_data = $data . '.' . base64url_encode($type) . '.'
280 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
282 $signature = rsa_sign($signable_data,$prvkey);
283 $sig = base64url_encode($signature);
286 <?xml version='1.0' encoding='UTF-8'?>
287 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
289 <author_id>$handle</author_id>
292 <me:encoding>base64url</me:encoding>
293 <me:alg>RSA-SHA256</me:alg>
294 <me:data type="application/xml">$data</me:data>
295 <me:sig>$sig</me:sig>
300 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
308 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
312 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
314 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
316 // without a public key nothing will work
319 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
323 $inner_aes_key = random_string(32);
324 $b_inner_aes_key = base64_encode($inner_aes_key);
325 $inner_iv = random_string(16);
326 $b_inner_iv = base64_encode($inner_iv);
328 $outer_aes_key = random_string(32);
329 $b_outer_aes_key = base64_encode($outer_aes_key);
330 $outer_iv = random_string(16);
331 $b_outer_iv = base64_encode($outer_iv);
333 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
335 $padded_data = pkcs5_pad($msg,16);
336 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
338 $b64_data = base64_encode($inner_encrypted);
341 $b64url_data = base64url_encode($b64_data);
342 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
344 $type = 'application/xml';
345 $encoding = 'base64url';
348 $signable_data = $data . '.' . base64url_encode($type) . '.'
349 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
351 $signature = rsa_sign($signable_data,$prvkey);
352 $sig = base64url_encode($signature);
354 $decrypted_header = <<< EOT
357 <aes_key>$b_inner_aes_key</aes_key>
358 <author_id>$handle</author_id>
362 $decrypted_header = pkcs5_pad($decrypted_header,16);
364 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
366 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
368 $encrypted_outer_key_bundle = '';
369 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
371 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
373 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
375 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
376 'ciphertext' => base64_encode($ciphertext)));
377 $cipher_json = base64_encode($encrypted_header_json_object);
379 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
382 <?xml version='1.0' encoding='UTF-8'?>
383 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
386 <me:encoding>base64url</me:encoding>
387 <me:alg>RSA-SHA256</me:alg>
388 <me:data type="application/xml">$data</me:data>
389 <me:sig>$sig</me:sig>
394 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
401 * diaspora_decode($importer,$xml)
402 * array $importer -> from user table
403 * string $xml -> urldecoded Diaspora salmon
406 * 'message' -> decoded Diaspora XML message
407 * 'author' -> author diaspora handle
408 * 'key' -> author public key (converted to pkcs#8)
410 * Author and key are used elsewhere to save a lookup for verifying replies and likes
414 function diaspora_decode($importer,$xml) {
417 $basedom = parse_xml_string($xml);
419 $children = $basedom->children('https://joindiaspora.com/protocol');
421 if($children->header) {
423 $author_link = str_replace('acct:','',$children->header->author_id);
427 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
429 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
430 $ciphertext = base64_decode($encrypted_header->ciphertext);
432 $outer_key_bundle = '';
433 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
435 $j_outer_key_bundle = json_decode($outer_key_bundle);
437 $outer_iv = base64_decode($j_outer_key_bundle->iv);
438 $outer_key = base64_decode($j_outer_key_bundle->key);
440 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
443 $decrypted = pkcs5_unpad($decrypted);
446 * $decrypted now contains something like
449 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
450 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
455 * <name>Ryan Hughes</name>
456 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
461 * <author_id>galaxor@diaspora.priateship.org</author_id>
465 * </decrypted_header>
468 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
469 $idom = parse_xml_string($decrypted,false);
471 $inner_iv = base64_decode($idom->iv);
472 $inner_aes_key = base64_decode($idom->aes_key);
474 $author_link = str_replace('acct:','',$idom->author_id);
478 $dom = $basedom->children(NAMESPACE_SALMON_ME);
480 // figure out where in the DOM tree our data is hiding
482 if($dom->provenance->data)
483 $base = $dom->provenance;
484 elseif($dom->env->data)
490 logger('mod-diaspora: unable to locate salmon data in xml ');
491 http_status_exit(400);
495 // Stash the signature away for now. We have to find their key or it won't be good for anything.
496 $signature = base64url_decode($base->sig);
500 // strip whitespace so our data element will return to one big base64 blob
501 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
504 // stash away some other stuff for later
506 $type = $base->data[0]->attributes()->type[0];
507 $keyhash = $base->sig[0]->attributes()->keyhash[0];
508 $encoding = $base->encoding;
512 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
516 $data = base64url_decode($data);
520 $inner_decrypted = $data;
524 // Decode the encrypted blob
526 $inner_encrypted = base64_decode($data);
527 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
528 $inner_decrypted = pkcs5_unpad($inner_decrypted);
532 logger('mod-diaspora: Could not retrieve author URI.');
533 http_status_exit(400);
536 // Once we have the author URI, go to the web and try to find their public key
537 // (first this will look it up locally if it is in the fcontact cache)
538 // This will also convert diaspora public key from pkcs#1 to pkcs#8
540 logger('mod-diaspora: Fetching key for ' . $author_link );
541 $key = get_diaspora_key($author_link);
544 logger('mod-diaspora: Could not retrieve author key.');
545 http_status_exit(400);
548 $verify = rsa_verify($signed_data,$signature,$key);
551 logger('mod-diaspora: Message did not verify. Discarding.');
552 http_status_exit(400);
555 logger('mod-diaspora: Message verified.');
557 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
562 function diaspora_request($importer,$xml) {
566 $sender_handle = unxmlify($xml->sender_handle);
567 $recipient_handle = unxmlify($xml->recipient_handle);
569 if(! $sender_handle || ! $recipient_handle)
572 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
576 // perhaps we were already sharing with this person. Now they're sharing with us.
577 // That makes us friends.
579 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
580 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
581 intval(CONTACT_IS_FRIEND),
582 intval($contact['id']),
583 intval($importer['uid'])
588 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
589 intval($importer['uid'])
592 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
593 require_once('include/items.php');
595 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
596 intval($importer['uid'])
599 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
601 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
604 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
605 $arr['uid'] = $importer['uid'];
606 $arr['contact-id'] = $self[0]['id'];
608 $arr['type'] = 'wall';
611 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
612 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
613 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
614 $arr['verb'] = ACTIVITY_FRIEND;
615 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
617 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
618 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
619 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
620 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
622 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
623 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
624 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
625 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
626 $arr['object'] .= '</link></object>' . "\n";
627 $arr['last-child'] = 1;
629 $arr['allow_cid'] = $user[0]['allow_cid'];
630 $arr['allow_gid'] = $user[0]['allow_gid'];
631 $arr['deny_cid'] = $user[0]['deny_cid'];
632 $arr['deny_gid'] = $user[0]['deny_gid'];
634 $i = item_store($arr);
636 proc_run('php',"include/notifier.php","activity","$i");
645 $ret = find_diaspora_person_by_handle($sender_handle);
648 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
649 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
653 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
657 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
658 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
659 intval($importer['uid']),
660 dbesc($ret['network']),
664 dbesc(normalise_link($ret['url'])),
668 dbesc($ret['photo']),
669 dbesc($ret['pubkey']),
670 dbesc($ret['notify']),
676 // find the contact record we just created
678 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
680 if(! $contact_record) {
681 logger('diaspora_request: unable to locate newly created contact record.');
685 $g = q("select def_gid from user where uid = %d limit 1",
686 intval($importer['uid'])
688 if($g && intval($g[0]['def_gid'])) {
689 require_once('include/group.php');
690 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
693 if($importer['page-flags'] == PAGE_NORMAL) {
695 $hash = random_string() . (string) time(); // Generate a confirm_key
697 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
698 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
699 intval($importer['uid']),
700 intval($contact_record['id']),
703 dbesc( t('Sharing notification from Diaspora network')),
705 dbesc(datetime_convert())
710 // automatic friend approval
712 require_once('include/Photo.php');
714 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
716 // technically they are sharing with us (CONTACT_IS_SHARING),
717 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
718 // we are going to change the relationship and make them a follower.
720 if($importer['page-flags'] == PAGE_FREELOVE)
721 $new_relation = CONTACT_IS_FRIEND;
723 $new_relation = CONTACT_IS_FOLLOWER;
725 $r = q("UPDATE `contact` SET
732 `avatar-date` = '%s',
740 intval($new_relation),
741 dbesc(datetime_convert()),
742 dbesc(datetime_convert()),
743 dbesc(datetime_convert()),
744 intval($contact_record['id'])
747 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
749 $ret = diaspora_share($u[0],$contact_record);
755 function diaspora_post_allow($importer,$contact) {
757 // perhaps we were already sharing with this person. Now they're sharing with us.
758 // That makes us friends.
759 // Normally this should have handled by getting a request - but this could get lost
760 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
761 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
762 intval(CONTACT_IS_FRIEND),
763 intval($contact['id']),
764 intval($importer['uid'])
766 $contact['rel'] = CONTACT_IS_FRIEND;
767 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
770 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
772 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
774 if($contact['rel'] == CONTACT_IS_FOLLOWER)
775 if($importer['page-flags'] == PAGE_COMMUNITY)
781 function diaspora_post($importer,$xml,$msg) {
784 $guid = notags(unxmlify($xml->guid));
785 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
787 if($diaspora_handle != $msg['author']) {
788 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
792 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
796 if(! diaspora_post_allow($importer,$contact)) {
797 logger('diaspora_post: Ignoring this author.');
801 $message_id = $diaspora_handle . ':' . $guid;
802 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
803 intval($importer['uid']),
808 logger('diaspora_post: message exists: ' . $guid);
812 // allocate a guid on our system - we aren't fixing any collisions.
813 // we're ignoring them
815 $g = q("select * from guid where guid = '%s' limit 1",
819 q("insert into guid ( guid ) values ( '%s' )",
824 $created = unxmlify($xml->created_at);
825 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
827 $body = diaspora2bb($xml->raw_message);
829 // Add OEmbed and other information to the body
830 $body = add_page_info_to_body($body, false, true);
836 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
838 foreach($matches as $mtch) {
839 if(strlen($str_tags))
841 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
845 $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
847 $datarray['uid'] = $importer['uid'];
848 $datarray['contact-id'] = $contact['id'];
849 $datarray['wall'] = 0;
850 $datarray['network'] = NETWORK_DIASPORA;
851 $datarray['verb'] = ACTIVITY_POST;
852 $datarray['guid'] = $guid;
853 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
854 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
855 $datarray['private'] = $private;
856 $datarray['parent'] = 0;
857 $datarray['plink'] = $plink;
858 $datarray['owner-name'] = $contact['name'];
859 $datarray['owner-link'] = $contact['url'];
860 //$datarray['owner-avatar'] = $contact['thumb'];
861 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
862 $datarray['author-name'] = $contact['name'];
863 $datarray['author-link'] = $contact['url'];
864 $datarray['author-avatar'] = $contact['thumb'];
865 $datarray['body'] = $body;
866 $datarray['tag'] = $str_tags;
867 $datarray['app'] = 'Diaspora';
869 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
871 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
873 DiasporaFetchGuid($datarray);
874 $message_id = item_store($datarray);
880 function DiasporaFetchGuid($item) {
881 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
882 function ($match) use ($item){
883 return(DiasporaFetchGuidSub($match, $item));
887 function DiasporaFetchGuidSub($match, $item) {
890 $author = parse_url($item["author-link"]);
891 $authorserver = $author["scheme"]."://".$author["host"];
893 $owner = parse_url($item["owner-link"]);
894 $ownerserver = $owner["scheme"]."://".$owner["host"];
896 if (!diaspora_store_by_guid($match[1], $authorserver))
897 diaspora_store_by_guid($match[1], $ownerserver);
900 function diaspora_store_by_guid($guid, $server) {
901 require_once("include/Contact.php");
903 logger("fetching item ".$guid." from ".$server, LOGGER_DEBUG);
905 $item = diaspora_fetch_message($guid, $server);
910 $body = $item["body"];
911 $str_tags = $item["tag"];
913 $created = $item["created"];
914 $author = $item["author"];
915 $guid = $item["guid"];
916 $private = $item["private"];
918 $message_id = $author.':'.$guid;
919 $r = q("SELECT `id` FROM `item` WHERE `uid` = 0 AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
926 $person = find_diaspora_person_by_handle($author);
929 $datarray['uid'] = 0;
930 $datarray['contact-id'] = get_contact($person['url'], 0);
931 $datarray['wall'] = 0;
932 $datarray['network'] = NETWORK_DIASPORA;
933 $datarray['guid'] = $guid;
934 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
935 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
936 $datarray['private'] = $private;
937 $datarray['parent'] = 0;
938 $datarray['plink'] = 'https://'.substr($author,strpos($author,'@')+1).'/posts/'.$guid;
939 $datarray['author-name'] = $person['name'];
940 $datarray['author-link'] = $person['url'];
941 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
942 $datarray['owner-name'] = $datarray['author-name'];
943 $datarray['owner-link'] = $datarray['author-link'];
944 $datarray['owner-avatar'] = $datarray['author-avatar'];
945 $datarray['body'] = $body;
946 $datarray['tag'] = $str_tags;
947 $datarray['app'] = $app;
948 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
950 DiasporaFetchGuid($datarray);
951 $message_id = item_store($datarray);
954 // Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
959 function diaspora_fetch_message($guid, $server, $level = 0) {
966 // This will not work if the server is not a Diaspora server
967 $source_url = $server.'/p/'.$guid.'.xml';
968 $x = fetch_url($source_url);
972 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
973 $source_xml = parse_xml_string($x,false);
976 $item["app"] = 'Diaspora';
977 $item["guid"] = $guid;
980 if ($source_xml->post->status_message->created_at)
981 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
983 if ($source_xml->post->status_message->provider_display_name)
984 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
986 if ($source_xml->post->status_message->diaspora_handle)
987 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
989 if ($source_xml->post->status_message->guid)
990 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
992 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
994 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
995 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
996 $body = scale_external_images($body,false);
997 } elseif($source_xml->post->asphoto->image_url) {
998 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
999 $body = scale_external_images($body);
1000 } elseif($source_xml->post->status_message) {
1001 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1003 // Checking for embedded pictures
1004 if($source_xml->post->status_message->photo->remote_photo_path AND
1005 $source_xml->post->status_message->photo->remote_photo_name) {
1007 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1008 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1010 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1012 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1015 $body = scale_external_images($body);
1017 // Add OEmbed and other information to the body
1018 $body = add_page_info_to_body($body, false, true);
1019 } elseif($source_xml->post->reshare) {
1020 // Reshare of a reshare
1021 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1023 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1024 logger('no content found: '.print_r($source_xml,true));
1032 $item["body"] = $body;
1037 function diaspora_reshare($importer,$xml,$msg) {
1039 logger('diaspora_reshare: init: ' . print_r($xml,true));
1042 $guid = notags(unxmlify($xml->guid));
1043 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1046 if($diaspora_handle != $msg['author']) {
1047 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1051 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1055 if(! diaspora_post_allow($importer,$contact)) {
1056 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1060 $message_id = $diaspora_handle . ':' . $guid;
1061 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1062 intval($importer['uid']),
1067 logger('diaspora_reshare: message exists: ' . $guid);
1071 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1072 $orig_guid = notags(unxmlify($xml->root_guid));
1074 $create_original_post = false;
1076 // Do we already have this item?
1077 $r = q("SELECT `body`, `tag`, `app`, `author-link`, `plink` FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1079 dbesc(NETWORK_DIASPORA)
1082 logger('reshared message '.orig_guid." reshared by ".$guid.' already exists on system: '.$orig_url);
1084 // Maybe it is already a reshared item?
1085 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1086 require_once('include/api.php');
1087 if (api_share_as_retweet($r[0]))
1090 $orig_url = $a->get_baseurl().'/display/'.$orig_guid;
1098 $orig_url = 'https://'.substr($orig_author,strpos($orig_author,'@')+1).'/posts/'.$orig_guid;
1100 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1101 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1102 $item = diaspora_fetch_message($orig_guid, $server);
1105 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1106 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1107 $item = diaspora_fetch_message($orig_guid, $server);
1110 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1111 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1112 $item = diaspora_fetch_message($orig_guid, $server);
1115 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1116 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1117 $item = diaspora_fetch_message($orig_guid, $server);
1121 $body = $item["body"];
1122 $str_tags = $item["tag"];
1123 $app = $item["app"];
1124 $orig_created = $item["created"];
1125 $orig_author = $item["author"];
1126 $orig_guid = $item["guid"];
1127 $create_original_post = ($body != "");
1128 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1132 $person = find_diaspora_person_by_handle($orig_author);
1134 // allocate a guid on our system - we aren't fixing any collisions.
1135 // we're ignoring them
1137 $g = q("select * from guid where guid = '%s' limit 1",
1141 q("insert into guid ( guid ) values ( '%s' )",
1146 $created = unxmlify($xml->created_at);
1147 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1149 $datarray = array();
1151 $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
1153 $datarray['uid'] = $importer['uid'];
1154 $datarray['contact-id'] = $contact['id'];
1155 $datarray['wall'] = 0;
1156 $datarray['network'] = NETWORK_DIASPORA;
1157 $datarray['guid'] = $guid;
1158 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1159 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1160 $datarray['private'] = $private;
1161 $datarray['parent'] = 0;
1162 $datarray['plink'] = $plink;
1163 $datarray['owner-name'] = $contact['name'];
1164 $datarray['owner-link'] = $contact['url'];
1165 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1166 if (!intval(get_config('system','wall-to-wall_share'))) {
1167 $prefix = "[share author='".str_replace(array("'", "[", "]"), array("'", "[", "]"),$person['name']).
1168 "' profile='".$person['url'].
1169 "' avatar='".((x($person,'thumb')) ? $person['thumb'] : $person['photo']).
1170 "' guid='".$orig_guid.
1171 "' posted='".$orig_created.
1172 "' link='".str_replace(array("'", "[", "]"), array("'", "[", "]"),$orig_url)."']";
1173 $datarray['author-name'] = $contact['name'];
1174 $datarray['author-link'] = $contact['url'];
1175 $datarray['author-avatar'] = $contact['thumb'];
1176 $datarray['body'] = $prefix.$body."[/share]";
1178 // Let reshared messages look like wall-to-wall posts
1179 $datarray['author-name'] = $person['name'];
1180 $datarray['author-link'] = $person['url'];
1181 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1182 $datarray['body'] = $body;
1185 $datarray['tag'] = $str_tags;
1186 $datarray['app'] = $app;
1188 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1189 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1191 // Store the original item of a reshare
1192 if ($create_original_post) {
1193 require_once("include/Contact.php");
1195 $datarray2 = $datarray;
1197 $datarray2['uid'] = 0;
1198 $datarray2['contact-id'] = get_contact($person['url'], 0);
1199 $datarray2['guid'] = $orig_guid;
1200 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_author.':'.$orig_guid;
1201 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = datetime_convert('UTC','UTC',$orig_created);
1202 $datarray2['plink'] = 'https://'.substr($orig_author,strpos($orig_author,'@')+1).'/posts/'.$orig_guid;
1204 $datarray2['author-name'] = $person['name'];
1205 $datarray2['author-link'] = $person['url'];
1206 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1207 $datarray2['owner-name'] = $datarray2['author-name'];
1208 $datarray2['owner-link'] = $datarray2['author-link'];
1209 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1210 $datarray2['body'] = $body;
1212 DiasporaFetchGuid($datarray2);
1213 $message_id = item_store($datarray2);
1215 logger("Store original item ".$orig_guid." under message id ".$message_id);
1218 DiasporaFetchGuid($datarray);
1219 $message_id = item_store($datarray);
1226 function diaspora_asphoto($importer,$xml,$msg) {
1227 logger('diaspora_asphoto called');
1230 $guid = notags(unxmlify($xml->guid));
1231 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1233 if($diaspora_handle != $msg['author']) {
1234 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1238 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1242 if(! diaspora_post_allow($importer,$contact)) {
1243 logger('diaspora_asphoto: Ignoring this author.');
1247 $message_id = $diaspora_handle . ':' . $guid;
1248 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1249 intval($importer['uid']),
1254 logger('diaspora_asphoto: message exists: ' . $guid);
1258 // allocate a guid on our system - we aren't fixing any collisions.
1259 // we're ignoring them
1261 $g = q("select * from guid where guid = '%s' limit 1",
1265 q("insert into guid ( guid ) values ( '%s' )",
1270 $created = unxmlify($xml->created_at);
1271 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1273 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1274 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1275 $body = scale_external_images($body,false);
1277 elseif($xml->image_url) {
1278 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1279 $body = scale_external_images($body);
1282 logger('diaspora_asphoto: no photo url found.');
1286 $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
1288 $datarray = array();
1290 $datarray['uid'] = $importer['uid'];
1291 $datarray['contact-id'] = $contact['id'];
1292 $datarray['wall'] = 0;
1293 $datarray['network'] = NETWORK_DIASPORA;
1294 $datarray['guid'] = $guid;
1295 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1296 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1297 $datarray['private'] = $private;
1298 $datarray['parent'] = 0;
1299 $datarray['plink'] = $plink;
1300 $datarray['owner-name'] = $contact['name'];
1301 $datarray['owner-link'] = $contact['url'];
1302 //$datarray['owner-avatar'] = $contact['thumb'];
1303 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1304 $datarray['author-name'] = $contact['name'];
1305 $datarray['author-link'] = $contact['url'];
1306 $datarray['author-avatar'] = $contact['thumb'];
1307 $datarray['body'] = $body;
1309 $datarray['app'] = 'Diaspora/Cubbi.es';
1311 DiasporaFetchGuid($datarray);
1312 $message_id = item_store($datarray);
1315 // q("update item set plink = '%s' where id = %d",
1316 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1317 // intval($message_id)
1330 function diaspora_comment($importer,$xml,$msg) {
1333 $guid = notags(unxmlify($xml->guid));
1334 $parent_guid = notags(unxmlify($xml->parent_guid));
1335 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1336 $target_type = notags(unxmlify($xml->target_type));
1337 $text = unxmlify($xml->text);
1338 $author_signature = notags(unxmlify($xml->author_signature));
1340 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1342 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1344 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1348 if(! diaspora_post_allow($importer,$contact)) {
1349 logger('diaspora_comment: Ignoring this author.');
1353 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1354 intval($importer['uid']),
1358 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1362 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1363 intval($importer['uid']),
1367 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1370 $parent_item = $r[0];
1373 /* How Diaspora performs comment signature checking:
1375 - If an item has been sent by the comment author to the top-level post owner to relay on
1376 to the rest of the contacts on the top-level post, the top-level post owner should check
1377 the author_signature, then create a parent_author_signature before relaying the comment on
1378 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1379 check only the parent_author_signature. Basically, they trust that the top-level post
1380 owner has already verified the authenticity of anything he/she sends out
1381 - In either case, the signature that get checked is the signature created by the person
1385 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1388 if($parent_author_signature) {
1389 // If a parent_author_signature exists, then we've received the comment
1390 // relayed from the top-level post owner. There's no need to check the
1391 // author_signature if the parent_author_signature is valid
1393 $parent_author_signature = base64_decode($parent_author_signature);
1395 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1396 logger('diaspora_comment: top-level owner verification failed.');
1401 // If there's no parent_author_signature, then we've received the comment
1402 // from the comment creator. In that case, the person is commenting on
1403 // our post, so he/she must be a contact of ours and his/her public key
1404 // should be in $msg['key']
1406 $author_signature = base64_decode($author_signature);
1408 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1409 logger('diaspora_comment: comment author verification failed.');
1414 // Phew! Everything checks out. Now create an item.
1416 // Find the original comment author information.
1417 // We need this to make sure we display the comment author
1418 // information (name and avatar) correctly.
1419 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1422 $person = find_diaspora_person_by_handle($diaspora_handle);
1424 if(! is_array($person)) {
1425 logger('diaspora_comment: unable to find author details');
1430 $body = diaspora2bb($text);
1431 $message_id = $diaspora_handle . ':' . $guid;
1433 $datarray = array();
1435 $datarray['uid'] = $importer['uid'];
1436 $datarray['contact-id'] = $contact['id'];
1437 $datarray['type'] = 'remote-comment';
1438 $datarray['wall'] = $parent_item['wall'];
1439 $datarray['network'] = NETWORK_DIASPORA;
1440 $datarray['verb'] = ACTIVITY_POST;
1441 $datarray['gravity'] = GRAVITY_COMMENT;
1442 $datarray['guid'] = $guid;
1443 $datarray['uri'] = $message_id;
1444 $datarray['parent-uri'] = $parent_item['uri'];
1446 // No timestamps for comments? OK, we'll the use current time.
1447 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1448 $datarray['private'] = $parent_item['private'];
1450 $datarray['owner-name'] = $parent_item['owner-name'];
1451 $datarray['owner-link'] = $parent_item['owner-link'];
1452 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1454 $datarray['author-name'] = $person['name'];
1455 $datarray['author-link'] = $person['url'];
1456 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1457 $datarray['body'] = $body;
1459 // We can't be certain what the original app is if the message is relayed.
1460 if(($parent_item['origin']) && (! $parent_author_signature))
1461 $datarray['app'] = 'Diaspora';
1463 DiasporaFetchGuid($datarray);
1464 $message_id = item_store($datarray);
1467 //q("update item set plink = '%s' where id = %d",
1468 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1469 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1470 // intval($message_id)
1474 if(($parent_item['origin']) && (! $parent_author_signature)) {
1475 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1476 intval($message_id),
1477 dbesc($signed_data),
1478 dbesc(base64_encode($author_signature)),
1479 dbesc($diaspora_handle)
1482 // if the message isn't already being relayed, notify others
1483 // the existence of parent_author_signature means the parent_author or owner
1484 // is already relaying.
1486 proc_run('php','include/notifier.php','comment-import',$message_id);
1489 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1490 dbesc($parent_item['uri']),
1491 intval($importer['uid'])
1494 if(count($myconv)) {
1495 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1497 foreach($myconv as $conv) {
1499 // now if we find a match, it means we're in this conversation
1501 if(! link_compare($conv['author-link'],$importer_url))
1504 require_once('include/enotify.php');
1506 $conv_parent = $conv['parent'];
1509 'type' => NOTIFY_COMMENT,
1510 'notify_flags' => $importer['notify-flags'],
1511 'language' => $importer['language'],
1512 'to_name' => $importer['username'],
1513 'to_email' => $importer['email'],
1514 'uid' => $importer['uid'],
1515 'item' => $datarray,
1516 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1517 'source_name' => $datarray['author-name'],
1518 'source_link' => $datarray['author-link'],
1519 'source_photo' => $datarray['author-avatar'],
1520 'verb' => ACTIVITY_POST,
1522 'parent' => $conv_parent,
1523 'parent_uri' => $parent_uri
1526 // only send one notification
1536 function diaspora_conversation($importer,$xml,$msg) {
1540 $guid = notags(unxmlify($xml->guid));
1541 $subject = notags(unxmlify($xml->subject));
1542 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1543 $participant_handles = notags(unxmlify($xml->participant_handles));
1544 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1546 $parent_uri = $diaspora_handle . ':' . $guid;
1548 $messages = $xml->message;
1550 if(! count($messages)) {
1551 logger('diaspora_conversation: empty conversation');
1555 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1557 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1561 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1562 logger('diaspora_conversation: Ignoring this author.');
1566 $conversation = null;
1568 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1569 intval($importer['uid']),
1573 $conversation = $c[0];
1575 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1576 intval($importer['uid']),
1578 dbesc($diaspora_handle),
1579 dbesc(datetime_convert('UTC','UTC',$created_at)),
1580 dbesc(datetime_convert()),
1582 dbesc($participant_handles)
1585 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1586 intval($importer['uid']),
1590 $conversation = $c[0];
1592 if(! $conversation) {
1593 logger('diaspora_conversation: unable to create conversation.');
1597 foreach($messages as $mesg) {
1601 $msg_guid = notags(unxmlify($mesg->guid));
1602 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1603 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1604 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1605 $msg_text = unxmlify($mesg->text);
1606 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1607 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1608 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1609 if($msg_conversation_guid != $guid) {
1610 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1614 $body = diaspora2bb($msg_text);
1615 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1617 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1619 $author_signature = base64_decode($msg_author_signature);
1621 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1626 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1628 if(is_array($person) && x($person,'pubkey'))
1629 $key = $person['pubkey'];
1631 logger('diaspora_conversation: unable to find author details');
1636 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1637 logger('diaspora_conversation: verification failed.');
1641 if($msg_parent_author_signature) {
1642 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1644 $parent_author_signature = base64_decode($msg_parent_author_signature);
1648 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1649 logger('diaspora_conversation: owner verification failed.');
1654 $r = q("select id from mail where `uri` = '%s' limit 1",
1658 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1662 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')",
1663 intval($importer['uid']),
1665 intval($conversation['id']),
1666 dbesc($person['name']),
1667 dbesc($person['photo']),
1668 dbesc($person['url']),
1669 intval($contact['id']),
1676 dbesc($msg_created_at)
1679 q("update conv set updated = '%s' where id = %d",
1680 dbesc(datetime_convert()),
1681 intval($conversation['id'])
1684 require_once('include/enotify.php');
1686 'type' => NOTIFY_MAIL,
1687 'notify_flags' => $importer['notify-flags'],
1688 'language' => $importer['language'],
1689 'to_name' => $importer['username'],
1690 'to_email' => $importer['email'],
1691 'uid' =>$importer['importer_uid'],
1692 'item' => array('subject' => $subject, 'body' => $body),
1693 'source_name' => $person['name'],
1694 'source_link' => $person['url'],
1695 'source_photo' => $person['thumb'],
1696 'verb' => ACTIVITY_POST,
1704 function diaspora_message($importer,$xml,$msg) {
1708 $msg_guid = notags(unxmlify($xml->guid));
1709 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1710 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1711 $msg_author_signature = notags(unxmlify($xml->author_signature));
1712 $msg_text = unxmlify($xml->text);
1713 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1714 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1715 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1717 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1719 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1721 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1725 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1726 logger('diaspora_message: Ignoring this author.');
1730 $conversation = null;
1732 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1733 intval($importer['uid']),
1734 dbesc($msg_conversation_guid)
1737 $conversation = $c[0];
1739 logger('diaspora_message: conversation not available.');
1745 $body = diaspora2bb($msg_text);
1746 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1748 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1751 $author_signature = base64_decode($msg_author_signature);
1753 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1754 if(is_array($person) && x($person,'pubkey'))
1755 $key = $person['pubkey'];
1757 logger('diaspora_message: unable to find author details');
1761 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1762 logger('diaspora_message: verification failed.');
1766 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1768 intval($importer['uid'])
1771 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1775 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')",
1776 intval($importer['uid']),
1778 intval($conversation['id']),
1779 dbesc($person['name']),
1780 dbesc($person['photo']),
1781 dbesc($person['url']),
1782 intval($contact['id']),
1783 dbesc($conversation['subject']),
1789 dbesc($msg_created_at)
1792 q("update conv set updated = '%s' where id = %d",
1793 dbesc(datetime_convert()),
1794 intval($conversation['id'])
1801 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1805 logger('diaspora_photo: init',LOGGER_DEBUG);
1807 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1809 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1811 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1813 $guid = notags(unxmlify($xml->guid));
1815 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1817 $public = notags(unxmlify($xml->public));
1819 $created_at = notags(unxmlify($xml_created_at));
1821 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1823 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1825 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1829 if(! diaspora_post_allow($importer,$contact)) {
1830 logger('diaspora_photo: Ignoring this author.');
1834 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1835 intval($importer['uid']),
1836 dbesc($status_message_guid)
1840 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1841 intval($importer['uid']),
1842 dbesc(serialize($msg)),
1843 intval($attempt + 1)
1846 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1850 $parent_item = $r[0];
1852 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1854 $link_text = scale_external_images($link_text, true,
1855 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1857 if(strpos($parent_item['body'],$link_text) === false) {
1858 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d",
1859 dbesc($link_text . $parent_item['body']),
1860 intval($parent_item['id']),
1861 intval($parent_item['uid'])
1871 function diaspora_like($importer,$xml,$msg) {
1874 $guid = notags(unxmlify($xml->guid));
1875 $parent_guid = notags(unxmlify($xml->parent_guid));
1876 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1877 $target_type = notags(unxmlify($xml->target_type));
1878 $positive = notags(unxmlify($xml->positive));
1879 $author_signature = notags(unxmlify($xml->author_signature));
1881 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1883 // likes on comments not supported here and likes on photos not supported by Diaspora
1885 // if($target_type !== 'Post')
1888 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1890 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1894 if(! diaspora_post_allow($importer,$contact)) {
1895 logger('diaspora_like: Ignoring this author.');
1899 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1900 intval($importer['uid']),
1904 logger('diaspora_like: parent item not found: ' . $guid);
1908 $parent_item = $r[0];
1910 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1911 intval($importer['uid']),
1915 if($positive === 'true') {
1916 logger('diaspora_like: duplicate like: ' . $guid);
1919 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1920 // It looks like "RelayableRetractions" are used for "unlike" instead
1921 if($positive === 'false') {
1922 logger('diaspora_like: received a like with positive set to "false"...ignoring');
1923 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
1924 intval($r[0]['id']),
1925 intval($importer['uid'])
1927 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1928 // send notification via proc_run()
1932 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1933 // It looks like "RelayableRetractions" are used for "unlike" instead
1934 if($positive === 'false') {
1935 logger('diaspora_like: received a like with positive set to "false"');
1936 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1941 /* How Diaspora performs "like" signature checking:
1943 - If an item has been sent by the like author to the top-level post owner to relay on
1944 to the rest of the contacts on the top-level post, the top-level post owner should check
1945 the author_signature, then create a parent_author_signature before relaying the like on
1946 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1947 check only the parent_author_signature. Basically, they trust that the top-level post
1948 owner has already verified the authenticity of anything he/she sends out
1949 - In either case, the signature that get checked is the signature created by the person
1953 $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1956 if($parent_author_signature) {
1957 // If a parent_author_signature exists, then we've received the like
1958 // relayed from the top-level post owner. There's no need to check the
1959 // author_signature if the parent_author_signature is valid
1961 $parent_author_signature = base64_decode($parent_author_signature);
1963 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1964 if (intval(get_config('system','ignore_diaspora_like_signature')))
1965 logger('diaspora_like: top-level owner verification failed. Proceeding anyway.');
1967 logger('diaspora_like: top-level owner verification failed.');
1973 // If there's no parent_author_signature, then we've received the like
1974 // from the like creator. In that case, the person is "like"ing
1975 // our post, so he/she must be a contact of ours and his/her public key
1976 // should be in $msg['key']
1978 $author_signature = base64_decode($author_signature);
1980 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1981 if (intval(get_config('system','ignore_diaspora_like_signature')))
1982 logger('diaspora_like: like creator verification failed. Proceeding anyway');
1984 logger('diaspora_like: like creator verification failed.');
1990 // Phew! Everything checks out. Now create an item.
1992 // Find the original comment author information.
1993 // We need this to make sure we display the comment author
1994 // information (name and avatar) correctly.
1995 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1998 $person = find_diaspora_person_by_handle($diaspora_handle);
2000 if(! is_array($person)) {
2001 logger('diaspora_like: unable to find author details');
2006 $uri = $diaspora_handle . ':' . $guid;
2008 $activity = ACTIVITY_LIKE;
2009 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2010 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2011 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2012 $body = $parent_item['body'];
2017 <type>$objtype</type>
2019 <id>{$parent_item['uri']}</id>
2022 <content>$body</content>
2025 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2030 $arr['uid'] = $importer['uid'];
2031 $arr['guid'] = $guid;
2032 $arr['network'] = NETWORK_DIASPORA;
2033 $arr['contact-id'] = $contact['id'];
2034 $arr['type'] = 'activity';
2035 $arr['wall'] = $parent_item['wall'];
2036 $arr['gravity'] = GRAVITY_LIKE;
2037 $arr['parent'] = $parent_item['id'];
2038 $arr['parent-uri'] = $parent_item['uri'];
2040 $arr['owner-name'] = $parent_item['name'];
2041 $arr['owner-link'] = $parent_item['url'];
2042 //$arr['owner-avatar'] = $parent_item['thumb'];
2043 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2045 $arr['author-name'] = $person['name'];
2046 $arr['author-link'] = $person['url'];
2047 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2049 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2050 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2051 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2052 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2053 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2055 $arr['app'] = 'Diaspora';
2057 $arr['private'] = $parent_item['private'];
2058 $arr['verb'] = $activity;
2059 $arr['object-type'] = $objtype;
2060 $arr['object'] = $obj;
2061 $arr['visible'] = 1;
2063 $arr['last-child'] = 0;
2065 $message_id = item_store($arr);
2069 // q("update item set plink = '%s' where id = %d",
2070 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2071 // dbesc($a->get_baseurl().'/display/'.$guid),
2072 // intval($message_id)
2076 if(! $parent_author_signature) {
2077 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2078 intval($message_id),
2079 dbesc($signed_data),
2080 dbesc(base64_encode($author_signature)),
2081 dbesc($diaspora_handle)
2085 // if the message isn't already being relayed, notify others
2086 // the existence of parent_author_signature means the parent_author or owner
2087 // is already relaying. The parent_item['origin'] indicates the message was created on our system
2089 if(($parent_item['origin']) && (! $parent_author_signature))
2090 proc_run('php','include/notifier.php','comment-import',$message_id);
2095 function diaspora_retraction($importer,$xml) {
2098 $guid = notags(unxmlify($xml->guid));
2099 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2100 $type = notags(unxmlify($xml->type));
2102 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2106 if($type === 'Person') {
2107 require_once('include/Contact.php');
2108 contact_remove($contact['id']);
2110 elseif($type === 'Post') {
2111 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2113 intval($importer['uid'])
2116 if(link_compare($r[0]['author-link'],$contact['url'])) {
2117 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2118 dbesc(datetime_convert()),
2121 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2130 function diaspora_signed_retraction($importer,$xml,$msg) {
2133 $guid = notags(unxmlify($xml->target_guid));
2134 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2135 $type = notags(unxmlify($xml->target_type));
2136 $sig = notags(unxmlify($xml->target_author_signature));
2138 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2140 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2142 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2147 $signed_data = $guid . ';' . $type ;
2150 /* How Diaspora performs relayable_retraction signature checking:
2152 - If an item has been sent by the item author to the top-level post owner to relay on
2153 to the rest of the contacts on the top-level post, the top-level post owner checks
2154 the author_signature, then creates a parent_author_signature before relaying the item on
2155 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2156 check only the parent_author_signature. Basically, they trust that the top-level post
2157 owner has already verified the authenticity of anything he/she sends out
2158 - In either case, the signature that get checked is the signature created by the person
2162 if($parent_author_signature) {
2164 $parent_author_signature = base64_decode($parent_author_signature);
2166 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2167 logger('diaspora_signed_retraction: top-level post owner verification failed');
2174 $sig_decode = base64_decode($sig);
2176 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2177 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2182 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2183 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2185 intval($importer['uid'])
2188 if(link_compare($r[0]['author-link'],$contact['url'])) {
2189 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2190 dbesc(datetime_convert()),
2191 dbesc(datetime_convert()),
2194 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2196 // Now check if the retraction needs to be relayed by us
2198 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2199 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2200 // The only item with `parent` and `id` as the parent id is the parent item.
2201 $p = q("select origin from item where parent = %d and id = %d limit 1",
2206 if(($p[0]['origin']) && (! $parent_author_signature)) {
2207 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2209 dbesc($signed_data),
2211 dbesc($diaspora_handle)
2214 // the existence of parent_author_signature would have meant the parent_author or owner
2215 // is already relaying.
2216 logger('diaspora_signed_retraction: relaying relayable_retraction');
2218 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2225 logger('diaspora_signed_retraction: unknown type: ' . $type);
2231 function diaspora_profile($importer,$xml,$msg) {
2234 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2237 if($diaspora_handle != $msg['author']) {
2238 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2242 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2246 if($contact['blocked']) {
2247 logger('diaspora_post: Ignoring this author.');
2251 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2252 $image_url = unxmlify($xml->image_url);
2253 $birthday = unxmlify($xml->birthday);
2254 $location = diaspora2bb(unxmlify($xml->location));
2255 $about = diaspora2bb(unxmlify($xml->bio));
2256 $gender = unxmlify($xml->gender);
2257 $tags = unxmlify($xml->tag_string);
2259 $tags = explode("#", $tags);
2261 $keywords = array();
2262 foreach ($tags as $tag) {
2263 $tag = trim(strtolower($tag));
2268 $keywords = implode(", ", $keywords);
2270 $handle_parts = explode("@", $diaspora_handle);
2272 $name = $handle_parts[0];
2275 if( preg_match("|^https?://|", $image_url) === 0) {
2276 $image_url = "http://" . $handle_parts[1] . $image_url;
2279 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2280 intval($importer['uid']),
2281 intval($contact['id'])
2283 $oldphotos = ((count($r)) ? $r : null);*/
2285 require_once('include/Photo.php');
2287 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2289 // Generic birthday. We don't know the timezone. The year is irrelevant.
2291 $birthday = str_replace('1000','1901',$birthday);
2293 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2295 // this is to prevent multiple birthday notifications in a single year
2296 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2298 if(substr($birthday,5) === substr($contact['bd'],5))
2299 $birthday = $contact['bd'];
2301 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2302 // Not doing this currently because D* protocol is scheduled for revision soon.
2304 $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",
2306 dbesc(datetime_convert()),
2310 dbesc(datetime_convert()),
2316 intval($contact['id']),
2317 intval($importer['uid'])
2320 if (unxmlify($xml->searchable) == "true") {
2321 require_once('include/socgraph.php');
2322 poco_check($contact['url'], $name, NETWORK_DIASPORA, $images[0], $about, $location, $gender, $keywords, "",
2323 datetime_convert(), 2, $contact['id'], $importer['uid']);
2327 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
2328 dbesc(normalise_link($contact['url'])));
2330 if (count($author) == 0) {
2331 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`, `location`, `about`) VALUES ('%s', '%s', '%s', '%s', '%s')",
2332 dbesc(normalise_link($contact['url'])), dbesc($name), dbesc($location), dbesc($about), dbesc($images[0]));
2334 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
2335 dbesc(normalise_link($contact['url'])));
2336 } else if (normalise_link($contact['url']).$name.$location.$about != normalise_link($author[0]["url"]).$author[0]["name"].$author[0]["location"].$author[0]["about"]) {
2337 q("UPDATE unique_contacts SET name = '%s', avatar = '%s', `location` = '%s', `about` = '%s' WHERE url = '%s'",
2338 dbesc($name), dbesc($images[0]), dbesc($location), dbesc($about), dbesc(normalise_link($contact['url'])));
2343 foreach($oldphotos as $ph) {
2344 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2345 intval($importer['uid']),
2346 intval($contact['id']),
2347 dbesc($ph['resource-id'])
2357 function diaspora_share($me,$contact) {
2359 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2360 $theiraddr = $contact['addr'];
2362 $tpl = get_markup_template('diaspora_share.tpl');
2363 $msg = replace_macros($tpl, array(
2364 '$sender' => $myaddr,
2365 '$recipient' => $theiraddr
2368 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2369 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2371 return(diaspora_transmit($owner,$contact,$slap, false));
2374 function diaspora_unshare($me,$contact) {
2377 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2379 $tpl = get_markup_template('diaspora_retract.tpl');
2380 $msg = replace_macros($tpl, array(
2381 '$guid' => $me['guid'],
2382 '$type' => 'Person',
2383 '$handle' => $myaddr
2386 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2387 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2389 return(diaspora_transmit($owner,$contact,$slap, false));
2394 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2397 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2398 $theiraddr = $contact['addr'];
2402 $title = $item['title'];
2403 $body = $item['body'];
2406 // We're trying to match Diaspora's split message/photo protocol but
2407 // all the photos are displayed on D* as links and not img's - even
2408 // though we're sending pretty much precisely what they send us when
2409 // doing the same operation.
2410 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2411 // which seems to get through intact.
2413 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2415 foreach($matches as $mtch) {
2417 $detail['str'] = $mtch[0];
2418 $detail['path'] = dirname($mtch[1]) . '/';
2419 $detail['file'] = basename($mtch[1]);
2420 $detail['guid'] = $item['guid'];
2421 $detail['handle'] = $myaddr;
2422 $images[] = $detail;
2423 $body = str_replace($detail['str'],$mtch[1],$body);
2428 //if(strlen($title))
2429 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2431 // convert to markdown
2432 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2433 //$body = bb2diaspora($body);
2437 $body = "## ".html_entity_decode($title)."\n\n".$body;
2439 if($item['attach']) {
2440 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2442 $body .= "\n" . t('Attachments:') . "\n";
2443 foreach($matches as $mtch) {
2444 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2450 $public = (($item['private']) ? 'false' : 'true');
2452 require_once('include/datetime.php');
2453 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2455 // Detect a share element and do a reshare
2456 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2457 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2458 $tpl = get_markup_template('diaspora_reshare.tpl');
2459 $msg = replace_macros($tpl, array(
2460 '$root_handle' => xmlify($ret['root_handle']),
2461 '$root_guid' => $ret['root_guid'],
2462 '$guid' => $item['guid'],
2463 '$handle' => xmlify($myaddr),
2464 '$public' => $public,
2465 '$created' => $created,
2466 '$provider' => $item["app"]
2469 $tpl = get_markup_template('diaspora_post.tpl');
2470 $msg = replace_macros($tpl, array(
2472 '$guid' => $item['guid'],
2473 '$handle' => xmlify($myaddr),
2474 '$public' => $public,
2475 '$created' => $created,
2476 '$provider' => $item["app"]
2480 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2482 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2483 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2485 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2487 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2489 if(count($images)) {
2490 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2493 return $return_code;
2496 function diaspora_is_reshare($body) {
2497 $body = trim($body);
2499 // Skip if it isn't a pure repeated messages
2500 // Does it start with a share?
2501 if (strpos($body, "[share") > 0)
2504 // Does it end with a share?
2505 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2508 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2509 // Skip if there is no shared message in there
2510 if ($body == $attributes)
2514 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2515 if ($matches[1] != "")
2516 $profile = $matches[1];
2518 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2519 if ($matches[1] != "")
2520 $profile = $matches[1];
2524 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2525 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2529 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2530 if ($matches[1] != "")
2531 $link = $matches[1];
2533 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2534 if ($matches[1] != "")
2535 $link = $matches[1];
2537 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2538 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2544 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2546 if(! count($images))
2548 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2550 $tpl = get_markup_template('diaspora_photo.tpl');
2551 foreach($images as $image) {
2552 if(! stristr($image['path'],$mysite))
2554 $resource = str_replace('.jpg','',$image['file']);
2555 $resource = substr($resource,0,strpos($resource,'-'));
2557 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2559 intval($owner['uid'])
2563 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2564 $msg = replace_macros($tpl,array(
2565 '$path' => xmlify($image['path']),
2566 '$filename' => xmlify($image['file']),
2567 '$msg_guid' => xmlify($image['guid']),
2568 '$guid' => xmlify($r[0]['guid']),
2569 '$handle' => xmlify($image['handle']),
2570 '$public' => xmlify($public),
2571 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2575 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2576 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2577 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2579 diaspora_transmit($owner,$contact,$slap,$public_batch);
2584 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2587 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2588 // $theiraddr = $contact['addr'];
2590 // Diaspora doesn't support threaded comments, but some
2591 // versions of Diaspora (i.e. Diaspora-pistos) support
2592 // likes on comments
2593 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2594 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2595 dbesc($item['thr-parent'])
2599 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2600 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2601 // The only item with `parent` and `id` as the parent id is the parent item.
2602 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2603 intval($item['parent']),
2604 intval($item['parent'])
2612 if($item['verb'] === ACTIVITY_LIKE) {
2613 $tpl = get_markup_template('diaspora_like.tpl');
2615 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2616 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2617 // $positive = (($item['deleted']) ? 'false' : 'true');
2620 if(($item['deleted']))
2621 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2624 $tpl = get_markup_template('diaspora_comment.tpl');
2628 $text = html_entity_decode(bb2diaspora($item['body']));
2633 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2635 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2637 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2639 $msg = replace_macros($tpl,array(
2640 '$guid' => xmlify($item['guid']),
2641 '$parent_guid' => xmlify($parent['guid']),
2642 '$target_type' =>xmlify($target_type),
2643 '$authorsig' => xmlify($authorsig),
2644 '$body' => xmlify($text),
2645 '$positive' => xmlify($positive),
2646 '$handle' => xmlify($myaddr)
2649 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2651 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2652 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2654 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2658 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2662 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2663 // $theiraddr = $contact['addr'];
2665 $body = $item['body'];
2666 $text = html_entity_decode(bb2diaspora($body));
2668 // Diaspora doesn't support threaded comments, but some
2669 // versions of Diaspora (i.e. Diaspora-pistos) support
2670 // likes on comments
2671 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2672 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2673 dbesc($item['thr-parent'])
2677 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2678 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2679 // The only item with `parent` and `id` as the parent id is the parent item.
2680 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2681 intval($item['parent']),
2682 intval($item['parent'])
2691 $relay_retract = false;
2692 $sql_sign_id = 'iid';
2693 if( $item['deleted']) {
2694 $relay_retract = true;
2696 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2698 $sql_sign_id = 'retract_iid';
2699 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2701 elseif($item['verb'] === ACTIVITY_LIKE) {
2704 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2705 // $positive = (($item['deleted']) ? 'false' : 'true');
2708 $tpl = get_markup_template('diaspora_like_relay.tpl');
2710 else { // item is a comment
2711 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2715 // fetch the original signature if the relayable was created by a Diaspora
2716 // or DFRN user. Relayables for other networks are not supported.
2718 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2723 $signed_text = $orig_sign['signed_text'];
2724 $authorsig = $orig_sign['signature'];
2725 $handle = $orig_sign['signer'];
2729 // Author signature information (for likes, comments, and retractions of likes or comments,
2730 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2731 // function is called
2732 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2736 /* Since the author signature is only checked by the parent, not by the relay recipients,
2737 * I think it may not be necessary for us to do so much work to preserve all the original
2738 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2739 * Let's just generate that and forget about all the original author signature stuff.
2741 * Note: this might be more of an problem if we want to support likes on comments for older
2742 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2743 * doing that, let's ignore it for now.
2745 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2749 $handle = diaspora_handle_from_contact($item['contact-id']);
2755 $sender_signed_text = $item['guid'] . ';' . $target_type;
2757 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2759 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2761 // Sign the relayable with the top-level owner's signature
2763 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2764 // stored in the database, because that provides the best chance that Diaspora will
2765 // be able to reconstruct the signed text the same way we did. This is particularly a
2766 // concern for the comment, whose signed text includes the text of the comment. The
2767 // smallest change in the text of the comment, including removing whitespace, will
2768 // make the signature verification fail. Since we translate from BB code to Diaspora's
2769 // markup at the top of this function, which is AFTER we placed the original $signed_text
2770 // in the database, it's hazardous to trust the original $signed_text.
2772 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2774 $msg = replace_macros($tpl,array(
2775 '$guid' => xmlify($item['guid']),
2776 '$parent_guid' => xmlify($parent['guid']),
2777 '$target_type' =>xmlify($target_type),
2778 '$authorsig' => xmlify($authorsig),
2779 '$parentsig' => xmlify($parentauthorsig),
2780 '$body' => xmlify($text),
2781 '$positive' => xmlify($positive),
2782 '$handle' => xmlify($handle)
2785 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2788 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2789 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2791 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2797 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2800 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2802 // Check whether the retraction is for a top-level post or whether it's a relayable
2803 if( $item['uri'] !== $item['parent-uri'] ) {
2805 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2806 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2810 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2811 $target_type = 'StatusMessage';
2814 $signed_text = $item['guid'] . ';' . $target_type;
2816 $msg = replace_macros($tpl, array(
2817 '$guid' => xmlify($item['guid']),
2818 '$type' => xmlify($target_type),
2819 '$handle' => xmlify($myaddr),
2820 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2823 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2824 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2826 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2829 function diaspora_send_mail($item,$owner,$contact) {
2832 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2834 $r = q("select * from conv where id = %d and uid = %d limit 1",
2835 intval($item['convid']),
2836 intval($item['uid'])
2840 logger('diaspora_send_mail: conversation not found.');
2846 'guid' => xmlify($cnv['guid']),
2847 'subject' => xmlify($cnv['subject']),
2848 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2849 'diaspora_handle' => xmlify($cnv['creator']),
2850 'participant_handles' => xmlify($cnv['recips'])
2853 $body = bb2diaspora($item['body']);
2854 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2856 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2857 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2859 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2862 'guid' => xmlify($item['guid']),
2863 'parent_guid' => xmlify($cnv['guid']),
2864 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2865 'author_signature' => xmlify($sig),
2866 'text' => xmlify($body),
2867 'created_at' => xmlify($created),
2868 'diaspora_handle' => xmlify($myaddr),
2869 'conversation_guid' => xmlify($cnv['guid'])
2872 if($item['reply']) {
2873 $tpl = get_markup_template('diaspora_message.tpl');
2874 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2877 $conv['messages'] = array($msg);
2878 $tpl = get_markup_template('diaspora_conversation.tpl');
2879 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2882 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2884 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2885 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2887 return(diaspora_transmit($owner,$contact,$slap,false));
2892 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2894 $enabled = intval(get_config('system','diaspora_enabled'));
2900 $logid = random_string(4);
2901 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2903 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2907 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2909 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2913 if (!intval(get_config('system','diaspora_test'))) {
2914 post_url($dest_url . '/', $slap);
2915 $return_code = $a->get_curl_code();
2917 logger('diaspora_transmit: test_mode');
2922 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2924 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2925 logger('diaspora_transmit: queue message');
2927 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2928 intval($contact['id']),
2929 dbesc(NETWORK_DIASPORA),
2931 intval($public_batch)
2934 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2937 // queue message for redelivery
2938 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2943 return(($return_code) ? $return_code : (-1));