4 * @file include/diaspora.php
6 * @todo GET /people/9aed8882b9f64896/stream
9 require_once('include/crypto.php');
10 require_once('include/items.php');
11 require_once('include/bb2diaspora.php');
12 require_once('include/contact_selectors.php');
13 require_once('include/queue_fn.php');
14 require_once('include/lock.php');
15 require_once('include/threads.php');
16 require_once('mod/share.php');
17 require_once('include/enotify.php');
18 require_once('include/diaspora2.php');
20 function diaspora_dispatch_public($msg) {
22 $enabled = intval(get_config('system','diaspora_enabled'));
24 logger('mod-diaspora: disabled');
28 // Use a dummy importer to import the data for the public copy
29 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
30 $result = diaspora_dispatch($importer,$msg);
31 logger("Dispatcher reported ".$result, LOGGER_DEBUG);
33 // Now distribute it to the followers
34 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
35 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
36 AND `account_expired` = 0 AND `account_removed` = 0 ",
37 dbesc(NETWORK_DIASPORA),
42 logger('diaspora_public: delivering to: ' . $rr['username']);
43 diaspora_dispatch($rr,$msg);
47 logger('diaspora_public: no subscribers for '.$msg["author"].' '.print_r($msg, true));
52 function diaspora_dispatch($importer,$msg,$attempt=1) {
56 $enabled = intval(get_config('system','diaspora_enabled'));
58 logger('mod-diaspora: disabled');
64 // php doesn't like dashes in variable names
66 $msg['message'] = str_replace(
67 array('<activity_streams-photo>','</activity_streams-photo>'),
68 array('<asphoto>','</asphoto>'),
72 $parsed_xml = parse_xml_string($msg['message'],false);
74 $xmlbase = $parsed_xml->post;
76 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
79 if($xmlbase->request) {
80 $tempfile = tempnam(get_temppath(), "diaspora-request");
81 file_put_contents($tempfile, json_encode($data));
82 $ret = diaspora_request($importer,$xmlbase->request);
84 elseif($xmlbase->status_message) {
85 //$tempfile = tempnam(get_temppath(), "diaspora-status_message");
86 //file_put_contents($tempfile, json_encode($data));
87 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
89 elseif($xmlbase->profile) {
90 //$tempfile = tempnam(get_temppath(), "diaspora-profile");
91 //file_put_contents($tempfile, json_encode($data));
92 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
94 elseif($xmlbase->comment) {
95 //$tempfile = tempnam(get_temppath(), "diaspora-comment");
96 //file_put_contents($tempfile, json_encode($data));
97 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
99 elseif($xmlbase->like) {
100 //$tempfile = tempnam(get_temppath(), "diaspora-like");
101 //file_put_contents($tempfile, json_encode($data));
102 $ret = diaspora_like($importer,$xmlbase->like,$msg);
104 elseif($xmlbase->asphoto) {
105 $tempfile = tempnam(get_temppath(), "diaspora-asphoto");
106 file_put_contents($tempfile, json_encode($data));
107 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
109 elseif($xmlbase->reshare) {
110 //$tempfile = tempnam(get_temppath(), "diaspora-reshare");
111 //file_put_contents($tempfile, json_encode($data));
112 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
114 elseif($xmlbase->retraction) {
115 //$tempfile = tempnam(get_temppath(), "diaspora-retraction");
116 //file_put_contents($tempfile, json_encode($data));
117 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
119 elseif($xmlbase->signed_retraction) {
120 //$tempfile = tempnam(get_temppath(), "diaspora-signed_retraction");
121 //file_put_contents($tempfile, json_encode($data));
122 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
124 elseif($xmlbase->relayable_retraction) {
125 //$tempfile = tempnam(get_temppath(), "diaspora-relayable_retraction");
126 //file_put_contents($tempfile, json_encode($data));
127 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
129 elseif($xmlbase->photo) {
130 //$tempfile = tempnam(get_temppath(), "diaspora-photo");
131 //file_put_contents($tempfile, json_encode($data));
132 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
134 elseif($xmlbase->conversation) {
135 $tempfile = tempnam(get_temppath(), "diaspora-conversation");
136 file_put_contents($tempfile, json_encode($data));
137 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
139 elseif($xmlbase->message) {
140 $tempfile = tempnam(get_temppath(), "diaspora-message");
141 file_put_contents($tempfile, json_encode($data));
142 $ret = diaspora_message($importer,$xmlbase->message,$msg);
144 elseif($xmlbase->participation) {
145 //$tempfile = tempnam(get_temppath(), "diaspora-participation");
146 //file_put_contents($tempfile, json_encode($data));
147 $ret = diaspora_participation($importer,$xmlbase->participation);
149 elseif($xmlbase->poll_participation) {
150 //$tempfile = tempnam(get_temppath(), "diaspora-poll_participation");
151 //file_put_contents($tempfile, json_encode($data));
152 $ret = diaspora_participation($importer,$xmlbase->poll_participation);
155 $tempfile = tempnam(get_temppath(), "diaspora-unknown");
156 file_put_contents($tempfile, json_encode($data));
157 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
162 function diaspora_handle_from_contact($contact_id) {
165 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
167 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
173 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
175 if($contact['network'] === NETWORK_DIASPORA) {
176 $handle = $contact['addr'];
178 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
180 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
181 $baseurl_start = strpos($contact['url'],'://') + 3;
182 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
183 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
184 $handle = $contact['nick'] . '@' . $baseurl;
186 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
193 function diaspora_get_contact_by_handle($uid,$handle) {
194 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
195 dbesc(NETWORK_DIASPORA),
202 $handle_parts = explode("@", $handle);
203 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
204 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
215 function find_diaspora_person_by_handle($handle) {
225 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
226 dbesc(NETWORK_DIASPORA),
231 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
233 // update record occasionally so it doesn't get stale
234 $d = strtotime($person['updated'] . ' +00:00');
235 if($d < strtotime('now - 14 days'))
240 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
242 // If the person isn't in our 'fcontact' table, or if he/she is but
243 // his/her information hasn't been updated for more than 14 days, then
244 // we want to fetch the person's information from the remote server.
246 // Note that $person isn't changed by this block of code unless the
247 // person's information has been successfully fetched from the remote
248 // server. So if $person was 'false' to begin with (because he/she wasn't
249 // in the local cache), it'll stay false, and if $person held the local
250 // cache information to begin with, it'll keep that information. That way
251 // if there's a problem with the remote fetch, we can at least use our
252 // cached information--it's better than nothing.
254 if((! $person) || ($update)) {
255 // Lock the function to prevent race conditions if multiple items
256 // come in at the same time from a person who doesn't exist in
259 // Don't loop forever. On the last loop, try to create the contact
260 // whether the function is locked or not. Maybe the locking thread
261 // has died or something. At any rate, a duplicate in 'fcontact'
262 // is a much smaller problem than a deadlocked thread
263 $got_lock = lock_function('find_diaspora_person_by_handle', false);
264 if(($endlessloop + 1) >= $maxloops)
268 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
269 require_once('include/Scrape.php');
270 $r = probe_url($handle, PROBE_DIASPORA);
272 // Note that Friendica contacts can return a "Diaspora person"
273 // if Diaspora connectivity is enabled on their server
274 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
275 add_fcontact($r,$update);
279 unlock_function('find_diaspora_person_by_handle');
282 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
284 block_on_function_lock('find_diaspora_person_by_handle');
287 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
288 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
289 // The fact that the function was locked may mean that another process was creating the
290 // person's record. It could also mean another process was creating or updating an unrelated
293 // At any rate, we need to keep trying until we've either got the person or had a chance to
294 // try to fetch his/her remote information. But we don't want to block on locking the
295 // function, because if the other process is creating the record, then when we acquire the lock
296 // we'll dive right into creating another, duplicate record. We DO want to at least wait
297 // until the lock is released, so we don't flood the database with requests.
299 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
300 // we do have some information for the person
306 function get_diaspora_key($uri) {
307 logger('Fetching diaspora key for: ' . $uri);
309 $r = find_diaspora_person_by_handle($uri);
316 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
319 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
322 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
324 // $b64_data = base64_encode($msg);
325 // $b64url_data = base64url_encode($b64_data);
327 $b64url_data = base64url_encode($msg);
329 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
331 $type = 'application/xml';
332 $encoding = 'base64url';
335 $signable_data = $data . '.' . base64url_encode($type) . '.'
336 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
338 $signature = rsa_sign($signable_data,$prvkey);
339 $sig = base64url_encode($signature);
342 <?xml version='1.0' encoding='UTF-8'?>
343 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
345 <author_id>$handle</author_id>
348 <me:encoding>base64url</me:encoding>
349 <me:alg>RSA-SHA256</me:alg>
350 <me:data type="application/xml">$data</me:data>
351 <me:sig>$sig</me:sig>
356 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
364 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
368 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
370 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
372 // without a public key nothing will work
375 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
379 $inner_aes_key = random_string(32);
380 $b_inner_aes_key = base64_encode($inner_aes_key);
381 $inner_iv = random_string(16);
382 $b_inner_iv = base64_encode($inner_iv);
384 $outer_aes_key = random_string(32);
385 $b_outer_aes_key = base64_encode($outer_aes_key);
386 $outer_iv = random_string(16);
387 $b_outer_iv = base64_encode($outer_iv);
389 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
391 $padded_data = pkcs5_pad($msg,16);
392 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
394 $b64_data = base64_encode($inner_encrypted);
397 $b64url_data = base64url_encode($b64_data);
398 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
400 $type = 'application/xml';
401 $encoding = 'base64url';
404 $signable_data = $data . '.' . base64url_encode($type) . '.'
405 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
407 $signature = rsa_sign($signable_data,$prvkey);
408 $sig = base64url_encode($signature);
410 $decrypted_header = <<< EOT
413 <aes_key>$b_inner_aes_key</aes_key>
414 <author_id>$handle</author_id>
418 $decrypted_header = pkcs5_pad($decrypted_header,16);
420 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
422 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
424 $encrypted_outer_key_bundle = '';
425 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
427 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
429 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
431 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
432 'ciphertext' => base64_encode($ciphertext)));
433 $cipher_json = base64_encode($encrypted_header_json_object);
435 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
438 <?xml version='1.0' encoding='UTF-8'?>
439 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
442 <me:encoding>base64url</me:encoding>
443 <me:alg>RSA-SHA256</me:alg>
444 <me:data type="application/xml">$data</me:data>
445 <me:sig>$sig</me:sig>
450 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
457 * diaspora_decode($importer,$xml)
458 * array $importer -> from user table
459 * string $xml -> urldecoded Diaspora salmon
462 * 'message' -> decoded Diaspora XML message
463 * 'author' -> author diaspora handle
464 * 'key' -> author public key (converted to pkcs#8)
466 * Author and key are used elsewhere to save a lookup for verifying replies and likes
470 function diaspora_decode($importer,$xml) {
472 $tempfile = tempnam(get_temppath(), "diaspora-decode");
473 file_put_contents($tempfile, json_encode(array("importer" => $importer, "xml" => $xml)));
476 $basedom = parse_xml_string($xml);
478 $children = $basedom->children('https://joindiaspora.com/protocol');
480 if($children->header) {
482 $author_link = str_replace('acct:','',$children->header->author_id);
486 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
488 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
489 $ciphertext = base64_decode($encrypted_header->ciphertext);
491 $outer_key_bundle = '';
492 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
494 $j_outer_key_bundle = json_decode($outer_key_bundle);
496 $outer_iv = base64_decode($j_outer_key_bundle->iv);
497 $outer_key = base64_decode($j_outer_key_bundle->key);
499 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
502 $decrypted = pkcs5_unpad($decrypted);
505 * $decrypted now contains something like
508 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
509 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
514 * <name>Ryan Hughes</name>
515 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
520 * <author_id>galaxor@diaspora.priateship.org</author_id>
524 * </decrypted_header>
527 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
528 $idom = parse_xml_string($decrypted,false);
530 $inner_iv = base64_decode($idom->iv);
531 $inner_aes_key = base64_decode($idom->aes_key);
533 $author_link = str_replace('acct:','',$idom->author_id);
537 $dom = $basedom->children(NAMESPACE_SALMON_ME);
539 // figure out where in the DOM tree our data is hiding
541 if($dom->provenance->data)
542 $base = $dom->provenance;
543 elseif($dom->env->data)
549 logger('mod-diaspora: unable to locate salmon data in xml ');
550 http_status_exit(400);
554 // Stash the signature away for now. We have to find their key or it won't be good for anything.
555 $signature = base64url_decode($base->sig);
559 // strip whitespace so our data element will return to one big base64 blob
560 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
563 // stash away some other stuff for later
565 $type = $base->data[0]->attributes()->type[0];
566 $keyhash = $base->sig[0]->attributes()->keyhash[0];
567 $encoding = $base->encoding;
571 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
575 $data = base64url_decode($data);
579 $inner_decrypted = $data;
583 // Decode the encrypted blob
585 $inner_encrypted = base64_decode($data);
586 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
587 $inner_decrypted = pkcs5_unpad($inner_decrypted);
591 logger('mod-diaspora: Could not retrieve author URI.');
592 http_status_exit(400);
595 // Once we have the author URI, go to the web and try to find their public key
596 // (first this will look it up locally if it is in the fcontact cache)
597 // This will also convert diaspora public key from pkcs#1 to pkcs#8
599 logger('mod-diaspora: Fetching key for ' . $author_link );
600 $key = get_diaspora_key($author_link);
603 logger('mod-diaspora: Could not retrieve author key.');
604 http_status_exit(400);
607 $verify = rsa_verify($signed_data,$signature,$key);
610 logger('mod-diaspora: Message did not verify. Discarding.');
611 http_status_exit(400);
614 logger('mod-diaspora: Message verified.');
616 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
621 function diaspora_request($importer,$xml) {
625 $sender_handle = unxmlify($xml->sender_handle);
626 $recipient_handle = unxmlify($xml->recipient_handle);
628 if(! $sender_handle || ! $recipient_handle)
631 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
635 // perhaps we were already sharing with this person. Now they're sharing with us.
636 // That makes us friends.
638 if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
639 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
640 intval(CONTACT_IS_FRIEND),
641 intval($contact['id']),
642 intval($importer['uid'])
647 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
648 intval($importer['uid'])
651 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
652 require_once('include/items.php');
654 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
655 intval($importer['uid'])
658 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
660 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
663 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
664 $arr['uid'] = $importer['uid'];
665 $arr['contact-id'] = $self[0]['id'];
667 $arr['type'] = 'wall';
670 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
671 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
672 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
673 $arr['verb'] = ACTIVITY_FRIEND;
674 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
676 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
677 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
678 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
679 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
681 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
682 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
683 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
684 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
685 $arr['object'] .= '</link></object>' . "\n";
686 $arr['last-child'] = 1;
688 $arr['allow_cid'] = $user[0]['allow_cid'];
689 $arr['allow_gid'] = $user[0]['allow_gid'];
690 $arr['deny_cid'] = $user[0]['deny_cid'];
691 $arr['deny_gid'] = $user[0]['deny_gid'];
693 $i = item_store($arr);
695 proc_run('php',"include/notifier.php","activity","$i");
704 $ret = find_diaspora_person_by_handle($sender_handle);
707 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
708 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
712 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
716 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
717 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
718 intval($importer['uid']),
719 dbesc($ret['network']),
723 dbesc(normalise_link($ret['url'])),
727 dbesc($ret['photo']),
728 dbesc($ret['pubkey']),
729 dbesc($ret['notify']),
735 // find the contact record we just created
737 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
739 if(! $contact_record) {
740 logger('diaspora_request: unable to locate newly created contact record.');
744 $def_gid = get_default_group($importer['uid'], $ret["network"]);
745 if (intval($def_gid)) {
746 require_once('include/group.php');
747 group_add_member($importer['uid'], '', $contact_record['id'], $def_gid);
750 if($importer['page-flags'] == PAGE_NORMAL) {
752 $hash = random_string() . (string) time(); // Generate a confirm_key
754 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
755 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
756 intval($importer['uid']),
757 intval($contact_record['id']),
760 dbesc( t('Sharing notification from Diaspora network')),
762 dbesc(datetime_convert())
767 // automatic friend approval
769 require_once('include/Photo.php');
771 update_contact_avatar($contact_record['photo'],$importer['uid'],$contact_record['id']);
773 // technically they are sharing with us (CONTACT_IS_SHARING),
774 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
775 // we are going to change the relationship and make them a follower.
777 if($importer['page-flags'] == PAGE_FREELOVE)
778 $new_relation = CONTACT_IS_FRIEND;
780 $new_relation = CONTACT_IS_FOLLOWER;
782 $r = q("UPDATE `contact` SET `rel` = %d,
790 intval($new_relation),
791 dbesc(datetime_convert()),
792 dbesc(datetime_convert()),
793 intval($contact_record['id'])
796 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
798 $ret = diaspora_share($u[0],$contact_record);
804 function diaspora_post_allow($importer,$contact, $is_comment = false) {
806 // perhaps we were already sharing with this person. Now they're sharing with us.
807 // That makes us friends.
808 // Normally this should have handled by getting a request - but this could get lost
809 if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
810 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
811 intval(CONTACT_IS_FRIEND),
812 intval($contact['id']),
813 intval($importer['uid'])
815 $contact['rel'] = CONTACT_IS_FRIEND;
816 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
819 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
821 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
823 if($contact['rel'] == CONTACT_IS_FOLLOWER)
824 if(($importer['page-flags'] == PAGE_COMMUNITY) OR $is_comment)
827 // Messages for the global users are always accepted
828 if ($importer['uid'] == 0)
834 function diaspora_is_redmatrix($url) {
835 return(strstr($url, "/channel/"));
838 function diaspora_plink($addr, $guid) {
839 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
843 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
845 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
846 // So we try another way as well.
847 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
849 $r[0]["network"] = $s[0]["network"];
851 if ($r[0]["network"] == NETWORK_DFRN)
852 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
854 if (diaspora_is_redmatrix($r[0]["url"]))
855 return $r[0]["url"]."/?f=&mid=".$guid;
857 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
860 function diaspora_repair_signature($signature, $handle = "", $level = 1) {
862 if ($signature == "")
865 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
866 $signature = base64_decode($signature);
867 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
869 // Do a recursive call to be able to fix even multiple levels
871 $signature = diaspora_repair_signature($signature, $handle, ++$level);
877 function diaspora_post($importer,$xml,$msg) {
880 $guid = notags(unxmlify($xml->guid));
881 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
883 if($diaspora_handle != $msg['author']) {
884 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
888 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
890 logger('diaspora_post: A Contact for handle '.$diaspora_handle.' and user '.$importer['uid'].' was not found');
894 if(! diaspora_post_allow($importer,$contact, false)) {
895 logger('diaspora_post: Ignoring this author.');
899 $message_id = $diaspora_handle . ':' . $guid;
900 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
901 intval($importer['uid']),
905 logger('diaspora_post: message exists: ' . $guid);
909 $created = unxmlify($xml->created_at);
910 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
912 $body = diaspora2bb($xml->raw_message);
916 $datarray["object"] = json_encode($xml);
918 if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
919 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
921 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
922 // Add OEmbed and other information to the body
923 if (!diaspora_is_redmatrix($contact['url']))
924 $body = add_page_info_to_body($body, false, true);
929 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
931 foreach($matches as $mtch) {
932 if(strlen($str_tags))
934 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
938 $plink = diaspora_plink($diaspora_handle, $guid);
940 $datarray['uid'] = $importer['uid'];
941 $datarray['contact-id'] = $contact['id'];
942 $datarray['wall'] = 0;
943 $datarray['network'] = NETWORK_DIASPORA;
944 $datarray['verb'] = ACTIVITY_POST;
945 $datarray['guid'] = $guid;
946 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
947 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
948 $datarray['private'] = $private;
949 $datarray['parent'] = 0;
950 $datarray['plink'] = $plink;
951 $datarray['owner-name'] = $contact['name'];
952 $datarray['owner-link'] = $contact['url'];
953 //$datarray['owner-avatar'] = $contact['thumb'];
954 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
955 $datarray['author-name'] = $contact['name'];
956 $datarray['author-link'] = $contact['url'];
957 $datarray['author-avatar'] = $contact['thumb'];
958 $datarray['body'] = $body;
959 $datarray['tag'] = $str_tags;
960 if ($xml->provider_display_name)
961 $datarray["app"] = unxmlify($xml->provider_display_name);
963 $datarray['app'] = 'Diaspora';
965 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
967 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
969 DiasporaFetchGuid($datarray);
970 $message_id = item_store($datarray);
972 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
978 function DiasporaFetchGuid($item) {
979 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
980 function ($match) use ($item){
981 return(DiasporaFetchGuidSub($match, $item));
985 function DiasporaFetchGuidSub($match, $item) {
988 if (!diaspora_store_by_guid($match[1], $item["author-link"]))
989 diaspora_store_by_guid($match[1], $item["owner-link"]);
992 function diaspora_store_by_guid($guid, $server, $uid = 0) {
993 require_once("include/Contact.php");
995 $serverparts = parse_url($server);
996 $server = $serverparts["scheme"]."://".$serverparts["host"];
998 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1000 $item = diaspora_fetch_message($guid, $server);
1005 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1007 $body = $item["body"];
1008 $str_tags = $item["tag"];
1009 $app = $item["app"];
1010 $created = $item["created"];
1011 $author = $item["author"];
1012 $guid = $item["guid"];
1013 $private = $item["private"];
1014 $object = $item["object"];
1015 $objecttype = $item["object-type"];
1017 $message_id = $author.':'.$guid;
1018 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1025 $person = find_diaspora_person_by_handle($author);
1027 $contact_id = get_contact($person['url'], $uid);
1029 $contacts = q("SELECT * FROM `contact` WHERE `id` = %d", intval($contact_id));
1030 $importers = q("SELECT * FROM `user` WHERE `uid` = %d", intval($uid));
1032 if ($contacts AND $importers)
1033 if(!diaspora_post_allow($importers[0],$contacts[0], false)) {
1034 logger('Ignoring author '.$person['url'].' for uid '.$uid);
1037 logger('Author '.$person['url'].' is allowed for uid '.$uid);
1039 $datarray = array();
1040 $datarray['uid'] = $uid;
1041 $datarray['contact-id'] = $contact_id;
1042 $datarray['wall'] = 0;
1043 $datarray['network'] = NETWORK_DIASPORA;
1044 $datarray['guid'] = $guid;
1045 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1046 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1047 $datarray['private'] = $private;
1048 $datarray['parent'] = 0;
1049 $datarray['plink'] = diaspora_plink($author, $guid);
1050 $datarray['author-name'] = $person['name'];
1051 $datarray['author-link'] = $person['url'];
1052 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1053 $datarray['owner-name'] = $datarray['author-name'];
1054 $datarray['owner-link'] = $datarray['author-link'];
1055 $datarray['owner-avatar'] = $datarray['author-avatar'];
1056 $datarray['body'] = $body;
1057 $datarray['tag'] = $str_tags;
1058 $datarray['app'] = $app;
1059 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1060 $datarray['object'] = $object;
1061 $datarray['object-type'] = $objecttype;
1063 if ($datarray['contact-id'] == 0)
1066 DiasporaFetchGuid($datarray);
1067 $message_id = item_store($datarray);
1070 /// Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
1075 function diaspora_fetch_message($guid, $server, $level = 0) {
1082 // This will not work if the server is not a Diaspora server
1083 $source_url = $server.'/p/'.$guid.'.xml';
1084 $x = fetch_url($source_url);
1088 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1089 $source_xml = parse_xml_string($x,false);
1092 $item["app"] = 'Diaspora';
1093 $item["guid"] = $guid;
1096 if ($source_xml->post->status_message->created_at)
1097 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1099 if ($source_xml->post->status_message->provider_display_name)
1100 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1102 if ($source_xml->post->status_message->diaspora_handle)
1103 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1105 if ($source_xml->post->status_message->guid)
1106 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1108 $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1109 $item["object"] = json_encode($source_xml->post);
1111 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1112 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1113 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1114 $body = scale_external_images($body,false);
1115 } elseif($source_xml->post->asphoto->image_url) {
1116 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1117 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1118 $body = scale_external_images($body);
1119 } elseif($source_xml->post->status_message) {
1120 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1122 // Checking for embedded pictures
1123 if($source_xml->post->status_message->photo->remote_photo_path AND
1124 $source_xml->post->status_message->photo->remote_photo_name) {
1126 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1128 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1129 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1131 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1133 logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1135 $item["object-type"] = ACTIVITY_OBJ_NOTE;
1137 $body = scale_external_images($body);
1139 // Add OEmbed and other information to the body
1140 /// @TODO It could be a repeated redmatrix item
1141 /// Then we shouldn't add further data to it
1142 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1143 $body = add_page_info_to_body($body, false, true);
1145 } elseif($source_xml->post->reshare) {
1146 // Reshare of a reshare
1147 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1149 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1150 logger('no content found: '.print_r($source_xml,true));
1154 if (trim($body) == "")
1158 $item["body"] = $body;
1163 function diaspora_reshare($importer,$xml,$msg) {
1165 logger('diaspora_reshare: init: ' . print_r($xml,true));
1168 $guid = notags(unxmlify($xml->guid));
1169 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1172 if($diaspora_handle != $msg['author']) {
1173 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1177 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1181 if(! diaspora_post_allow($importer,$contact, false)) {
1182 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1186 $message_id = $diaspora_handle . ':' . $guid;
1187 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1188 intval($importer['uid']),
1192 logger('diaspora_reshare: message exists: ' . $guid);
1196 $orig_author = notags(unxmlify($xml->root_diaspora_id));
1197 $orig_guid = notags(unxmlify($xml->root_guid));
1198 $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1200 $create_original_post = false;
1202 // Do we already have this item?
1203 $r = q("SELECT `body`, `tag`, `app`, `created`, `plink`, `object`, `object-type`, `uri` FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1205 dbesc(NETWORK_DIASPORA)
1208 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1210 // Maybe it is already a reshared item?
1211 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1212 require_once('include/api.php');
1213 if (api_share_as_retweet($r[0]))
1216 $body = $r[0]["body"];
1217 $str_tags = $r[0]["tag"];
1218 $app = $r[0]["app"];
1219 $orig_created = $r[0]["created"];
1220 $orig_plink = $r[0]["plink"];
1221 $orig_uri = $r[0]["uri"];
1222 $object = $r[0]["object"];
1223 $objecttype = $r[0]["object-type"];
1232 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1233 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1234 $item = diaspora_fetch_message($orig_guid, $server);
1237 $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1238 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1239 $item = diaspora_fetch_message($orig_guid, $server);
1242 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1243 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1244 $item = diaspora_fetch_message($orig_guid, $server);
1247 $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1248 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1249 $item = diaspora_fetch_message($orig_guid, $server);
1253 $body = $item["body"];
1254 $str_tags = $item["tag"];
1255 $app = $item["app"];
1256 $orig_created = $item["created"];
1257 $orig_author = $item["author"];
1258 $orig_guid = $item["guid"];
1259 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1260 $orig_uri = $orig_author.':'.$orig_guid;
1261 $create_original_post = ($body != "");
1262 $object = $item["object"];
1263 $objecttype = $item["object-type"];
1267 $plink = diaspora_plink($diaspora_handle, $guid);
1269 $person = find_diaspora_person_by_handle($orig_author);
1271 $created = unxmlify($xml->created_at);
1272 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1274 $datarray = array();
1276 $datarray['uid'] = $importer['uid'];
1277 $datarray['contact-id'] = $contact['id'];
1278 $datarray['wall'] = 0;
1279 $datarray['network'] = NETWORK_DIASPORA;
1280 $datarray['guid'] = $guid;
1281 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1282 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1283 $datarray['private'] = $private;
1284 $datarray['parent'] = 0;
1285 $datarray['plink'] = $plink;
1286 $datarray['owner-name'] = $contact['name'];
1287 $datarray['owner-link'] = $contact['url'];
1288 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1289 if (!intval(get_config('system','wall-to-wall_share'))) {
1290 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1292 $datarray['author-name'] = $contact['name'];
1293 $datarray['author-link'] = $contact['url'];
1294 $datarray['author-avatar'] = $contact['thumb'];
1295 $datarray['body'] = $prefix.$body."[/share]";
1297 // Let reshared messages look like wall-to-wall posts
1298 $datarray['author-name'] = $person['name'];
1299 $datarray['author-link'] = $person['url'];
1300 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1301 $datarray['body'] = $body;
1304 $datarray["object"] = json_encode($xml);
1305 $datarray['object-type'] = $objecttype;
1307 $datarray['tag'] = $str_tags;
1308 $datarray['app'] = $app;
1310 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1311 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1313 // Store the original item of a reshare
1314 if ($create_original_post) {
1315 require_once("include/Contact.php");
1317 $datarray2 = $datarray;
1319 $datarray2['uid'] = 0;
1320 $datarray2['contact-id'] = get_contact($person['url'], 0);
1321 $datarray2['guid'] = $orig_guid;
1322 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1323 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1324 $datarray2['parent'] = 0;
1325 $datarray2['plink'] = $orig_plink;
1327 $datarray2['author-name'] = $person['name'];
1328 $datarray2['author-link'] = $person['url'];
1329 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1330 $datarray2['owner-name'] = $datarray2['author-name'];
1331 $datarray2['owner-link'] = $datarray2['author-link'];
1332 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1333 $datarray2['body'] = $body;
1334 $datarray2["object"] = $object;
1336 DiasporaFetchGuid($datarray2);
1337 $message_id = item_store($datarray2);
1339 logger("Store original item ".$orig_guid." under message id ".$message_id);
1342 DiasporaFetchGuid($datarray);
1343 $message_id = item_store($datarray);
1350 function diaspora_asphoto($importer,$xml,$msg) {
1351 logger('diaspora_asphoto called');
1354 $guid = notags(unxmlify($xml->guid));
1355 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1357 if($diaspora_handle != $msg['author']) {
1358 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1362 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1366 if(! diaspora_post_allow($importer,$contact, false)) {
1367 logger('diaspora_asphoto: Ignoring this author.');
1371 $message_id = $diaspora_handle . ':' . $guid;
1372 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1373 intval($importer['uid']),
1377 logger('diaspora_asphoto: message exists: ' . $guid);
1381 $created = unxmlify($xml->created_at);
1382 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1384 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1385 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1386 $body = scale_external_images($body,false);
1388 elseif($xml->image_url) {
1389 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1390 $body = scale_external_images($body);
1393 logger('diaspora_asphoto: no photo url found.');
1397 $plink = diaspora_plink($diaspora_handle, $guid);
1399 $datarray = array();
1401 $datarray['uid'] = $importer['uid'];
1402 $datarray['contact-id'] = $contact['id'];
1403 $datarray['wall'] = 0;
1404 $datarray['network'] = NETWORK_DIASPORA;
1405 $datarray['guid'] = $guid;
1406 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1407 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1408 $datarray['private'] = $private;
1409 $datarray['parent'] = 0;
1410 $datarray['plink'] = $plink;
1411 $datarray['owner-name'] = $contact['name'];
1412 $datarray['owner-link'] = $contact['url'];
1413 //$datarray['owner-avatar'] = $contact['thumb'];
1414 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1415 $datarray['author-name'] = $contact['name'];
1416 $datarray['author-link'] = $contact['url'];
1417 $datarray['author-avatar'] = $contact['thumb'];
1418 $datarray['body'] = $body;
1419 $datarray["object"] = json_encode($xml);
1420 $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1422 $datarray['app'] = 'Diaspora/Cubbi.es';
1424 DiasporaFetchGuid($datarray);
1425 $message_id = item_store($datarray);
1428 // q("update item set plink = '%s' where id = %d",
1429 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1430 // intval($message_id)
1438 function diaspora_comment($importer,$xml,$msg) {
1441 $guid = notags(unxmlify($xml->guid));
1442 $parent_guid = notags(unxmlify($xml->parent_guid));
1443 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1444 $target_type = notags(unxmlify($xml->target_type));
1445 $text = unxmlify($xml->text);
1446 $author_signature = notags(unxmlify($xml->author_signature));
1448 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1450 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1452 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1456 if(! diaspora_post_allow($importer,$contact, true)) {
1457 logger('diaspora_comment: Ignoring this author.');
1461 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1462 intval($importer['uid']),
1466 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1470 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1471 intval($importer['uid']),
1476 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1479 $person = find_diaspora_person_by_handle($diaspora_handle);
1480 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1484 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1486 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1487 intval($importer['uid']),
1494 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1497 $parent_item = $r[0];
1500 /* How Diaspora performs comment signature checking:
1502 - If an item has been sent by the comment author to the top-level post owner to relay on
1503 to the rest of the contacts on the top-level post, the top-level post owner should check
1504 the author_signature, then create a parent_author_signature before relaying the comment on
1505 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1506 check only the parent_author_signature. Basically, they trust that the top-level post
1507 owner has already verified the authenticity of anything he/she sends out
1508 - In either case, the signature that get checked is the signature created by the person
1512 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1515 if($parent_author_signature) {
1516 // If a parent_author_signature exists, then we've received the comment
1517 // relayed from the top-level post owner. There's no need to check the
1518 // author_signature if the parent_author_signature is valid
1520 $parent_author_signature = base64_decode($parent_author_signature);
1522 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1523 logger('diaspora_comment: top-level owner verification failed.');
1528 // If there's no parent_author_signature, then we've received the comment
1529 // from the comment creator. In that case, the person is commenting on
1530 // our post, so he/she must be a contact of ours and his/her public key
1531 // should be in $msg['key']
1533 $author_signature = base64_decode($author_signature);
1535 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1536 logger('diaspora_comment: comment author verification failed.');
1541 // Phew! Everything checks out. Now create an item.
1543 // Find the original comment author information.
1544 // We need this to make sure we display the comment author
1545 // information (name and avatar) correctly.
1546 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1549 $person = find_diaspora_person_by_handle($diaspora_handle);
1551 if(! is_array($person)) {
1552 logger('diaspora_comment: unable to find author details');
1557 // Fetch the contact id - if we know this contact
1558 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1559 dbesc(normalise_link($person['url'])), intval($importer['uid']));
1562 $network = $r[0]['network'];
1564 $cid = $contact['id'];
1565 $network = NETWORK_DIASPORA;
1568 $body = diaspora2bb($text);
1569 $message_id = $diaspora_handle . ':' . $guid;
1571 $datarray = array();
1573 $datarray['uid'] = $importer['uid'];
1574 $datarray['contact-id'] = $cid;
1575 $datarray['type'] = 'remote-comment';
1576 $datarray['wall'] = $parent_item['wall'];
1577 $datarray['network'] = $network;
1578 $datarray['verb'] = ACTIVITY_POST;
1579 $datarray['gravity'] = GRAVITY_COMMENT;
1580 $datarray['guid'] = $guid;
1581 $datarray['uri'] = $message_id;
1582 $datarray['parent-uri'] = $parent_item['uri'];
1584 // No timestamps for comments? OK, we'll the use current time.
1585 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1586 $datarray['private'] = $parent_item['private'];
1588 $datarray['owner-name'] = $parent_item['owner-name'];
1589 $datarray['owner-link'] = $parent_item['owner-link'];
1590 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1592 $datarray['author-name'] = $person['name'];
1593 $datarray['author-link'] = $person['url'];
1594 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1595 $datarray['body'] = $body;
1596 $datarray["object"] = json_encode($xml);
1597 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1599 // We can't be certain what the original app is if the message is relayed.
1600 if(($parent_item['origin']) && (! $parent_author_signature))
1601 $datarray['app'] = 'Diaspora';
1603 DiasporaFetchGuid($datarray);
1604 $message_id = item_store($datarray);
1606 $datarray['id'] = $message_id;
1609 //q("update item set plink = '%s' where id = %d",
1610 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1611 // dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1612 // intval($message_id)
1616 // If we are the origin of the parent we store the original signature and notify our followers
1617 if($parent_item['origin']) {
1618 $author_signature_base64 = base64_encode($author_signature);
1619 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
1621 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1622 intval($message_id),
1623 dbesc($signed_data),
1624 dbesc($author_signature_base64),
1625 dbesc($diaspora_handle)
1629 proc_run('php','include/notifier.php','comment-import',$message_id);
1638 function diaspora_conversation($importer,$xml,$msg) {
1642 $guid = notags(unxmlify($xml->guid));
1643 $subject = notags(unxmlify($xml->subject));
1644 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1645 $participant_handles = notags(unxmlify($xml->participant_handles));
1646 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1648 $parent_uri = $diaspora_handle . ':' . $guid;
1650 $messages = $xml->message;
1652 if(! count($messages)) {
1653 logger('diaspora_conversation: empty conversation');
1657 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1659 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1663 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1664 logger('diaspora_conversation: Ignoring this author.');
1668 $conversation = null;
1670 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1671 intval($importer['uid']),
1675 $conversation = $c[0];
1677 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1678 intval($importer['uid']),
1680 dbesc($diaspora_handle),
1681 dbesc(datetime_convert('UTC','UTC',$created_at)),
1682 dbesc(datetime_convert()),
1684 dbesc($participant_handles)
1687 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1688 intval($importer['uid']),
1692 $conversation = $c[0];
1694 if(! $conversation) {
1695 logger('diaspora_conversation: unable to create conversation.');
1699 foreach($messages as $mesg) {
1703 $msg_guid = notags(unxmlify($mesg->guid));
1704 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1705 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1706 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1707 $msg_text = unxmlify($mesg->text);
1708 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1709 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1710 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1711 if($msg_conversation_guid != $guid) {
1712 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1716 $body = diaspora2bb($msg_text);
1717 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1719 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1721 $author_signature = base64_decode($msg_author_signature);
1723 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1728 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1730 if(is_array($person) && x($person,'pubkey'))
1731 $key = $person['pubkey'];
1733 logger('diaspora_conversation: unable to find author details');
1738 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1739 logger('diaspora_conversation: verification failed.');
1743 if($msg_parent_author_signature) {
1744 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1746 $parent_author_signature = base64_decode($msg_parent_author_signature);
1750 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1751 logger('diaspora_conversation: owner verification failed.');
1756 $r = q("select id from mail where `uri` = '%s' limit 1",
1760 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1764 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')",
1765 intval($importer['uid']),
1767 intval($conversation['id']),
1768 dbesc($person['name']),
1769 dbesc($person['photo']),
1770 dbesc($person['url']),
1771 intval($contact['id']),
1778 dbesc($msg_created_at)
1781 q("update conv set updated = '%s' where id = %d",
1782 dbesc(datetime_convert()),
1783 intval($conversation['id'])
1787 'type' => NOTIFY_MAIL,
1788 'notify_flags' => $importer['notify-flags'],
1789 'language' => $importer['language'],
1790 'to_name' => $importer['username'],
1791 'to_email' => $importer['email'],
1792 'uid' =>$importer['uid'],
1793 'item' => array('subject' => $subject, 'body' => $body),
1794 'source_name' => $person['name'],
1795 'source_link' => $person['url'],
1796 'source_photo' => $person['thumb'],
1797 'verb' => ACTIVITY_POST,
1805 function diaspora_message($importer,$xml,$msg) {
1809 $msg_guid = notags(unxmlify($xml->guid));
1810 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1811 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1812 $msg_author_signature = notags(unxmlify($xml->author_signature));
1813 $msg_text = unxmlify($xml->text);
1814 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1815 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1816 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1818 $parent_uri = $msg_diaspora_handle . ':' . $msg_parent_guid;
1820 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1822 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1826 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1827 logger('diaspora_message: Ignoring this author.');
1831 $conversation = null;
1833 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1834 intval($importer['uid']),
1835 dbesc($msg_conversation_guid)
1838 $conversation = $c[0];
1840 logger('diaspora_message: conversation not available.');
1846 $body = diaspora2bb($msg_text);
1847 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1849 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1852 $author_signature = base64_decode($msg_author_signature);
1854 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1855 if(is_array($person) && x($person,'pubkey'))
1856 $key = $person['pubkey'];
1858 logger('diaspora_message: unable to find author details');
1862 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1863 logger('diaspora_message: verification failed.');
1867 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1869 intval($importer['uid'])
1872 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1876 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')",
1877 intval($importer['uid']),
1879 intval($conversation['id']),
1880 dbesc($person['name']),
1881 dbesc($person['photo']),
1882 dbesc($person['url']),
1883 intval($contact['id']),
1884 dbesc($conversation['subject']),
1890 dbesc($msg_created_at)
1893 q("update conv set updated = '%s' where id = %d",
1894 dbesc(datetime_convert()),
1895 intval($conversation['id'])
1901 function diaspora_participation($importer,$xml) {
1902 logger("Unsupported message type 'participation' ".print_r($xml, true));
1905 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1909 logger('diaspora_photo: init',LOGGER_DEBUG);
1911 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1913 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1915 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1917 $guid = notags(unxmlify($xml->guid));
1919 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1921 $public = notags(unxmlify($xml->public));
1923 $created_at = notags(unxmlify($xml_created_at));
1925 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1927 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1929 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1933 if(! diaspora_post_allow($importer,$contact, false)) {
1934 logger('diaspora_photo: Ignoring this author.');
1938 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1939 intval($importer['uid']),
1940 dbesc($status_message_guid)
1943 /* deactivated by now since it can lead to multiplicated pictures in posts.
1945 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1948 $person = find_diaspora_person_by_handle($diaspora_handle);
1949 $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1953 logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1955 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1956 intval($importer['uid']),
1957 dbesc($status_message_guid)
1964 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1965 intval($importer['uid']),
1966 dbesc(serialize($msg)),
1967 intval($attempt + 1)
1971 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1975 $parent_item = $r[0];
1977 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1979 $link_text = scale_external_images($link_text, true,
1980 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1982 if(strpos($parent_item['body'],$link_text) === false) {
1984 $parent_item['body'] = $link_text . $parent_item['body'];
1986 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1987 dbesc($parent_item['body']),
1988 intval($parent_item['id']),
1989 intval($parent_item['uid'])
1991 put_item_in_cache($parent_item, true);
1992 update_thread($parent_item['id']);
2001 function diaspora_like($importer,$xml,$msg) {
2004 $guid = notags(unxmlify($xml->guid));
2005 $parent_guid = notags(unxmlify($xml->parent_guid));
2006 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2007 $target_type = notags(unxmlify($xml->target_type));
2008 $positive = notags(unxmlify($xml->positive));
2009 $author_signature = notags(unxmlify($xml->author_signature));
2011 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2013 // likes on comments not supported here and likes on photos not supported by Diaspora
2015 // if($target_type !== 'Post')
2018 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
2020 logger('diaspora_like: cannot find contact: ' . $msg['author']);
2024 if(! diaspora_post_allow($importer,$contact, false)) {
2025 logger('diaspora_like: Ignoring this author.');
2029 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2030 intval($importer['uid']),
2035 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
2038 $person = find_diaspora_person_by_handle($diaspora_handle);
2039 $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
2043 logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
2045 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2046 intval($importer['uid']),
2053 logger('diaspora_like: parent item not found: ' . $guid);
2057 $parent_item = $r[0];
2059 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2060 intval($importer['uid']),
2064 if($positive === 'true') {
2065 logger('diaspora_like: duplicate like: ' . $guid);
2068 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2069 // It looks like "RelayableRetractions" are used for "unlike" instead
2070 if($positive === 'false') {
2071 logger('diaspora_like: received a like with positive set to "false"...ignoring');
2072 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2073 intval($r[0]['id']),
2074 intval($importer['uid'])
2076 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2077 // send notification via proc_run()
2081 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2082 // It looks like "RelayableRetractions" are used for "unlike" instead
2083 if($positive === 'false') {
2084 logger('diaspora_like: received a like with positive set to "false"');
2085 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2090 /* How Diaspora performs "like" signature checking:
2092 - If an item has been sent by the like author to the top-level post owner to relay on
2093 to the rest of the contacts on the top-level post, the top-level post owner should check
2094 the author_signature, then create a parent_author_signature before relaying the like on
2095 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2096 check only the parent_author_signature. Basically, they trust that the top-level post
2097 owner has already verified the authenticity of anything he/she sends out
2098 - In either case, the signature that get checked is the signature created by the person
2102 // Diaspora has changed the way they are signing the likes.
2103 // Just to make sure that we don't miss any likes we will check the old and the current way.
2104 $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2106 $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2110 if ($parent_author_signature) {
2111 // If a parent_author_signature exists, then we've received the like
2112 // relayed from the top-level post owner. There's no need to check the
2113 // author_signature if the parent_author_signature is valid
2115 $parent_author_signature = base64_decode($parent_author_signature);
2117 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2118 !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2120 logger('diaspora_like: top-level owner verification failed.');
2124 // If there's no parent_author_signature, then we've received the like
2125 // from the like creator. In that case, the person is "like"ing
2126 // our post, so he/she must be a contact of ours and his/her public key
2127 // should be in $msg['key']
2129 $author_signature = base64_decode($author_signature);
2131 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2132 !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2134 logger('diaspora_like: like creator verification failed.');
2139 // Phew! Everything checks out. Now create an item.
2141 // Find the original comment author information.
2142 // We need this to make sure we display the comment author
2143 // information (name and avatar) correctly.
2144 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2147 $person = find_diaspora_person_by_handle($diaspora_handle);
2149 if(! is_array($person)) {
2150 logger('diaspora_like: unable to find author details');
2155 $uri = $diaspora_handle . ':' . $guid;
2157 $activity = ACTIVITY_LIKE;
2158 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2159 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2160 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2161 $body = $parent_item['body'];
2166 <type>$objtype</type>
2168 <id>{$parent_item['uri']}</id>
2171 <content>$body</content>
2174 $bodyverb = t('%1$s likes %2$s\'s %3$s');
2176 // Fetch the contact id - if we know this contact
2177 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
2178 dbesc(normalise_link($person['url'])), intval($importer['uid']));
2181 $network = $r[0]['network'];
2183 $cid = $contact['id'];
2184 $network = NETWORK_DIASPORA;
2190 $arr['uid'] = $importer['uid'];
2191 $arr['guid'] = $guid;
2192 $arr['network'] = $network;
2193 $arr['contact-id'] = $cid;
2194 $arr['type'] = 'activity';
2195 $arr['wall'] = $parent_item['wall'];
2196 $arr['gravity'] = GRAVITY_LIKE;
2197 $arr['parent'] = $parent_item['id'];
2198 $arr['parent-uri'] = $parent_item['uri'];
2200 $arr['owner-name'] = $parent_item['name'];
2201 $arr['owner-link'] = $parent_item['url'];
2202 //$arr['owner-avatar'] = $parent_item['thumb'];
2203 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2205 $arr['author-name'] = $person['name'];
2206 $arr['author-link'] = $person['url'];
2207 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2209 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2210 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2211 //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2212 $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2213 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
2215 $arr['app'] = 'Diaspora';
2217 $arr['private'] = $parent_item['private'];
2218 $arr['verb'] = $activity;
2219 $arr['object-type'] = $objtype;
2220 $arr['object'] = $obj;
2221 $arr['visible'] = 1;
2223 $arr['last-child'] = 0;
2225 $message_id = item_store($arr);
2229 // q("update item set plink = '%s' where id = %d",
2230 // //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2231 // dbesc($a->get_baseurl().'/display/'.$guid),
2232 // intval($message_id)
2236 // If we are the origin of the parent we store the original signature and notify our followers
2237 if($parent_item['origin']) {
2238 $author_signature_base64 = base64_encode($author_signature);
2239 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
2241 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2242 intval($message_id),
2243 dbesc($signed_data),
2244 dbesc($author_signature_base64),
2245 dbesc($diaspora_handle)
2249 proc_run('php','include/notifier.php','comment-import',$message_id);
2255 function diaspora_retraction($importer,$xml) {
2258 $guid = notags(unxmlify($xml->guid));
2259 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2260 $type = notags(unxmlify($xml->type));
2262 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2266 if($type === 'Person') {
2267 require_once('include/Contact.php');
2268 contact_remove($contact['id']);
2269 } elseif($type === 'StatusMessage') {
2270 $guid = notags(unxmlify($xml->post_guid));
2272 $r = q("SELECT * FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2274 intval($importer['uid'])
2277 if(link_compare($r[0]['author-link'],$contact['url'])) {
2278 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
2279 dbesc(datetime_convert()),
2282 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2285 } elseif($type === 'Post') {
2286 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2288 intval($importer['uid'])
2291 if(link_compare($r[0]['author-link'],$contact['url'])) {
2292 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2293 dbesc(datetime_convert()),
2296 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2305 function diaspora_signed_retraction($importer,$xml,$msg) {
2308 $guid = notags(unxmlify($xml->target_guid));
2309 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2310 $type = notags(unxmlify($xml->target_type));
2311 $sig = notags(unxmlify($xml->target_author_signature));
2313 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2315 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2317 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2322 $signed_data = $guid . ';' . $type ;
2325 /* How Diaspora performs relayable_retraction signature checking:
2327 - If an item has been sent by the item author to the top-level post owner to relay on
2328 to the rest of the contacts on the top-level post, the top-level post owner checks
2329 the author_signature, then creates a parent_author_signature before relaying the item on
2330 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2331 check only the parent_author_signature. Basically, they trust that the top-level post
2332 owner has already verified the authenticity of anything he/she sends out
2333 - In either case, the signature that get checked is the signature created by the person
2337 if($parent_author_signature) {
2339 $parent_author_signature = base64_decode($parent_author_signature);
2341 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2342 logger('diaspora_signed_retraction: top-level post owner verification failed');
2348 $sig_decode = base64_decode($sig);
2350 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2351 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2356 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2357 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2359 intval($importer['uid'])
2362 if(link_compare($r[0]['author-link'],$contact['url'])) {
2363 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2364 dbesc(datetime_convert()),
2365 dbesc(datetime_convert()),
2368 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2370 // Now check if the retraction needs to be relayed by us
2372 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2373 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2374 // The only item with `parent` and `id` as the parent id is the parent item.
2375 $p = q("SELECT `origin` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2376 intval($r[0]['parent']),
2377 intval($r[0]['parent'])
2380 if($p[0]['origin']) {
2381 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2383 dbesc($signed_data),
2385 dbesc($diaspora_handle)
2388 // the existence of parent_author_signature would have meant the parent_author or owner
2389 // is already relaying.
2390 logger('diaspora_signed_retraction: relaying relayable_retraction');
2392 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2399 logger('diaspora_signed_retraction: unknown type: ' . $type);
2405 function diaspora_profile($importer,$xml,$msg) {
2408 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2411 if($diaspora_handle != $msg['author']) {
2412 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2416 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2420 //if($contact['blocked']) {
2421 // logger('diaspora_post: Ignoring this author.');
2425 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2426 $image_url = unxmlify($xml->image_url);
2427 $birthday = unxmlify($xml->birthday);
2428 $location = diaspora2bb(unxmlify($xml->location));
2429 $about = diaspora2bb(unxmlify($xml->bio));
2430 $gender = unxmlify($xml->gender);
2431 $searchable = (unxmlify($xml->searchable) == "true");
2432 $nsfw = (unxmlify($xml->nsfw) == "true");
2433 $tags = unxmlify($xml->tag_string);
2435 $tags = explode("#", $tags);
2437 $keywords = array();
2438 foreach ($tags as $tag) {
2439 $tag = trim(strtolower($tag));
2444 $keywords = implode(", ", $keywords);
2446 $handle_parts = explode("@", $diaspora_handle);
2447 $nick = $handle_parts[0];
2450 $name = $handle_parts[0];
2453 if( preg_match("|^https?://|", $image_url) === 0) {
2454 $image_url = "http://" . $handle_parts[1] . $image_url;
2457 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2458 intval($importer['uid']),
2459 intval($contact['id'])
2461 $oldphotos = ((count($r)) ? $r : null);*/
2463 require_once('include/Photo.php');
2465 update_contact_avatar($image_url,$importer['uid'],$contact['id']);
2467 // Generic birthday. We don't know the timezone. The year is irrelevant.
2469 $birthday = str_replace('1000','1901',$birthday);
2471 if ($birthday != "")
2472 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2474 // this is to prevent multiple birthday notifications in a single year
2475 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2477 if(substr($birthday,5) === substr($contact['bd'],5))
2478 $birthday = $contact['bd'];
2480 /// @TODO Update name on item['author-name'] if the name changed. See consume_feed()
2481 /// (Not doing this currently because D* protocol is scheduled for revision soon).
2483 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2484 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2487 dbesc($diaspora_handle),
2488 dbesc(datetime_convert()),
2494 intval($contact['id']),
2495 intval($importer['uid'])
2499 require_once('include/socgraph.php');
2500 poco_check($contact['url'], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
2501 datetime_convert(), 2, $contact['id'], $importer['uid']);
2504 update_gcontact(array("url" => $contact['url'], "network" => NETWORK_DIASPORA, "generation" => 2,
2505 "photo" => $image_url, "name" => $name, "location" => $location,
2506 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2507 "addr" => $diaspora_handle, "nick" => $nick, "keywords" => $keywords,
2508 "hide" => !$searchable, "nsfw" => $nsfw));
2512 foreach($oldphotos as $ph) {
2513 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2514 intval($importer['uid']),
2515 intval($contact['id']),
2516 dbesc($ph['resource-id'])
2526 function diaspora_share($me,$contact) {
2528 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2529 $theiraddr = $contact['addr'];
2531 $tpl = get_markup_template('diaspora_share.tpl');
2532 $msg = replace_macros($tpl, array(
2533 '$sender' => $myaddr,
2534 '$recipient' => $theiraddr
2537 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2538 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2540 return(diaspora_transmit($owner,$contact,$slap, false));
2543 function diaspora_unshare($me,$contact) {
2546 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2548 $tpl = get_markup_template('diaspora_retract.tpl');
2549 $msg = replace_macros($tpl, array(
2550 '$guid' => $me['guid'],
2551 '$type' => 'Person',
2552 '$handle' => $myaddr
2555 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2556 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2558 return(diaspora_transmit($owner,$contact,$slap, false));
2563 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2566 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2567 $theiraddr = $contact['addr'];
2571 $title = $item['title'];
2572 $body = $item['body'];
2575 // We're trying to match Diaspora's split message/photo protocol but
2576 // all the photos are displayed on D* as links and not img's - even
2577 // though we're sending pretty much precisely what they send us when
2578 // doing the same operation.
2579 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2580 // which seems to get through intact.
2582 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2584 foreach($matches as $mtch) {
2586 $detail['str'] = $mtch[0];
2587 $detail['path'] = dirname($mtch[1]) . '/';
2588 $detail['file'] = basename($mtch[1]);
2589 $detail['guid'] = $item['guid'];
2590 $detail['handle'] = $myaddr;
2591 $images[] = $detail;
2592 $body = str_replace($detail['str'],$mtch[1],$body);
2597 //if(strlen($title))
2598 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2600 // convert to markdown
2601 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2602 //$body = bb2diaspora($body);
2606 $body = "## ".html_entity_decode($title)."\n\n".$body;
2608 if($item['attach']) {
2609 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2611 $body .= "\n" . t('Attachments:') . "\n";
2612 foreach($matches as $mtch) {
2613 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2619 $public = (($item['private']) ? 'false' : 'true');
2621 require_once('include/datetime.php');
2622 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2624 // Detect a share element and do a reshare
2625 // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2626 if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2627 $tpl = get_markup_template('diaspora_reshare.tpl');
2628 $msg = replace_macros($tpl, array(
2629 '$root_handle' => xmlify($ret['root_handle']),
2630 '$root_guid' => $ret['root_guid'],
2631 '$guid' => $item['guid'],
2632 '$handle' => xmlify($myaddr),
2633 '$public' => $public,
2634 '$created' => $created,
2635 '$provider' => $item["app"]
2638 $tpl = get_markup_template('diaspora_post.tpl');
2639 $msg = replace_macros($tpl, array(
2641 '$guid' => $item['guid'],
2642 '$handle' => xmlify($myaddr),
2643 '$public' => $public,
2644 '$created' => $created,
2645 '$provider' => $item["app"]
2649 logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2650 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2652 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2653 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2655 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']);
2657 logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2659 if(count($images)) {
2660 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2663 return $return_code;
2666 function diaspora_is_reshare($body) {
2667 $body = trim($body);
2669 // Skip if it isn't a pure repeated messages
2670 // Does it start with a share?
2671 if (strpos($body, "[share") > 0)
2674 // Does it end with a share?
2675 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2678 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2679 // Skip if there is no shared message in there
2680 if ($body == $attributes)
2684 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2685 if ($matches[1] != "")
2686 $guid = $matches[1];
2688 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2689 if ($matches[1] != "")
2690 $guid = $matches[1];
2693 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2694 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2697 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2698 $ret["root_guid"] = $guid;
2704 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2705 if ($matches[1] != "")
2706 $profile = $matches[1];
2708 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2709 if ($matches[1] != "")
2710 $profile = $matches[1];
2714 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2715 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2719 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2720 if ($matches[1] != "")
2721 $link = $matches[1];
2723 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2724 if ($matches[1] != "")
2725 $link = $matches[1];
2727 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2728 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2734 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2736 if(! count($images))
2738 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2740 $tpl = get_markup_template('diaspora_photo.tpl');
2741 foreach($images as $image) {
2742 if(! stristr($image['path'],$mysite))
2744 $resource = str_replace('.jpg','',$image['file']);
2745 $resource = substr($resource,0,strpos($resource,'-'));
2747 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2749 intval($owner['uid'])
2753 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2754 $msg = replace_macros($tpl,array(
2755 '$path' => xmlify($image['path']),
2756 '$filename' => xmlify($image['file']),
2757 '$msg_guid' => xmlify($image['guid']),
2758 '$guid' => xmlify($r[0]['guid']),
2759 '$handle' => xmlify($image['handle']),
2760 '$public' => xmlify($public),
2761 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2765 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2766 logger('send guid '.$r[0]['guid'], LOGGER_DEBUG);
2768 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2769 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2771 diaspora_transmit($owner,$contact,$slap,$public_batch,false,$r[0]['guid']);
2776 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2779 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2780 // $theiraddr = $contact['addr'];
2782 // Diaspora doesn't support threaded comments, but some
2783 // versions of Diaspora (i.e. Diaspora-pistos) support
2784 // likes on comments
2785 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2786 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2787 dbesc($item['thr-parent'])
2791 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2792 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2793 // The only item with `parent` and `id` as the parent id is the parent item.
2794 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2795 intval($item['parent']),
2796 intval($item['parent'])
2804 if($item['verb'] === ACTIVITY_LIKE) {
2805 $tpl = get_markup_template('diaspora_like.tpl');
2807 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2808 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2809 // $positive = (($item['deleted']) ? 'false' : 'true');
2812 if(($item['deleted']))
2813 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2816 $tpl = get_markup_template('diaspora_comment.tpl');
2820 $text = html_entity_decode(bb2diaspora($item['body']));
2825 $signed_text = $positive . ';' . $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $myaddr;
2827 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2829 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2831 $msg = replace_macros($tpl,array(
2832 '$guid' => xmlify($item['guid']),
2833 '$parent_guid' => xmlify($parent['guid']),
2834 '$target_type' =>xmlify($target_type),
2835 '$authorsig' => xmlify($authorsig),
2836 '$body' => xmlify($text),
2837 '$positive' => xmlify($positive),
2838 '$handle' => xmlify($myaddr)
2841 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2842 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2844 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2845 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2847 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2851 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2855 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2856 // $theiraddr = $contact['addr'];
2858 // Diaspora doesn't support threaded comments, but some
2859 // versions of Diaspora (i.e. Diaspora-pistos) support
2860 // likes on comments
2861 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2862 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2863 dbesc($item['thr-parent'])
2867 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2868 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2869 // The only item with `parent` and `id` as the parent id is the parent item.
2870 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2871 intval($item['parent']),
2872 intval($item['parent'])
2881 $relay_retract = false;
2882 $sql_sign_id = 'iid';
2883 if( $item['deleted']) {
2884 $relay_retract = true;
2886 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2888 $sql_sign_id = 'retract_iid';
2889 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2891 elseif($item['verb'] === ACTIVITY_LIKE) {
2894 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2895 // $positive = (($item['deleted']) ? 'false' : 'true');
2898 $tpl = get_markup_template('diaspora_like_relay.tpl');
2900 else { // item is a comment
2901 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2905 // fetch the original signature if the relayable was created by a Diaspora
2906 // or DFRN user. Relayables for other networks are not supported.
2908 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE " . $sql_sign_id . " = %d LIMIT 1",
2913 $signed_text = $orig_sign['signed_text'];
2914 $authorsig = $orig_sign['signature'];
2915 $handle = $orig_sign['signer'];
2917 // Split the signed text
2918 $signed_parts = explode(";", $signed_text);
2920 // Remove the parent guid
2921 array_shift($signed_parts);
2923 // Remove the comment guid
2924 array_shift($signed_parts);
2926 // Remove the handle
2927 array_pop($signed_parts);
2929 // Glue the parts together
2930 $text = implode(";", $signed_parts);
2933 // This part is meant for cases where we don't have the signatur. (Which shouldn't happen with posts from Diaspora and Friendica)
2934 // This means that the comment won't be accepted by newer Diaspora servers
2936 $body = $item['body'];
2937 $text = html_entity_decode(bb2diaspora($body));
2939 $handle = diaspora_handle_from_contact($item['contact-id']);
2944 $signed_text = $item['guid'] . ';' . $target_type;
2946 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2948 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2950 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2953 // Sign the relayable with the top-level owner's signature
2954 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2956 $msg = replace_macros($tpl,array(
2957 '$guid' => xmlify($item['guid']),
2958 '$parent_guid' => xmlify($parent['guid']),
2959 '$target_type' =>xmlify($target_type),
2960 '$authorsig' => xmlify($authorsig),
2961 '$parentsig' => xmlify($parentauthorsig),
2962 '$body' => xmlify($text),
2963 '$positive' => xmlify($positive),
2964 '$handle' => xmlify($handle)
2967 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2968 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2970 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2971 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2973 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2979 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2982 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2984 // Check whether the retraction is for a top-level post or whether it's a relayable
2985 if( $item['uri'] !== $item['parent-uri'] ) {
2987 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2988 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2992 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2993 $target_type = 'StatusMessage';
2996 $signed_text = $item['guid'] . ';' . $target_type;
2998 $msg = replace_macros($tpl, array(
2999 '$guid' => xmlify($item['guid']),
3000 '$type' => xmlify($target_type),
3001 '$handle' => xmlify($myaddr),
3002 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
3005 logger('send guid '.$item['guid'], LOGGER_DEBUG);
3007 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
3008 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
3010 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
3013 function diaspora_send_mail($item,$owner,$contact) {
3016 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
3018 $r = q("select * from conv where id = %d and uid = %d limit 1",
3019 intval($item['convid']),
3020 intval($item['uid'])
3024 logger('diaspora_send_mail: conversation not found.');
3030 'guid' => xmlify($cnv['guid']),
3031 'subject' => xmlify($cnv['subject']),
3032 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
3033 'diaspora_handle' => xmlify($cnv['creator']),
3034 'participant_handles' => xmlify($cnv['recips'])
3037 $body = bb2diaspora($item['body']);
3038 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
3040 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
3041 . $created . ';' . $myaddr . ';' . $cnv['guid'];
3043 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
3046 'guid' => xmlify($item['guid']),
3047 'parent_guid' => xmlify($cnv['guid']),
3048 'parent_author_signature' => xmlify($sig),
3049 'author_signature' => xmlify($sig),
3050 'text' => xmlify($body),
3051 'created_at' => xmlify($created),
3052 'diaspora_handle' => xmlify($myaddr),
3053 'conversation_guid' => xmlify($cnv['guid'])
3056 if($item['reply']) {
3057 $tpl = get_markup_template('diaspora_message.tpl');
3058 $xmsg = replace_macros($tpl, array('$msg' => $msg));
3061 $conv['messages'] = array($msg);
3062 $tpl = get_markup_template('diaspora_conversation.tpl');
3063 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3066 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3067 logger('send guid '.$item['guid'], LOGGER_DEBUG);
3069 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3070 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3072 return(diaspora_transmit($owner,$contact,$slap,false,false,$item['guid']));
3077 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false,$guid = "") {
3079 $enabled = intval(get_config('system','diaspora_enabled'));
3085 $logid = random_string(4);
3086 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3088 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3092 logger('diaspora_transmit: '.$logid.'-'.$guid.' '.$dest_url);
3094 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3098 if (!intval(get_config('system','diaspora_test'))) {
3099 post_url($dest_url . '/', $slap);
3100 $return_code = $a->get_curl_code();
3102 logger('diaspora_transmit: test_mode');
3107 logger('diaspora_transmit: '.$logid.'-'.$guid.' returns: '.$return_code);
3109 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3110 logger('diaspora_transmit: queue message');
3112 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3113 intval($contact['id']),
3114 dbesc(NETWORK_DIASPORA),
3116 intval($public_batch)
3119 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3122 // queue message for redelivery
3123 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3128 return(($return_code) ? $return_code : (-1));
3131 function diaspora_fetch_relay() {
3133 $serverdata = get_config("system", "relay_server");
3134 if ($serverdata == "")
3139 $servers = explode(",", $serverdata);
3141 foreach($servers AS $server) {
3142 $server = trim($server);
3143 $batch = $server."/receive/public";
3145 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3148 $addr = "relay@".str_replace("http://", "", normalise_link($server));
3150 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
3151 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
3156 dbesc(normalise_link($server)),
3158 dbesc(NETWORK_DIASPORA),
3159 intval(CONTACT_IS_FOLLOWER),
3160 dbesc(datetime_convert()),
3161 dbesc(datetime_convert()),
3162 dbesc(datetime_convert())
3165 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3167 $relay[] = $relais[0];
3169 $relay[] = $relais[0];