3 require_once('include/crypto.php');
4 require_once('include/items.php');
5 require_once('include/bb2diaspora.php');
6 require_once('include/contact_selectors.php');
7 require_once('include/queue_fn.php');
8 require_once('include/lock.php');
11 function diaspora_dispatch_public($msg) {
13 $enabled = intval(get_config('system','diaspora_enabled'));
15 logger('mod-diaspora: disabled');
19 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' ) AND `account_expired` = 0 AND `account_removed` = 0 ",
20 dbesc(NETWORK_DIASPORA),
25 logger('diaspora_public: delivering to: ' . $rr['username']);
26 diaspora_dispatch($rr,$msg);
30 logger('diaspora_public: no subscribers');
35 function diaspora_dispatch($importer,$msg) {
39 $enabled = intval(get_config('system','diaspora_enabled'));
41 logger('mod-diaspora: disabled');
45 // php doesn't like dashes in variable names
47 $msg['message'] = str_replace(
48 array('<activity_streams-photo>','</activity_streams-photo>'),
49 array('<asphoto>','</asphoto>'),
53 $parsed_xml = parse_xml_string($msg['message'],false);
55 $xmlbase = $parsed_xml->post;
57 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
60 if($xmlbase->request) {
61 $ret = diaspora_request($importer,$xmlbase->request);
63 elseif($xmlbase->status_message) {
64 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
66 elseif($xmlbase->profile) {
67 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
69 elseif($xmlbase->comment) {
70 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
72 elseif($xmlbase->like) {
73 $ret = diaspora_like($importer,$xmlbase->like,$msg);
75 elseif($xmlbase->asphoto) {
76 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
78 elseif($xmlbase->reshare) {
79 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
81 elseif($xmlbase->retraction) {
82 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
84 elseif($xmlbase->signed_retraction) {
85 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
87 elseif($xmlbase->relayable_retraction) {
88 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
90 elseif($xmlbase->photo) {
91 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
93 elseif($xmlbase->conversation) {
94 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
96 elseif($xmlbase->message) {
97 $ret = diaspora_message($importer,$xmlbase->message,$msg);
100 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
105 function diaspora_handle_from_contact($contact_id) {
108 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
110 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
116 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
118 if($contact['network'] === NETWORK_DIASPORA) {
119 $handle = $contact['addr'];
121 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
123 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
124 $baseurl_start = strpos($contact['url'],'://') + 3;
125 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
126 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
127 $handle = $contact['nick'] . '@' . $baseurl;
129 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
136 function diaspora_get_contact_by_handle($uid,$handle) {
137 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
138 dbesc(NETWORK_DIASPORA),
145 $handle_parts = explode("@", $handle);
146 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
147 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
158 function find_diaspora_person_by_handle($handle) {
168 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
169 dbesc(NETWORK_DIASPORA),
174 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
176 // update record occasionally so it doesn't get stale
177 $d = strtotime($person['updated'] . ' +00:00');
178 if($d < strtotime('now - 14 days'))
183 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
185 // If the person isn't in our 'fcontact' table, or if he/she is but
186 // his/her information hasn't been updated for more than 14 days, then
187 // we want to fetch the person's information from the remote server.
189 // Note that $person isn't changed by this block of code unless the
190 // person's information has been successfully fetched from the remote
191 // server. So if $person was 'false' to begin with (because he/she wasn't
192 // in the local cache), it'll stay false, and if $person held the local
193 // cache information to begin with, it'll keep that information. That way
194 // if there's a problem with the remote fetch, we can at least use our
195 // cached information--it's better than nothing.
197 if((! $person) || ($update)) {
198 // Lock the function to prevent race conditions if multiple items
199 // come in at the same time from a person who doesn't exist in
202 // Don't loop forever. On the last loop, try to create the contact
203 // whether the function is locked or not. Maybe the locking thread
204 // has died or something. At any rate, a duplicate in 'fcontact'
205 // is a much smaller problem than a deadlocked thread
206 $got_lock = lock_function('find_diaspora_person_by_handle', false);
207 if(($endlessloop + 1) >= $maxloops)
211 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
212 require_once('include/Scrape.php');
213 $r = probe_url($handle, PROBE_DIASPORA);
215 // Note that Friendica contacts can return a "Diaspora person"
216 // if Diaspora connectivity is enabled on their server
217 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
218 add_fcontact($r,$update);
222 unlock_function('find_diaspora_person_by_handle');
225 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
227 block_on_function_lock('find_diaspora_person_by_handle');
230 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
231 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
232 // The fact that the function was locked may mean that another process was creating the
233 // person's record. It could also mean another process was creating or updating an unrelated
236 // At any rate, we need to keep trying until we've either got the person or had a chance to
237 // try to fetch his/her remote information. But we don't want to block on locking the
238 // function, because if the other process is creating the record, then when we acquire the lock
239 // we'll dive right into creating another, duplicate record. We DO want to at least wait
240 // until the lock is released, so we don't flood the database with requests.
242 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
243 // we do have some information for the person
249 function get_diaspora_key($uri) {
250 logger('Fetching diaspora key for: ' . $uri);
252 $r = find_diaspora_person_by_handle($uri);
259 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
262 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
265 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
267 // $b64_data = base64_encode($msg);
268 // $b64url_data = base64url_encode($b64_data);
270 $b64url_data = base64url_encode($msg);
272 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
274 $type = 'application/xml';
275 $encoding = 'base64url';
278 $signable_data = $data . '.' . base64url_encode($type) . '.'
279 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
281 $signature = rsa_sign($signable_data,$prvkey);
282 $sig = base64url_encode($signature);
285 <?xml version='1.0' encoding='UTF-8'?>
286 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
288 <author_id>$handle</author_id>
291 <me:encoding>base64url</me:encoding>
292 <me:alg>RSA-SHA256</me:alg>
293 <me:data type="application/xml">$data</me:data>
294 <me:sig>$sig</me:sig>
299 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
307 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
311 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
313 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
315 // without a public key nothing will work
318 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
322 $inner_aes_key = random_string(32);
323 $b_inner_aes_key = base64_encode($inner_aes_key);
324 $inner_iv = random_string(16);
325 $b_inner_iv = base64_encode($inner_iv);
327 $outer_aes_key = random_string(32);
328 $b_outer_aes_key = base64_encode($outer_aes_key);
329 $outer_iv = random_string(16);
330 $b_outer_iv = base64_encode($outer_iv);
332 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
334 $padded_data = pkcs5_pad($msg,16);
335 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
337 $b64_data = base64_encode($inner_encrypted);
340 $b64url_data = base64url_encode($b64_data);
341 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
343 $type = 'application/xml';
344 $encoding = 'base64url';
347 $signable_data = $data . '.' . base64url_encode($type) . '.'
348 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
350 $signature = rsa_sign($signable_data,$prvkey);
351 $sig = base64url_encode($signature);
353 $decrypted_header = <<< EOT
356 <aes_key>$b_inner_aes_key</aes_key>
357 <author_id>$handle</author_id>
361 $decrypted_header = pkcs5_pad($decrypted_header,16);
363 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
365 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
367 $encrypted_outer_key_bundle = '';
368 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
370 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
372 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
374 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
375 'ciphertext' => base64_encode($ciphertext)));
376 $cipher_json = base64_encode($encrypted_header_json_object);
378 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
381 <?xml version='1.0' encoding='UTF-8'?>
382 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
385 <me:encoding>base64url</me:encoding>
386 <me:alg>RSA-SHA256</me:alg>
387 <me:data type="application/xml">$data</me:data>
388 <me:sig>$sig</me:sig>
393 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
400 * diaspora_decode($importer,$xml)
401 * array $importer -> from user table
402 * string $xml -> urldecoded Diaspora salmon
405 * 'message' -> decoded Diaspora XML message
406 * 'author' -> author diaspora handle
407 * 'key' -> author public key (converted to pkcs#8)
409 * Author and key are used elsewhere to save a lookup for verifying replies and likes
413 function diaspora_decode($importer,$xml) {
416 $basedom = parse_xml_string($xml);
418 $children = $basedom->children('https://joindiaspora.com/protocol');
420 if($children->header) {
422 $author_link = str_replace('acct:','',$children->header->author_id);
426 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
428 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
429 $ciphertext = base64_decode($encrypted_header->ciphertext);
431 $outer_key_bundle = '';
432 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
434 $j_outer_key_bundle = json_decode($outer_key_bundle);
436 $outer_iv = base64_decode($j_outer_key_bundle->iv);
437 $outer_key = base64_decode($j_outer_key_bundle->key);
439 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
442 $decrypted = pkcs5_unpad($decrypted);
445 * $decrypted now contains something like
448 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
449 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
454 * <name>Ryan Hughes</name>
455 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
460 * <author_id>galaxor@diaspora.priateship.org</author_id>
464 * </decrypted_header>
467 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
468 $idom = parse_xml_string($decrypted,false);
470 $inner_iv = base64_decode($idom->iv);
471 $inner_aes_key = base64_decode($idom->aes_key);
473 $author_link = str_replace('acct:','',$idom->author_id);
477 $dom = $basedom->children(NAMESPACE_SALMON_ME);
479 // figure out where in the DOM tree our data is hiding
481 if($dom->provenance->data)
482 $base = $dom->provenance;
483 elseif($dom->env->data)
489 logger('mod-diaspora: unable to locate salmon data in xml ');
490 http_status_exit(400);
494 // Stash the signature away for now. We have to find their key or it won't be good for anything.
495 $signature = base64url_decode($base->sig);
499 // strip whitespace so our data element will return to one big base64 blob
500 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
503 // stash away some other stuff for later
505 $type = $base->data[0]->attributes()->type[0];
506 $keyhash = $base->sig[0]->attributes()->keyhash[0];
507 $encoding = $base->encoding;
511 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
515 $data = base64url_decode($data);
519 $inner_decrypted = $data;
523 // Decode the encrypted blob
525 $inner_encrypted = base64_decode($data);
526 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
527 $inner_decrypted = pkcs5_unpad($inner_decrypted);
531 logger('mod-diaspora: Could not retrieve author URI.');
532 http_status_exit(400);
535 // Once we have the author URI, go to the web and try to find their public key
536 // (first this will look it up locally if it is in the fcontact cache)
537 // This will also convert diaspora public key from pkcs#1 to pkcs#8
539 logger('mod-diaspora: Fetching key for ' . $author_link );
540 $key = get_diaspora_key($author_link);
543 logger('mod-diaspora: Could not retrieve author key.');
544 http_status_exit(400);
547 $verify = rsa_verify($signed_data,$signature,$key);
550 logger('mod-diaspora: Message did not verify. Discarding.');
551 http_status_exit(400);
554 logger('mod-diaspora: Message verified.');
556 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
561 function diaspora_request($importer,$xml) {
565 $sender_handle = unxmlify($xml->sender_handle);
566 $recipient_handle = unxmlify($xml->recipient_handle);
568 if(! $sender_handle || ! $recipient_handle)
571 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
575 // perhaps we were already sharing with this person. Now they're sharing with us.
576 // That makes us friends.
578 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
579 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
580 intval(CONTACT_IS_FRIEND),
581 intval($contact['id']),
582 intval($importer['uid'])
587 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
588 intval($importer['uid'])
591 if((count($r)) && (! $r[0]['hide-friends']) && (! $contact['hidden'])) {
592 require_once('include/items.php');
594 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
595 intval($importer['uid'])
598 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
600 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
603 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
604 $arr['uid'] = $importer['uid'];
605 $arr['contact-id'] = $self[0]['id'];
607 $arr['type'] = 'wall';
610 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
611 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
612 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
613 $arr['verb'] = ACTIVITY_FRIEND;
614 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
616 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
617 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
618 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
619 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
621 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
622 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
623 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
624 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
625 $arr['object'] .= '</link></object>' . "\n";
626 $arr['last-child'] = 1;
628 $arr['allow_cid'] = $user[0]['allow_cid'];
629 $arr['allow_gid'] = $user[0]['allow_gid'];
630 $arr['deny_cid'] = $user[0]['deny_cid'];
631 $arr['deny_gid'] = $user[0]['deny_gid'];
633 $i = item_store($arr);
635 proc_run('php',"include/notifier.php","activity","$i");
644 $ret = find_diaspora_person_by_handle($sender_handle);
647 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
648 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
652 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
656 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
657 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
658 intval($importer['uid']),
659 dbesc($ret['network']),
663 dbesc(normalise_link($ret['url'])),
667 dbesc($ret['photo']),
668 dbesc($ret['pubkey']),
669 dbesc($ret['notify']),
675 // find the contact record we just created
677 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
679 if(! $contact_record) {
680 logger('diaspora_request: unable to locate newly created contact record.');
684 $g = q("select def_gid from user where uid = %d limit 1",
685 intval($importer['uid'])
687 if($g && intval($g[0]['def_gid'])) {
688 require_once('include/group.php');
689 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
692 if($importer['page-flags'] == PAGE_NORMAL) {
694 $hash = random_string() . (string) time(); // Generate a confirm_key
696 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
697 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
698 intval($importer['uid']),
699 intval($contact_record['id']),
702 dbesc( t('Sharing notification from Diaspora network')),
704 dbesc(datetime_convert())
709 // automatic friend approval
711 require_once('include/Photo.php');
713 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
715 // technically they are sharing with us (CONTACT_IS_SHARING),
716 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
717 // we are going to change the relationship and make them a follower.
719 if($importer['page-flags'] == PAGE_FREELOVE)
720 $new_relation = CONTACT_IS_FRIEND;
722 $new_relation = CONTACT_IS_FOLLOWER;
724 $r = q("UPDATE `contact` SET
731 `avatar-date` = '%s',
734 WHERE `id` = %d LIMIT 1
739 intval($new_relation),
740 dbesc(datetime_convert()),
741 dbesc(datetime_convert()),
742 dbesc(datetime_convert()),
743 intval($contact_record['id'])
746 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
748 $ret = diaspora_share($u[0],$contact_record);
754 function diaspora_post_allow($importer,$contact) {
755 if(($contact['blocked']) || ($contact['readonly']))
757 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
759 if($contact['rel'] == CONTACT_IS_FOLLOWER)
760 if($importer['page-flags'] == PAGE_COMMUNITY)
766 function diaspora_post($importer,$xml,$msg) {
769 $guid = notags(unxmlify($xml->guid));
770 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
772 if($diaspora_handle != $msg['author']) {
773 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
777 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
781 if(! diaspora_post_allow($importer,$contact)) {
782 logger('diaspora_post: Ignoring this author.');
786 $message_id = $diaspora_handle . ':' . $guid;
787 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
788 intval($importer['uid']),
793 logger('diaspora_post: message exists: ' . $guid);
797 // allocate a guid on our system - we aren't fixing any collisions.
798 // we're ignoring them
800 $g = q("select * from guid where guid = '%s' limit 1",
804 q("insert into guid ( guid ) values ( '%s' )",
809 $created = unxmlify($xml->created_at);
810 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
812 $body = diaspora2bb($xml->raw_message);
818 $tags = get_tags($body);
821 foreach($tags as $tag) {
822 if(strpos($tag,'#') === 0) {
823 if(strpos($tag,'[url='))
826 // don't link tags that are already embedded in links
828 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
830 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
833 $basetag = str_replace('_',' ',substr($tag,1));
834 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
835 if(strlen($str_tags))
837 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
843 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
845 foreach($matches as $mtch) {
846 if(strlen($str_tags))
848 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
852 $datarray['uid'] = $importer['uid'];
853 $datarray['contact-id'] = $contact['id'];
854 $datarray['wall'] = 0;
855 $datarray['guid'] = $guid;
856 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
857 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
858 $datarray['private'] = $private;
859 $datarray['parent'] = 0;
860 $datarray['owner-name'] = $contact['name'];
861 $datarray['owner-link'] = $contact['url'];
862 //$datarray['owner-avatar'] = $contact['thumb'];
863 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
864 $datarray['author-name'] = $contact['name'];
865 $datarray['author-link'] = $contact['url'];
866 $datarray['author-avatar'] = $contact['thumb'];
867 $datarray['body'] = $body;
868 $datarray['tag'] = $str_tags;
869 $datarray['app'] = 'Diaspora';
871 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
873 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
875 $message_id = item_store($datarray);
878 q("update item set plink = '%s' where id = %d limit 1",
879 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
888 function diaspora_reshare($importer,$xml,$msg) {
890 logger('diaspora_reshare: init: ' . print_r($xml,true));
893 $guid = notags(unxmlify($xml->guid));
894 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
897 if($diaspora_handle != $msg['author']) {
898 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
902 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
906 if(! diaspora_post_allow($importer,$contact)) {
907 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
911 $message_id = $diaspora_handle . ':' . $guid;
912 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
913 intval($importer['uid']),
918 logger('diaspora_reshare: message exists: ' . $guid);
922 $orig_author = notags(unxmlify($xml->root_diaspora_id));
923 $orig_guid = notags(unxmlify($xml->root_guid));
925 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
926 $x = fetch_url($source_url);
928 $x = fetch_url(str_replace('https://','http://',$source_url));
930 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
933 logger('diaspora_reshare: source: ' . $x);
935 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
936 $source_xml = parse_xml_string($x,false);
938 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
939 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
940 $body = scale_external_images($body,false);
942 elseif($source_xml->post->asphoto->image_url) {
943 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
944 $body = scale_external_images($body);
946 elseif($source_xml->post->status_message) {
947 $body = diaspora2bb($source_xml->post->status_message->raw_message);
948 $body = scale_external_images($body);
952 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
956 logger('diaspora_reshare: empty body: source= ' . $x);
960 $person = find_diaspora_person_by_handle($orig_author);
962 if(is_array($person) && x($person,'name') && x($person,'url'))
963 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
965 $details = $orig_author;
967 $prefix = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . $details . "\n";
970 // allocate a guid on our system - we aren't fixing any collisions.
971 // we're ignoring them
973 $g = q("select * from guid where guid = '%s' limit 1",
977 q("insert into guid ( guid ) values ( '%s' )",
982 $created = unxmlify($xml->created_at);
983 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
989 $tags = get_tags($body);
992 foreach($tags as $tag) {
993 if(strpos($tag,'#') === 0) {
994 if(strpos($tag,'[url='))
997 // don't link tags that are already embedded in links
999 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1001 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1005 $basetag = str_replace('_',' ',substr($tag,1));
1006 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1007 if(strlen($str_tags))
1009 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1015 $datarray['uid'] = $importer['uid'];
1016 $datarray['contact-id'] = $contact['id'];
1017 $datarray['wall'] = 0;
1018 $datarray['guid'] = $guid;
1019 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1020 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1021 $datarray['private'] = $private;
1022 $datarray['parent'] = 0;
1023 $datarray['owner-name'] = $contact['name'];
1024 $datarray['owner-link'] = $contact['url'];
1025 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1026 $datarray['author-name'] = $person['name']; // Let reshared messages look like wall-to-wall posts
1027 $datarray['author-link'] = $person['url']; // we have to set an additional value in the item in the future
1028 // $datarray['author-avatar'] = $person['thumb']; // to distinct the wall-to-wall-posts from reshared/repeated messages
1029 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1030 // $datarray['body'] = $prefix . $body;
1031 $datarray['body'] = $body;
1032 $datarray['tag'] = $str_tags;
1033 $datarray['app'] = 'Diaspora';
1035 $message_id = item_store($datarray);
1038 q("update item set plink = '%s' where id = %d limit 1",
1039 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1049 function diaspora_asphoto($importer,$xml,$msg) {
1050 logger('diaspora_asphoto called');
1053 $guid = notags(unxmlify($xml->guid));
1054 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1056 if($diaspora_handle != $msg['author']) {
1057 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1061 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1065 if(! diaspora_post_allow($importer,$contact)) {
1066 logger('diaspora_asphoto: Ignoring this author.');
1070 $message_id = $diaspora_handle . ':' . $guid;
1071 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1072 intval($importer['uid']),
1077 logger('diaspora_asphoto: message exists: ' . $guid);
1081 // allocate a guid on our system - we aren't fixing any collisions.
1082 // we're ignoring them
1084 $g = q("select * from guid where guid = '%s' limit 1",
1088 q("insert into guid ( guid ) values ( '%s' )",
1093 $created = unxmlify($xml->created_at);
1094 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1096 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1097 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1098 $body = scale_external_images($body,false);
1100 elseif($xml->image_url) {
1101 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1102 $body = scale_external_images($body);
1105 logger('diaspora_asphoto: no photo url found.');
1109 $datarray = array();
1112 $datarray['uid'] = $importer['uid'];
1113 $datarray['contact-id'] = $contact['id'];
1114 $datarray['wall'] = 0;
1115 $datarray['guid'] = $guid;
1116 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1117 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1118 $datarray['private'] = $private;
1119 $datarray['parent'] = 0;
1120 $datarray['owner-name'] = $contact['name'];
1121 $datarray['owner-link'] = $contact['url'];
1122 //$datarray['owner-avatar'] = $contact['thumb'];
1123 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1124 $datarray['author-name'] = $contact['name'];
1125 $datarray['author-link'] = $contact['url'];
1126 $datarray['author-avatar'] = $contact['thumb'];
1127 $datarray['body'] = $body;
1129 $datarray['app'] = 'Diaspora/Cubbi.es';
1131 $message_id = item_store($datarray);
1134 q("update item set plink = '%s' where id = %d limit 1",
1135 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1149 function diaspora_comment($importer,$xml,$msg) {
1152 $guid = notags(unxmlify($xml->guid));
1153 $parent_guid = notags(unxmlify($xml->parent_guid));
1154 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1155 $target_type = notags(unxmlify($xml->target_type));
1156 $text = unxmlify($xml->text);
1157 $author_signature = notags(unxmlify($xml->author_signature));
1159 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1161 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1163 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1167 if(! diaspora_post_allow($importer,$contact)) {
1168 logger('diaspora_comment: Ignoring this author.');
1172 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1173 intval($importer['uid']),
1177 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1181 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1182 intval($importer['uid']),
1186 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1189 $parent_item = $r[0];
1192 /* How Diaspora performs comment signature checking:
1194 - If an item has been sent by the comment author to the top-level post owner to relay on
1195 to the rest of the contacts on the top-level post, the top-level post owner should check
1196 the author_signature, then create a parent_author_signature before relaying the comment on
1197 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1198 check only the parent_author_signature. Basically, they trust that the top-level post
1199 owner has already verified the authenticity of anything he/she sends out
1200 - In either case, the signature that get checked is the signature created by the person
1204 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1207 if($parent_author_signature) {
1208 // If a parent_author_signature exists, then we've received the comment
1209 // relayed from the top-level post owner. There's no need to check the
1210 // author_signature if the parent_author_signature is valid
1212 $parent_author_signature = base64_decode($parent_author_signature);
1214 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1215 logger('diaspora_comment: top-level owner verification failed.');
1220 // If there's no parent_author_signature, then we've received the comment
1221 // from the comment creator. In that case, the person is commenting on
1222 // our post, so he/she must be a contact of ours and his/her public key
1223 // should be in $msg['key']
1225 $author_signature = base64_decode($author_signature);
1227 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1228 logger('diaspora_comment: comment author verification failed.');
1233 // Phew! Everything checks out. Now create an item.
1235 // Find the original comment author information.
1236 // We need this to make sure we display the comment author
1237 // information (name and avatar) correctly.
1238 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1241 $person = find_diaspora_person_by_handle($diaspora_handle);
1243 if(! is_array($person)) {
1244 logger('diaspora_comment: unable to find author details');
1249 $body = diaspora2bb($text);
1251 $message_id = $diaspora_handle . ':' . $guid;
1253 $datarray = array();
1257 $tags = get_tags($body);
1260 foreach($tags as $tag) {
1261 if(strpos($tag,'#') === 0) {
1262 if(strpos($tag,'[url='))
1265 // don't link tags that are already embedded in links
1267 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1269 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1273 $basetag = str_replace('_',' ',substr($tag,1));
1274 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1275 if(strlen($str_tags))
1277 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1283 $datarray['uid'] = $importer['uid'];
1284 $datarray['contact-id'] = $contact['id'];
1285 $datarray['type'] = 'remote-comment';
1286 $datarray['wall'] = $parent_item['wall'];
1287 $datarray['gravity'] = GRAVITY_COMMENT;
1288 $datarray['guid'] = $guid;
1289 $datarray['uri'] = $message_id;
1290 $datarray['parent-uri'] = $parent_item['uri'];
1292 // No timestamps for comments? OK, we'll the use current time.
1293 $datarray['created'] = $datarray['edited'] = datetime_convert();
1294 $datarray['private'] = $parent_item['private'];
1296 $datarray['owner-name'] = $parent_item['owner-name'];
1297 $datarray['owner-link'] = $parent_item['owner-link'];
1298 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1300 $datarray['author-name'] = $person['name'];
1301 $datarray['author-link'] = $person['url'];
1302 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1303 $datarray['body'] = $body;
1304 $datarray['tag'] = $str_tags;
1306 // We can't be certain what the original app is if the message is relayed.
1307 if(($parent_item['origin']) && (! $parent_author_signature))
1308 $datarray['app'] = 'Diaspora';
1310 $message_id = item_store($datarray);
1313 q("update item set plink = '%s' where id = %d limit 1",
1314 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1319 if(($parent_item['origin']) && (! $parent_author_signature)) {
1320 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1321 intval($message_id),
1322 dbesc($signed_data),
1323 dbesc(base64_encode($author_signature)),
1324 dbesc($diaspora_handle)
1327 // if the message isn't already being relayed, notify others
1328 // the existence of parent_author_signature means the parent_author or owner
1329 // is already relaying.
1331 proc_run('php','include/notifier.php','comment-import',$message_id);
1334 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1335 dbesc($parent_item['uri']),
1336 intval($importer['uid'])
1339 if(count($myconv)) {
1340 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1342 foreach($myconv as $conv) {
1344 // now if we find a match, it means we're in this conversation
1346 if(! link_compare($conv['author-link'],$importer_url))
1349 require_once('include/enotify.php');
1351 $conv_parent = $conv['parent'];
1354 'type' => NOTIFY_COMMENT,
1355 'notify_flags' => $importer['notify-flags'],
1356 'language' => $importer['language'],
1357 'to_name' => $importer['username'],
1358 'to_email' => $importer['email'],
1359 'uid' => $importer['uid'],
1360 'item' => $datarray,
1361 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id,
1362 'source_name' => $datarray['author-name'],
1363 'source_link' => $datarray['author-link'],
1364 'source_photo' => $datarray['author-avatar'],
1365 'verb' => ACTIVITY_POST,
1367 'parent' => $conv_parent,
1368 'parent_uri' => $parent_uri
1371 // only send one notification
1381 function diaspora_conversation($importer,$xml,$msg) {
1385 $guid = notags(unxmlify($xml->guid));
1386 $subject = notags(unxmlify($xml->subject));
1387 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1388 $participant_handles = notags(unxmlify($xml->participant_handles));
1389 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1391 $parent_uri = $diaspora_handle . ':' . $guid;
1393 $messages = $xml->message;
1395 if(! count($messages)) {
1396 logger('diaspora_conversation: empty conversation');
1400 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1402 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1406 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1407 logger('diaspora_conversation: Ignoring this author.');
1411 $conversation = null;
1413 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1414 intval($importer['uid']),
1418 $conversation = $c[0];
1420 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1421 intval($importer['uid']),
1423 dbesc($diaspora_handle),
1424 dbesc(datetime_convert('UTC','UTC',$created_at)),
1425 dbesc(datetime_convert()),
1427 dbesc($participant_handles)
1430 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1431 intval($importer['uid']),
1435 $conversation = $c[0];
1437 if(! $conversation) {
1438 logger('diaspora_conversation: unable to create conversation.');
1442 foreach($messages as $mesg) {
1446 $msg_guid = notags(unxmlify($mesg->guid));
1447 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1448 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1449 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1450 $msg_text = unxmlify($mesg->text);
1451 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1452 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1453 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1454 if($msg_conversation_guid != $guid) {
1455 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1459 $body = diaspora2bb($msg_text);
1460 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1462 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1464 $author_signature = base64_decode($msg_author_signature);
1466 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1471 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1473 if(is_array($person) && x($person,'pubkey'))
1474 $key = $person['pubkey'];
1476 logger('diaspora_conversation: unable to find author details');
1481 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1482 logger('diaspora_conversation: verification failed.');
1486 if($msg_parent_author_signature) {
1487 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1489 $parent_author_signature = base64_decode($msg_parent_author_signature);
1493 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1494 logger('diaspora_conversation: owner verification failed.');
1499 $r = q("select id from mail where `uri` = '%s' limit 1",
1503 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1507 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')",
1508 intval($importer['uid']),
1510 intval($conversation['id']),
1511 dbesc($person['name']),
1512 dbesc($person['photo']),
1513 dbesc($person['url']),
1514 intval($contact['id']),
1521 dbesc($msg_created_at)
1524 q("update conv set updated = '%s' where id = %d limit 1",
1525 dbesc(datetime_convert()),
1526 intval($conversation['id'])
1529 require_once('include/enotify.php');
1531 'type' => NOTIFY_MAIL,
1532 'notify_flags' => $importer['notify-flags'],
1533 'language' => $importer['language'],
1534 'to_name' => $importer['username'],
1535 'to_email' => $importer['email'],
1536 'uid' =>$importer['importer_uid'],
1537 'item' => array('subject' => $subject, 'body' => $body),
1538 'source_name' => $person['name'],
1539 'source_link' => $person['url'],
1540 'source_photo' => $person['thumb'],
1541 'verb' => ACTIVITY_POST,
1549 function diaspora_message($importer,$xml,$msg) {
1553 $msg_guid = notags(unxmlify($xml->guid));
1554 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1555 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1556 $msg_author_signature = notags(unxmlify($xml->author_signature));
1557 $msg_text = unxmlify($xml->text);
1558 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1559 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1560 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1562 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1564 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1566 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1570 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1571 logger('diaspora_message: Ignoring this author.');
1575 $conversation = null;
1577 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1578 intval($importer['uid']),
1579 dbesc($msg_conversation_guid)
1582 $conversation = $c[0];
1584 logger('diaspora_message: conversation not available.');
1590 $body = diaspora2bb($msg_text);
1591 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1593 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1596 $author_signature = base64_decode($msg_author_signature);
1598 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1599 if(is_array($person) && x($person,'pubkey'))
1600 $key = $person['pubkey'];
1602 logger('diaspora_message: unable to find author details');
1606 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1607 logger('diaspora_message: verification failed.');
1611 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1613 intval($importer['uid'])
1616 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1620 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')",
1621 intval($importer['uid']),
1623 intval($conversation['id']),
1624 dbesc($person['name']),
1625 dbesc($person['photo']),
1626 dbesc($person['url']),
1627 intval($contact['id']),
1628 dbesc($conversation['subject']),
1634 dbesc($msg_created_at)
1637 q("update conv set updated = '%s' where id = %d limit 1",
1638 dbesc(datetime_convert()),
1639 intval($conversation['id'])
1646 function diaspora_photo($importer,$xml,$msg) {
1650 logger('diaspora_photo: init',LOGGER_DEBUG);
1652 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1654 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1656 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1658 $guid = notags(unxmlify($xml->guid));
1660 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1662 $public = notags(unxmlify($xml->public));
1664 $created_at = notags(unxmlify($xml_created_at));
1666 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1668 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1670 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1674 if(! diaspora_post_allow($importer,$contact)) {
1675 logger('diaspora_photo: Ignoring this author.');
1679 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1680 intval($importer['uid']),
1681 dbesc($status_message_guid)
1684 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1688 $parent_item = $r[0];
1690 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1692 $link_text = scale_external_images($link_text, true,
1693 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1695 if(strpos($parent_item['body'],$link_text) === false) {
1696 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1697 dbesc($link_text . $parent_item['body']),
1698 intval($parent_item['id']),
1699 intval($parent_item['uid'])
1709 function diaspora_like($importer,$xml,$msg) {
1712 $guid = notags(unxmlify($xml->guid));
1713 $parent_guid = notags(unxmlify($xml->parent_guid));
1714 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1715 $target_type = notags(unxmlify($xml->target_type));
1716 $positive = notags(unxmlify($xml->positive));
1717 $author_signature = notags(unxmlify($xml->author_signature));
1719 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1721 // likes on comments not supported here and likes on photos not supported by Diaspora
1723 // if($target_type !== 'Post')
1726 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1728 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1732 if(! diaspora_post_allow($importer,$contact)) {
1733 logger('diaspora_like: Ignoring this author.');
1737 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1738 intval($importer['uid']),
1742 logger('diaspora_like: parent item not found: ' . $guid);
1746 $parent_item = $r[0];
1748 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1749 intval($importer['uid']),
1753 if($positive === 'true') {
1754 logger('diaspora_like: duplicate like: ' . $guid);
1757 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1758 // It looks like "RelayableRetractions" are used for "unlike" instead
1759 if($positive === 'false') {
1760 logger('diaspora_like: received a like with positive set to "false"...ignoring');
1761 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1762 intval($r[0]['id']),
1763 intval($importer['uid'])
1765 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1766 // send notification via proc_run()
1770 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1771 // It looks like "RelayableRetractions" are used for "unlike" instead
1772 if($positive === 'false') {
1773 logger('diaspora_like: received a like with positive set to "false"');
1774 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1779 /* How Diaspora performs "like" signature checking:
1781 - If an item has been sent by the like author to the top-level post owner to relay on
1782 to the rest of the contacts on the top-level post, the top-level post owner should check
1783 the author_signature, then create a parent_author_signature before relaying the like on
1784 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1785 check only the parent_author_signature. Basically, they trust that the top-level post
1786 owner has already verified the authenticity of anything he/she sends out
1787 - In either case, the signature that get checked is the signature created by the person
1791 $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1794 if($parent_author_signature) {
1795 // If a parent_author_signature exists, then we've received the like
1796 // relayed from the top-level post owner. There's no need to check the
1797 // author_signature if the parent_author_signature is valid
1799 $parent_author_signature = base64_decode($parent_author_signature);
1801 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1802 logger('diaspora_like: top-level owner verification failed.');
1807 // If there's no parent_author_signature, then we've received the like
1808 // from the like creator. In that case, the person is "like"ing
1809 // our post, so he/she must be a contact of ours and his/her public key
1810 // should be in $msg['key']
1812 $author_signature = base64_decode($author_signature);
1814 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1815 logger('diaspora_like: like creator verification failed.');
1820 // Phew! Everything checks out. Now create an item.
1822 // Find the original comment author information.
1823 // We need this to make sure we display the comment author
1824 // information (name and avatar) correctly.
1825 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1828 $person = find_diaspora_person_by_handle($diaspora_handle);
1830 if(! is_array($person)) {
1831 logger('diaspora_like: unable to find author details');
1836 $uri = $diaspora_handle . ':' . $guid;
1838 $activity = ACTIVITY_LIKE;
1839 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1840 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1841 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1842 $body = $parent_item['body'];
1847 <type>$objtype</type>
1849 <id>{$parent_item['uri']}</id>
1852 <content>$body</content>
1855 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1860 $arr['uid'] = $importer['uid'];
1861 $arr['guid'] = $guid;
1862 $arr['contact-id'] = $contact['id'];
1863 $arr['type'] = 'activity';
1864 $arr['wall'] = $parent_item['wall'];
1865 $arr['gravity'] = GRAVITY_LIKE;
1866 $arr['parent'] = $parent_item['id'];
1867 $arr['parent-uri'] = $parent_item['uri'];
1869 $arr['owner-name'] = $parent_item['name'];
1870 $arr['owner-link'] = $parent_item['url'];
1871 //$arr['owner-avatar'] = $parent_item['thumb'];
1872 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
1874 $arr['author-name'] = $person['name'];
1875 $arr['author-link'] = $person['url'];
1876 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1878 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1879 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1880 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1881 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1883 $arr['app'] = 'Diaspora';
1885 $arr['private'] = $parent_item['private'];
1886 $arr['verb'] = $activity;
1887 $arr['object-type'] = $objtype;
1888 $arr['object'] = $obj;
1889 $arr['visible'] = 1;
1891 $arr['last-child'] = 0;
1893 $message_id = item_store($arr);
1897 q("update item set plink = '%s' where id = %d limit 1",
1898 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1903 if(! $parent_author_signature) {
1904 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1905 intval($message_id),
1906 dbesc($signed_data),
1907 dbesc(base64_encode($author_signature)),
1908 dbesc($diaspora_handle)
1912 // if the message isn't already being relayed, notify others
1913 // the existence of parent_author_signature means the parent_author or owner
1914 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1916 if(($parent_item['origin']) && (! $parent_author_signature))
1917 proc_run('php','include/notifier.php','comment-import',$message_id);
1922 function diaspora_retraction($importer,$xml) {
1925 $guid = notags(unxmlify($xml->guid));
1926 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1927 $type = notags(unxmlify($xml->type));
1929 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1933 if($type === 'Person') {
1934 require_once('include/Contact.php');
1935 contact_remove($contact['id']);
1937 elseif($type === 'Post') {
1938 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1940 intval($importer['uid'])
1943 if(link_compare($r[0]['author-link'],$contact['url'])) {
1944 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1945 dbesc(datetime_convert()),
1956 function diaspora_signed_retraction($importer,$xml,$msg) {
1959 $guid = notags(unxmlify($xml->target_guid));
1960 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1961 $type = notags(unxmlify($xml->target_type));
1962 $sig = notags(unxmlify($xml->target_author_signature));
1964 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1966 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1968 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
1973 $signed_data = $guid . ';' . $type ;
1976 /* How Diaspora performs relayable_retraction signature checking:
1978 - If an item has been sent by the item author to the top-level post owner to relay on
1979 to the rest of the contacts on the top-level post, the top-level post owner checks
1980 the author_signature, then creates a parent_author_signature before relaying the item on
1981 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1982 check only the parent_author_signature. Basically, they trust that the top-level post
1983 owner has already verified the authenticity of anything he/she sends out
1984 - In either case, the signature that get checked is the signature created by the person
1988 if($parent_author_signature) {
1990 $parent_author_signature = base64_decode($parent_author_signature);
1992 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1993 logger('diaspora_signed_retraction: top-level post owner verification failed');
2000 $sig_decode = base64_decode($sig);
2002 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2003 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2008 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2009 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2011 intval($importer['uid'])
2014 if(link_compare($r[0]['author-link'],$contact['url'])) {
2015 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d limit 1",
2016 dbesc(datetime_convert()),
2017 dbesc(datetime_convert()),
2021 // Now check if the retraction needs to be relayed by us
2023 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2024 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2025 // The only item with `parent` and `id` as the parent id is the parent item.
2026 $p = q("select origin from item where parent = %d and id = %d limit 1",
2031 if(($p[0]['origin']) && (! $parent_author_signature)) {
2032 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2034 dbesc($signed_data),
2036 dbesc($diaspora_handle)
2039 // the existence of parent_author_signature would have meant the parent_author or owner
2040 // is already relaying.
2041 logger('diaspora_signed_retraction: relaying relayable_retraction');
2043 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2050 logger('diaspora_signed_retraction: unknown type: ' . $type);
2056 function diaspora_profile($importer,$xml,$msg) {
2059 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2062 if($diaspora_handle != $msg['author']) {
2063 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2067 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2071 if($contact['blocked']) {
2072 logger('diaspora_post: Ignoring this author.');
2076 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2077 $image_url = unxmlify($xml->image_url);
2078 $birthday = unxmlify($xml->birthday);
2081 $handle_parts = explode("@", $diaspora_handle);
2083 $name = $handle_parts[0];
2085 if(strpos($image_url, $handle_parts[1]) === false) {
2086 $image_url = "http://" . $handle_parts[1] . $image_url;
2089 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2090 intval($importer['uid']),
2091 intval($contact['id'])
2093 $oldphotos = ((count($r)) ? $r : null);*/
2095 require_once('include/Photo.php');
2097 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2099 // Generic birthday. We don't know the timezone. The year is irrelevant.
2101 $birthday = str_replace('1000','1901',$birthday);
2103 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2105 // this is to prevent multiple birthday notifications in a single year
2106 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2108 if(substr($birthday,5) === substr($contact['bd'],5))
2109 $birthday = $contact['bd'];
2111 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2112 // Not doing this currently because D* protocol is scheduled for revision soon.
2114 $r = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
2116 dbesc(datetime_convert()),
2120 dbesc(datetime_convert()),
2122 intval($contact['id']),
2123 intval($importer['uid'])
2128 foreach($oldphotos as $ph) {
2129 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2130 intval($importer['uid']),
2131 intval($contact['id']),
2132 dbesc($ph['resource-id'])
2142 function diaspora_share($me,$contact) {
2144 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2145 $theiraddr = $contact['addr'];
2147 $tpl = get_markup_template('diaspora_share.tpl');
2148 $msg = replace_macros($tpl, array(
2149 '$sender' => $myaddr,
2150 '$recipient' => $theiraddr
2153 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2154 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2156 return(diaspora_transmit($owner,$contact,$slap, false));
2159 function diaspora_unshare($me,$contact) {
2162 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2164 $tpl = get_markup_template('diaspora_retract.tpl');
2165 $msg = replace_macros($tpl, array(
2166 '$guid' => $me['guid'],
2167 '$type' => 'Person',
2168 '$handle' => $myaddr
2171 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2172 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2174 return(diaspora_transmit($owner,$contact,$slap, false));
2179 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2182 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2183 $theiraddr = $contact['addr'];
2187 $title = $item['title'];
2188 $body = $item['body'];
2191 // We're trying to match Diaspora's split message/photo protocol but
2192 // all the photos are displayed on D* as links and not img's - even
2193 // though we're sending pretty much precisely what they send us when
2194 // doing the same operation.
2195 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2196 // which seems to get through intact.
2198 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2200 foreach($matches as $mtch) {
2202 $detail['str'] = $mtch[0];
2203 $detail['path'] = dirname($mtch[1]) . '/';
2204 $detail['file'] = basename($mtch[1]);
2205 $detail['guid'] = $item['guid'];
2206 $detail['handle'] = $myaddr;
2207 $images[] = $detail;
2208 $body = str_replace($detail['str'],$mtch[1],$body);
2213 //if(strlen($title))
2214 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2216 // convert to markdown
2217 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2218 //$body = bb2diaspora($body);
2222 $body = "## ".html_entity_decode($title)."\n\n".$body;
2224 if($item['attach']) {
2225 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2227 $body .= "\n" . t('Attachments:') . "\n";
2228 foreach($matches as $mtch) {
2229 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2235 $public = (($item['private']) ? 'false' : 'true');
2237 require_once('include/datetime.php');
2238 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2240 $tpl = get_markup_template('diaspora_post.tpl');
2241 $msg = replace_macros($tpl, array(
2243 '$guid' => $item['guid'],
2244 '$handle' => xmlify($myaddr),
2245 '$public' => $public,
2246 '$created' => $created
2249 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
2251 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2252 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2254 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2256 if(count($images)) {
2257 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2260 return $return_code;
2264 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2266 if(! count($images))
2268 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2270 $tpl = get_markup_template('diaspora_photo.tpl');
2271 foreach($images as $image) {
2272 if(! stristr($image['path'],$mysite))
2274 $resource = str_replace('.jpg','',$image['file']);
2275 $resource = substr($resource,0,strpos($resource,'-'));
2277 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2279 intval($owner['uid'])
2283 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2284 $msg = replace_macros($tpl,array(
2285 '$path' => xmlify($image['path']),
2286 '$filename' => xmlify($image['file']),
2287 '$msg_guid' => xmlify($image['guid']),
2288 '$guid' => xmlify($r[0]['guid']),
2289 '$handle' => xmlify($image['handle']),
2290 '$public' => xmlify($public),
2291 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2295 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2296 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2297 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2299 diaspora_transmit($owner,$contact,$slap,$public_batch);
2304 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2307 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2308 // $theiraddr = $contact['addr'];
2310 // Diaspora doesn't support threaded comments
2311 /*if($item['thr-parent']) {
2312 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2313 dbesc($item['thr-parent'])
2317 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2318 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2319 // The only item with `parent` and `id` as the parent id is the parent item.
2320 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2321 intval($item['parent']),
2322 intval($item['parent'])
2330 if($item['verb'] === ACTIVITY_LIKE) {
2331 $tpl = get_markup_template('diaspora_like.tpl');
2333 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2334 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2335 // $positive = (($item['deleted']) ? 'false' : 'true');
2338 if(($item['deleted']))
2339 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2342 $tpl = get_markup_template('diaspora_comment.tpl');
2346 $text = html_entity_decode(bb2diaspora($item['body']));
2351 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2353 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2355 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2357 $msg = replace_macros($tpl,array(
2358 '$guid' => xmlify($item['guid']),
2359 '$parent_guid' => xmlify($parent['guid']),
2360 '$target_type' =>xmlify($target_type),
2361 '$authorsig' => xmlify($authorsig),
2362 '$body' => xmlify($text),
2363 '$positive' => xmlify($positive),
2364 '$handle' => xmlify($myaddr)
2367 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2369 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2370 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2372 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2376 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2380 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2381 // $theiraddr = $contact['addr'];
2383 $body = $item['body'];
2384 $text = html_entity_decode(bb2diaspora($body));
2386 // Diaspora doesn't support threaded comments
2387 /*if($item['thr-parent']) {
2388 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2389 dbesc($item['thr-parent'])
2393 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2394 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2395 // The only item with `parent` and `id` as the parent id is the parent item.
2396 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2397 intval($item['parent']),
2398 intval($item['parent'])
2407 $relay_retract = false;
2408 $sql_sign_id = 'iid';
2409 if( $item['deleted']) {
2410 $relay_retract = true;
2412 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2414 $sql_sign_id = 'retract_iid';
2415 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2417 elseif($item['verb'] === ACTIVITY_LIKE) {
2420 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2421 // $positive = (($item['deleted']) ? 'false' : 'true');
2424 $tpl = get_markup_template('diaspora_like_relay.tpl');
2426 else { // item is a comment
2427 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2431 // fetch the original signature if the relayable was created by a Diaspora
2432 // or DFRN user. Relayables for other networks are not supported.
2434 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2439 $signed_text = $orig_sign['signed_text'];
2440 $authorsig = $orig_sign['signature'];
2441 $handle = $orig_sign['signer'];
2445 // Author signature information (for likes, comments, and retractions of likes or comments,
2446 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2447 // function is called
2448 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2452 /* Since the author signature is only checked by the parent, not by the relay recipients,
2453 * I think it may not be necessary for us to do so much work to preserve all the original
2454 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2455 * Let's just generate that and forget about all the original author signature stuff.
2457 * Note: this might be more of an problem if we want to support likes on comments for older
2458 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2459 * doing that, let's ignore it for now.
2461 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2465 $handle = diaspora_handle_from_contact($item['contact-id']);
2471 $sender_signed_text = $item['guid'] . ';' . $target_type;
2473 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2475 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2477 // Sign the relayable with the top-level owner's signature
2479 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2480 // stored in the database, because that provides the best chance that Diaspora will
2481 // be able to reconstruct the signed text the same way we did. This is particularly a
2482 // concern for the comment, whose signed text includes the text of the comment. The
2483 // smallest change in the text of the comment, including removing whitespace, will
2484 // make the signature verification fail. Since we translate from BB code to Diaspora's
2485 // markup at the top of this function, which is AFTER we placed the original $signed_text
2486 // in the database, it's hazardous to trust the original $signed_text.
2488 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2490 $msg = replace_macros($tpl,array(
2491 '$guid' => xmlify($item['guid']),
2492 '$parent_guid' => xmlify($parent['guid']),
2493 '$target_type' =>xmlify($target_type),
2494 '$authorsig' => xmlify($authorsig),
2495 '$parentsig' => xmlify($parentauthorsig),
2496 '$body' => xmlify($text),
2497 '$positive' => xmlify($positive),
2498 '$handle' => xmlify($handle)
2501 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2504 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2505 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2507 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2513 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2516 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2518 // Check whether the retraction is for a top-level post or whether it's a relayable
2519 if( $item['uri'] !== $item['parent-uri'] ) {
2521 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2522 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2526 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2527 $target_type = 'StatusMessage';
2530 $signed_text = $item['guid'] . ';' . $target_type;
2532 $msg = replace_macros($tpl, array(
2533 '$guid' => xmlify($item['guid']),
2534 '$type' => xmlify($target_type),
2535 '$handle' => xmlify($myaddr),
2536 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2539 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2540 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2542 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2545 function diaspora_send_mail($item,$owner,$contact) {
2548 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2550 $r = q("select * from conv where id = %d and uid = %d limit 1",
2551 intval($item['convid']),
2552 intval($item['uid'])
2556 logger('diaspora_send_mail: conversation not found.');
2562 'guid' => xmlify($cnv['guid']),
2563 'subject' => xmlify($cnv['subject']),
2564 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2565 'diaspora_handle' => xmlify($cnv['creator']),
2566 'participant_handles' => xmlify($cnv['recips'])
2569 $body = bb2diaspora($item['body']);
2570 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2572 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2573 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2575 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2578 'guid' => xmlify($item['guid']),
2579 'parent_guid' => xmlify($cnv['guid']),
2580 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2581 'author_signature' => xmlify($sig),
2582 'text' => xmlify($body),
2583 'created_at' => xmlify($created),
2584 'diaspora_handle' => xmlify($myaddr),
2585 'conversation_guid' => xmlify($cnv['guid'])
2588 if($item['reply']) {
2589 $tpl = get_markup_template('diaspora_message.tpl');
2590 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2593 $conv['messages'] = array($msg);
2594 $tpl = get_markup_template('diaspora_conversation.tpl');
2595 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2598 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2600 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2601 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2603 return(diaspora_transmit($owner,$contact,$slap,false));
2608 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2610 $enabled = intval(get_config('system','diaspora_enabled'));
2616 $logid = random_string(4);
2617 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2619 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2623 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2625 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2629 if(! intval(get_config('system','diaspora_test'))) {
2630 post_url($dest_url . '/', $slap);
2631 $return_code = $a->get_curl_code();
2634 logger('diaspora_transmit: test_mode');
2639 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2641 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2642 logger('diaspora_transmit: queue message');
2644 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2645 intval($contact['id']),
2646 dbesc(NETWORK_DIASPORA),
2648 intval($public_batch)
2651 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2654 // queue message for redelivery
2655 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2660 return(($return_code) ? $return_code : (-1));