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 ",
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);
66 elseif($xmlbase->profile) {
67 $ret = diaspora_profile($importer,$xmlbase->profile);
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);
78 elseif($xmlbase->reshare) {
79 $ret = diaspora_reshare($importer,$xmlbase->reshare);
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_get_contact_by_handle($uid,$handle) {
106 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
107 dbesc(NETWORK_DIASPORA),
116 function find_diaspora_person_by_handle($handle) {
123 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
124 dbesc(NETWORK_DIASPORA),
129 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
131 // update record occasionally so it doesn't get stale
132 $d = strtotime($person['updated'] . ' +00:00');
133 if($d < strtotime('now - 14 days'))
138 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
140 // If the person isn't in our 'fcontact' table, or if he/she is but
141 // his/her information hasn't been updated for more than 14 days, then
142 // we want to fetch the person's information from the remote server.
144 // Note that $person isn't changed by this block of code unless the
145 // person's information has been successfully fetched from the remote
146 // server. So if $person was 'false' to begin with (because he/she wasn't
147 // in the local cache), it'll stay false, and if $person held the local
148 // cache information to begin with, it'll keep that information. That way
149 // if there's a problem with the remote fetch, we can at least use our
150 // cached information--it's better than nothing.
152 if((! $person) || ($update)) {
153 // Lock the function to prevent race conditions if multiple items
154 // come in at the same time from a person who doesn't exist in
156 $got_lock = lock_function('find_diaspora_person_by_handle', false);
159 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
160 require_once('include/Scrape.php');
161 $r = probe_url($handle, PROBE_DIASPORA);
163 // Note that Friendica contacts can return a "Diaspora person"
164 // if Diaspora connectivity is enabled on their server
165 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
166 add_fcontact($r,$update);
170 unlock_function('find_diaspora_person_by_handle');
173 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
175 block_on_function_lock('find_diaspora_person_by_handle');
178 } while((! $person) && (! $got_lock));
179 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
180 // The fact that the function was locked may mean that another process was creating the
181 // person's record. It could also mean another process was creating or updating an unrelated
184 // At any rate, we need to keep trying until we've either got the person or had a chance to
185 // try to fetch his/her remote information. But we don't want to block on locking the
186 // function, because if the other process is creating the record, then when we acquire the lock
187 // we'll dive right into creating another, duplicate record. We DO want to at least wait
188 // until the lock is released, so we don't flood the database with requests.
190 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
191 // we do have some information for the person
197 function get_diaspora_key($uri) {
198 logger('Fetching diaspora key for: ' . $uri);
200 $r = find_diaspora_person_by_handle($uri);
207 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
210 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
213 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
215 // $b64_data = base64_encode($msg);
216 // $b64url_data = base64url_encode($b64_data);
218 $b64url_data = base64url_encode($msg);
220 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
222 $type = 'application/xml';
223 $encoding = 'base64url';
226 $signable_data = $data . '.' . base64url_encode($type) . '.'
227 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
229 $signature = rsa_sign($signable_data,$prvkey);
230 $sig = base64url_encode($signature);
233 <?xml version='1.0' encoding='UTF-8'?>
234 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
236 <author_id>$handle</author_id>
239 <me:encoding>base64url</me:encoding>
240 <me:alg>RSA-SHA256</me:alg>
241 <me:data type="application/xml">$data</me:data>
242 <me:sig>$sig</me:sig>
247 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
255 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
259 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
261 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
263 // without a public key nothing will work
266 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
270 $inner_aes_key = random_string(32);
271 $b_inner_aes_key = base64_encode($inner_aes_key);
272 $inner_iv = random_string(16);
273 $b_inner_iv = base64_encode($inner_iv);
275 $outer_aes_key = random_string(32);
276 $b_outer_aes_key = base64_encode($outer_aes_key);
277 $outer_iv = random_string(16);
278 $b_outer_iv = base64_encode($outer_iv);
280 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
282 $padded_data = pkcs5_pad($msg,16);
283 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
285 $b64_data = base64_encode($inner_encrypted);
288 $b64url_data = base64url_encode($b64_data);
289 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
291 $type = 'application/xml';
292 $encoding = 'base64url';
295 $signable_data = $data . '.' . base64url_encode($type) . '.'
296 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
298 $signature = rsa_sign($signable_data,$prvkey);
299 $sig = base64url_encode($signature);
301 $decrypted_header = <<< EOT
304 <aes_key>$b_inner_aes_key</aes_key>
305 <author_id>$handle</author_id>
309 $decrypted_header = pkcs5_pad($decrypted_header,16);
311 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
313 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
315 $encrypted_outer_key_bundle = '';
316 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
318 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
320 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
322 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
323 'ciphertext' => base64_encode($ciphertext)));
324 $cipher_json = base64_encode($encrypted_header_json_object);
326 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
329 <?xml version='1.0' encoding='UTF-8'?>
330 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
333 <me:encoding>base64url</me:encoding>
334 <me:alg>RSA-SHA256</me:alg>
335 <me:data type="application/xml">$data</me:data>
336 <me:sig>$sig</me:sig>
341 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
348 * diaspora_decode($importer,$xml)
349 * array $importer -> from user table
350 * string $xml -> urldecoded Diaspora salmon
353 * 'message' -> decoded Diaspora XML message
354 * 'author' -> author diaspora handle
355 * 'key' -> author public key (converted to pkcs#8)
357 * Author and key are used elsewhere to save a lookup for verifying replies and likes
361 function diaspora_decode($importer,$xml) {
364 $basedom = parse_xml_string($xml);
366 $children = $basedom->children('https://joindiaspora.com/protocol');
368 if($children->header) {
370 $author_link = str_replace('acct:','',$children->header->author_id);
374 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
376 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
377 $ciphertext = base64_decode($encrypted_header->ciphertext);
379 $outer_key_bundle = '';
380 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
382 $j_outer_key_bundle = json_decode($outer_key_bundle);
384 $outer_iv = base64_decode($j_outer_key_bundle->iv);
385 $outer_key = base64_decode($j_outer_key_bundle->key);
387 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
390 $decrypted = pkcs5_unpad($decrypted);
393 * $decrypted now contains something like
396 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
397 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
402 * <name>Ryan Hughes</name>
403 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
408 * <author_id>galaxor@diaspora.priateship.org</author_id>
412 * </decrypted_header>
415 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
416 $idom = parse_xml_string($decrypted,false);
418 $inner_iv = base64_decode($idom->iv);
419 $inner_aes_key = base64_decode($idom->aes_key);
421 $author_link = str_replace('acct:','',$idom->author_id);
425 $dom = $basedom->children(NAMESPACE_SALMON_ME);
427 // figure out where in the DOM tree our data is hiding
429 if($dom->provenance->data)
430 $base = $dom->provenance;
431 elseif($dom->env->data)
437 logger('mod-diaspora: unable to locate salmon data in xml ');
438 http_status_exit(400);
442 // Stash the signature away for now. We have to find their key or it won't be good for anything.
443 $signature = base64url_decode($base->sig);
447 // strip whitespace so our data element will return to one big base64 blob
448 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
451 // stash away some other stuff for later
453 $type = $base->data[0]->attributes()->type[0];
454 $keyhash = $base->sig[0]->attributes()->keyhash[0];
455 $encoding = $base->encoding;
459 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
463 $data = base64url_decode($data);
467 $inner_decrypted = $data;
471 // Decode the encrypted blob
473 $inner_encrypted = base64_decode($data);
474 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
475 $inner_decrypted = pkcs5_unpad($inner_decrypted);
479 logger('mod-diaspora: Could not retrieve author URI.');
480 http_status_exit(400);
483 // Once we have the author URI, go to the web and try to find their public key
484 // (first this will look it up locally if it is in the fcontact cache)
485 // This will also convert diaspora public key from pkcs#1 to pkcs#8
487 logger('mod-diaspora: Fetching key for ' . $author_link );
488 $key = get_diaspora_key($author_link);
491 logger('mod-diaspora: Could not retrieve author key.');
492 http_status_exit(400);
495 $verify = rsa_verify($signed_data,$signature,$key);
498 logger('mod-diaspora: Message did not verify. Discarding.');
499 http_status_exit(400);
502 logger('mod-diaspora: Message verified.');
504 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
509 function diaspora_request($importer,$xml) {
513 $sender_handle = unxmlify($xml->sender_handle);
514 $recipient_handle = unxmlify($xml->recipient_handle);
516 if(! $sender_handle || ! $recipient_handle)
519 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
523 // perhaps we were already sharing with this person. Now they're sharing with us.
524 // That makes us friends.
526 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
527 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
528 intval(CONTACT_IS_FRIEND),
529 intval($contact['id']),
530 intval($importer['uid'])
535 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
536 intval($importer['uid'])
539 if((count($r)) && (! $r[0]['hide-friends']) && (! $contact['hidden'])) {
540 require_once('include/items.php');
542 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
543 intval($importer['uid'])
546 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
548 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
551 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
552 $arr['uid'] = $importer['uid'];
553 $arr['contact-id'] = $self[0]['id'];
555 $arr['type'] = 'wall';
558 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
559 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
560 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
561 $arr['verb'] = ACTIVITY_FRIEND;
562 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
564 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
565 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
566 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
567 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
569 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
570 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
571 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
572 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
573 $arr['object'] .= '</link></object>' . "\n";
574 $arr['last-child'] = 1;
576 $arr['allow_cid'] = $user[0]['allow_cid'];
577 $arr['allow_gid'] = $user[0]['allow_gid'];
578 $arr['deny_cid'] = $user[0]['deny_cid'];
579 $arr['deny_gid'] = $user[0]['deny_gid'];
581 $i = item_store($arr);
583 proc_run('php',"include/notifier.php","activity","$i");
592 $ret = find_diaspora_person_by_handle($sender_handle);
595 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
596 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
600 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
604 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
605 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
606 intval($importer['uid']),
607 dbesc($ret['network']),
611 dbesc(normalise_link($ret['url'])),
615 dbesc($ret['photo']),
616 dbesc($ret['pubkey']),
617 dbesc($ret['notify']),
623 // find the contact record we just created
625 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
627 if(! $contact_record) {
628 logger('diaspora_request: unable to locate newly created contact record.');
632 $g = q("select def_gid from user where uid = %d limit 1",
633 intval($importer['uid'])
635 if($g && intval($g[0]['def_gid'])) {
636 require_once('include/group.php');
637 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
640 if($importer['page-flags'] == PAGE_NORMAL) {
642 $hash = random_string() . (string) time(); // Generate a confirm_key
644 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
645 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
646 intval($importer['uid']),
647 intval($contact_record['id']),
650 dbesc( t('Sharing notification from Diaspora network')),
652 dbesc(datetime_convert())
657 // automatic friend approval
659 require_once('include/Photo.php');
661 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
663 // technically they are sharing with us (CONTACT_IS_SHARING),
664 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
665 // we are going to change the relationship and make them a follower.
667 if($importer['page-flags'] == PAGE_FREELOVE)
668 $new_relation = CONTACT_IS_FRIEND;
670 $new_relation = CONTACT_IS_FOLLOWER;
672 $r = q("UPDATE `contact` SET
679 `avatar-date` = '%s',
682 WHERE `id` = %d LIMIT 1
687 intval($new_relation),
688 dbesc(datetime_convert()),
689 dbesc(datetime_convert()),
690 dbesc(datetime_convert()),
691 intval($contact_record['id'])
694 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
696 $ret = diaspora_share($u[0],$contact_record);
702 function diaspora_post_allow($importer,$contact) {
703 if(($contact['blocked']) || ($contact['readonly']))
705 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
707 if($contact['rel'] == CONTACT_IS_FOLLOWER)
708 if($importer['page-flags'] == PAGE_COMMUNITY)
714 function diaspora_post($importer,$xml) {
717 $guid = notags(unxmlify($xml->guid));
718 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
720 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
724 if(! diaspora_post_allow($importer,$contact)) {
725 logger('diaspora_post: Ignoring this author.');
729 $message_id = $diaspora_handle . ':' . $guid;
730 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
731 intval($importer['uid']),
736 logger('diaspora_post: message exists: ' . $guid);
740 // allocate a guid on our system - we aren't fixing any collisions.
741 // we're ignoring them
743 $g = q("select * from guid where guid = '%s' limit 1",
747 q("insert into guid ( guid ) values ( '%s' )",
752 $created = unxmlify($xml->created_at);
753 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
755 $body = diaspora2bb($xml->raw_message);
761 $tags = get_tags($body);
764 foreach($tags as $tag) {
765 if(strpos($tag,'#') === 0) {
766 if(strpos($tag,'[url='))
769 // don't link tags that are already embedded in links
771 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
773 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
776 $basetag = str_replace('_',' ',substr($tag,1));
777 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
778 if(strlen($str_tags))
780 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
786 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
788 foreach($matches as $mtch) {
789 if(strlen($str_tags))
791 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
795 $datarray['uid'] = $importer['uid'];
796 $datarray['contact-id'] = $contact['id'];
797 $datarray['wall'] = 0;
798 $datarray['guid'] = $guid;
799 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
800 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
801 $datarray['private'] = $private;
802 $datarray['parent'] = 0;
803 $datarray['owner-name'] = $contact['name'];
804 $datarray['owner-link'] = $contact['url'];
805 $datarray['owner-avatar'] = $contact['thumb'];
806 $datarray['author-name'] = $contact['name'];
807 $datarray['author-link'] = $contact['url'];
808 $datarray['author-avatar'] = $contact['thumb'];
809 $datarray['body'] = $body;
810 $datarray['tag'] = $str_tags;
811 $datarray['app'] = 'Diaspora';
813 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
815 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
817 $message_id = item_store($datarray);
820 q("update item set plink = '%s' where id = %d limit 1",
821 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
830 function diaspora_reshare($importer,$xml) {
832 logger('diaspora_reshare: init: ' . print_r($xml,true));
835 $guid = notags(unxmlify($xml->guid));
836 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
839 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
843 if(! diaspora_post_allow($importer,$contact)) {
844 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
848 $message_id = $diaspora_handle . ':' . $guid;
849 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
850 intval($importer['uid']),
855 logger('diaspora_reshare: message exists: ' . $guid);
859 $orig_author = notags(unxmlify($xml->root_diaspora_id));
860 $orig_guid = notags(unxmlify($xml->root_guid));
862 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
863 $x = fetch_url($source_url);
865 $x = fetch_url(str_replace('https://','http://',$source_url));
867 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
870 logger('diaspora_reshare: source: ' . $x);
872 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
873 $source_xml = parse_xml_string($x,false);
875 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
876 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
877 $body = scale_external_images($body,false);
879 elseif($source_xml->post->asphoto->image_url) {
880 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
881 $body = scale_external_images($body);
883 elseif($source_xml->post->status_message) {
884 $body = diaspora2bb($source_xml->post->status_message->raw_message);
885 $body = scale_external_images($body);
889 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
893 logger('diaspora_reshare: empty body: source= ' . $x);
897 $person = find_diaspora_person_by_handle($orig_author);
899 if(is_array($person) && x($person,'name') && x($person,'url'))
900 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
902 $details = $orig_author;
904 $prefix = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . $details . "\n";
907 // allocate a guid on our system - we aren't fixing any collisions.
908 // we're ignoring them
910 $g = q("select * from guid where guid = '%s' limit 1",
914 q("insert into guid ( guid ) values ( '%s' )",
919 $created = unxmlify($xml->created_at);
920 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
926 $tags = get_tags($body);
929 foreach($tags as $tag) {
930 if(strpos($tag,'#') === 0) {
931 if(strpos($tag,'[url='))
934 // don't link tags that are already embedded in links
936 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
938 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
942 $basetag = str_replace('_',' ',substr($tag,1));
943 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
944 if(strlen($str_tags))
946 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
952 $datarray['uid'] = $importer['uid'];
953 $datarray['contact-id'] = $contact['id'];
954 $datarray['wall'] = 0;
955 $datarray['guid'] = $guid;
956 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
957 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
958 $datarray['private'] = $private;
959 $datarray['parent'] = 0;
960 $datarray['owner-name'] = $contact['name'];
961 $datarray['owner-link'] = $contact['url'];
962 $datarray['owner-avatar'] = $contact['thumb'];
963 $datarray['author-name'] = $contact['name'];
964 $datarray['author-link'] = $contact['url'];
965 $datarray['author-avatar'] = $contact['thumb'];
966 $datarray['body'] = $prefix . $body;
967 $datarray['tag'] = $str_tags;
968 $datarray['app'] = 'Diaspora';
970 $message_id = item_store($datarray);
973 q("update item set plink = '%s' where id = %d limit 1",
974 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
984 function diaspora_asphoto($importer,$xml) {
985 logger('diaspora_asphoto called');
988 $guid = notags(unxmlify($xml->guid));
989 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
991 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
995 if(! diaspora_post_allow($importer,$contact)) {
996 logger('diaspora_asphoto: Ignoring this author.');
1000 $message_id = $diaspora_handle . ':' . $guid;
1001 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1002 intval($importer['uid']),
1007 logger('diaspora_asphoto: message exists: ' . $guid);
1011 // allocate a guid on our system - we aren't fixing any collisions.
1012 // we're ignoring them
1014 $g = q("select * from guid where guid = '%s' limit 1",
1018 q("insert into guid ( guid ) values ( '%s' )",
1023 $created = unxmlify($xml->created_at);
1024 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1026 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1027 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1028 $body = scale_external_images($body,false);
1030 elseif($xml->image_url) {
1031 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1032 $body = scale_external_images($body);
1035 logger('diaspora_asphoto: no photo url found.');
1039 $datarray = array();
1042 $datarray['uid'] = $importer['uid'];
1043 $datarray['contact-id'] = $contact['id'];
1044 $datarray['wall'] = 0;
1045 $datarray['guid'] = $guid;
1046 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1047 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1048 $datarray['private'] = $private;
1049 $datarray['parent'] = 0;
1050 $datarray['owner-name'] = $contact['name'];
1051 $datarray['owner-link'] = $contact['url'];
1052 $datarray['owner-avatar'] = $contact['thumb'];
1053 $datarray['author-name'] = $contact['name'];
1054 $datarray['author-link'] = $contact['url'];
1055 $datarray['author-avatar'] = $contact['thumb'];
1056 $datarray['body'] = $body;
1058 $datarray['app'] = 'Diaspora/Cubbi.es';
1060 $message_id = item_store($datarray);
1063 q("update item set plink = '%s' where id = %d limit 1",
1064 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1078 function diaspora_comment($importer,$xml,$msg) {
1081 $guid = notags(unxmlify($xml->guid));
1082 $parent_guid = notags(unxmlify($xml->parent_guid));
1083 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1084 $target_type = notags(unxmlify($xml->target_type));
1085 $text = unxmlify($xml->text);
1086 $author_signature = notags(unxmlify($xml->author_signature));
1088 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1090 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1092 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1096 if(! diaspora_post_allow($importer,$contact)) {
1097 logger('diaspora_comment: Ignoring this author.');
1101 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1102 intval($importer['uid']),
1106 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1110 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1111 intval($importer['uid']),
1115 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1118 $parent_item = $r[0];
1121 /* How Diaspora performs comment signature checking:
1123 - If an item has been sent by the comment author to the top-level post owner to relay on
1124 to the rest of the contacts on the top-level post, the top-level post owner should check
1125 the author_signature, then create a parent_author_signature before relaying the comment on
1126 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1127 check only the parent_author_signature. Basically, they trust that the top-level post
1128 owner has already verified the authenticity of anything he/she sends out
1129 - In either case, the signature that get checked is the signature created by the person
1133 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1136 if($parent_author_signature) {
1137 // If a parent_author_signature exists, then we've received the comment
1138 // relayed from the top-level post owner. There's no need to check the
1139 // author_signature if the parent_author_signature is valid
1141 $parent_author_signature = base64_decode($parent_author_signature);
1143 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1144 logger('diaspora_comment: top-level owner verification failed.');
1149 // If there's no parent_author_signature, then we've received the comment
1150 // from the comment creator. In that case, the person is commenting on
1151 // our post, so he/she must be a contact of ours and his/her public key
1152 // should be in $msg['key']
1154 $author_signature = base64_decode($author_signature);
1156 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1157 logger('diaspora_comment: comment author verification failed.');
1162 // Phew! Everything checks out. Now create an item.
1164 // Find the original comment author information.
1165 // We need this to make sure we display the comment author
1166 // information (name and avatar) correctly.
1167 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1170 $person = find_diaspora_person_by_handle($diaspora_handle);
1172 if(! is_array($person)) {
1173 logger('diaspora_comment: unable to find author details');
1178 $body = diaspora2bb($text);
1180 $message_id = $diaspora_handle . ':' . $guid;
1182 $datarray = array();
1186 $tags = get_tags($body);
1189 foreach($tags as $tag) {
1190 if(strpos($tag,'#') === 0) {
1191 if(strpos($tag,'[url='))
1194 // don't link tags that are already embedded in links
1196 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1198 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1202 $basetag = str_replace('_',' ',substr($tag,1));
1203 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1204 if(strlen($str_tags))
1206 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1212 $datarray['uid'] = $importer['uid'];
1213 $datarray['contact-id'] = $contact['id'];
1214 $datarray['wall'] = $parent_item['wall'];
1215 $datarray['gravity'] = GRAVITY_COMMENT;
1216 $datarray['guid'] = $guid;
1217 $datarray['uri'] = $message_id;
1218 $datarray['parent-uri'] = $parent_item['uri'];
1220 // No timestamps for comments? OK, we'll the use current time.
1221 $datarray['created'] = $datarray['edited'] = datetime_convert();
1222 $datarray['private'] = $parent_item['private'];
1224 $datarray['owner-name'] = $parent_item['owner-name'];
1225 $datarray['owner-link'] = $parent_item['owner-link'];
1226 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1228 $datarray['author-name'] = $person['name'];
1229 $datarray['author-link'] = $person['url'];
1230 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1231 $datarray['body'] = $body;
1232 $datarray['tag'] = $str_tags;
1234 // We can't be certain what the original app is if the message is relayed.
1235 if(($parent_item['origin']) && (! $parent_author_signature))
1236 $datarray['app'] = 'Diaspora';
1238 $message_id = item_store($datarray);
1241 q("update item set plink = '%s' where id = %d limit 1",
1242 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1247 if(($parent_item['origin']) && (! $parent_author_signature)) {
1248 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1249 intval($message_id),
1250 dbesc($author_signed_data),
1251 dbesc(base64_encode($author_signature)),
1252 dbesc($diaspora_handle)
1255 // if the message isn't already being relayed, notify others
1256 // the existence of parent_author_signature means the parent_author or owner
1257 // is already relaying.
1259 proc_run('php','include/notifier.php','comment',$message_id);
1262 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1263 dbesc($parent_item['uri']),
1264 intval($importer['uid'])
1267 if(count($myconv)) {
1268 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1270 foreach($myconv as $conv) {
1272 // now if we find a match, it means we're in this conversation
1274 if(! link_compare($conv['author-link'],$importer_url))
1277 require_once('include/enotify.php');
1279 $conv_parent = $conv['parent'];
1282 'type' => NOTIFY_COMMENT,
1283 'notify_flags' => $importer['notify-flags'],
1284 'language' => $importer['language'],
1285 'to_name' => $importer['username'],
1286 'to_email' => $importer['email'],
1287 'uid' => $importer['uid'],
1288 'item' => $datarray,
1289 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id,
1290 'source_name' => $datarray['author-name'],
1291 'source_link' => $datarray['author-link'],
1292 'source_photo' => $datarray['author-avatar'],
1293 'verb' => ACTIVITY_POST,
1295 'parent' => $conv_parent,
1299 // only send one notification
1309 function diaspora_conversation($importer,$xml,$msg) {
1313 $guid = notags(unxmlify($xml->guid));
1314 $subject = notags(unxmlify($xml->subject));
1315 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1316 $participant_handles = notags(unxmlify($xml->participant_handles));
1317 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1319 $parent_uri = $diaspora_handle . ':' . $guid;
1321 $messages = $xml->message;
1323 if(! count($messages)) {
1324 logger('diaspora_conversation: empty conversation');
1328 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1330 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1334 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1335 logger('diaspora_conversation: Ignoring this author.');
1339 $conversation = null;
1341 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1342 intval($importer['uid']),
1346 $conversation = $c[0];
1348 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1349 intval($importer['uid']),
1351 dbesc($diaspora_handle),
1352 dbesc(datetime_convert('UTC','UTC',$created_at)),
1353 dbesc(datetime_convert()),
1355 dbesc($participant_handles)
1358 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1359 intval($importer['uid']),
1363 $conversation = $c[0];
1365 if(! $conversation) {
1366 logger('diaspora_conversation: unable to create conversation.');
1370 foreach($messages as $mesg) {
1374 $msg_guid = notags(unxmlify($mesg->guid));
1375 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1376 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1377 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1378 $msg_text = unxmlify($mesg->text);
1379 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1380 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1381 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1382 if($msg_conversation_guid != $guid) {
1383 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1387 $body = diaspora2bb($msg_text);
1388 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1390 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1392 $author_signature = base64_decode($msg_author_signature);
1394 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1399 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1401 if(is_array($person) && x($person,'pubkey'))
1402 $key = $person['pubkey'];
1404 logger('diaspora_conversation: unable to find author details');
1409 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1410 logger('diaspora_conversation: verification failed.');
1414 if($msg_parent_author_signature) {
1415 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1417 $parent_author_signature = base64_decode($msg_parent_author_signature);
1421 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1422 logger('diaspora_conversation: owner verification failed.');
1427 $r = q("select id from mail where `uri` = '%s' limit 1",
1431 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1435 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')",
1436 intval($importer['uid']),
1438 intval($conversation['id']),
1439 dbesc($person['name']),
1440 dbesc($person['photo']),
1441 dbesc($person['url']),
1442 intval($contact['id']),
1449 dbesc($msg_created_at)
1452 q("update conv set updated = '%s' where id = %d limit 1",
1453 dbesc(datetime_convert()),
1454 intval($conversation['id'])
1457 require_once('include/enotify.php');
1459 'type' => NOTIFY_MAIL,
1460 'notify_flags' => $importer['notify-flags'],
1461 'language' => $importer['language'],
1462 'to_name' => $importer['username'],
1463 'to_email' => $importer['email'],
1464 'uid' =>$importer['importer_uid'],
1465 'item' => array('subject' => $subject, 'body' => $body),
1466 'source_name' => $person['name'],
1467 'source_link' => $person['url'],
1468 'source_photo' => $person['thumb'],
1469 'verb' => ACTIVITY_POST,
1477 function diaspora_message($importer,$xml,$msg) {
1481 $msg_guid = notags(unxmlify($xml->guid));
1482 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1483 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1484 $msg_author_signature = notags(unxmlify($xml->author_signature));
1485 $msg_text = unxmlify($xml->text);
1486 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1487 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1488 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1490 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1492 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1494 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1498 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1499 logger('diaspora_message: Ignoring this author.');
1503 $conversation = null;
1505 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1506 intval($importer['uid']),
1507 dbesc($msg_conversation_guid)
1510 $conversation = $c[0];
1512 logger('diaspora_message: conversation not available.');
1518 $body = diaspora2bb($msg_text);
1519 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1521 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1524 $author_signature = base64_decode($msg_author_signature);
1526 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1527 if(is_array($person) && x($person,'pubkey'))
1528 $key = $person['pubkey'];
1530 logger('diaspora_message: unable to find author details');
1534 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1535 logger('diaspora_message: verification failed.');
1539 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1541 intval($importer['uid'])
1544 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1548 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')",
1549 intval($importer['uid']),
1551 intval($conversation['id']),
1552 dbesc($person['name']),
1553 dbesc($person['photo']),
1554 dbesc($person['url']),
1555 intval($contact['id']),
1556 dbesc($conversation['subject']),
1562 dbesc($msg_created_at)
1565 q("update conv set updated = '%s' where id = %d limit 1",
1566 dbesc(datetime_convert()),
1567 intval($conversation['id'])
1574 function diaspora_photo($importer,$xml,$msg) {
1578 logger('diaspora_photo: init',LOGGER_DEBUG);
1580 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1582 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1584 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1586 $guid = notags(unxmlify($xml->guid));
1588 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1590 $public = notags(unxmlify($xml->public));
1592 $created_at = notags(unxmlify($xml_created_at));
1594 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1596 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1598 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1602 if(! diaspora_post_allow($importer,$contact)) {
1603 logger('diaspora_photo: Ignoring this author.');
1607 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1608 intval($importer['uid']),
1609 dbesc($status_message_guid)
1612 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1616 $parent_item = $r[0];
1618 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1620 $link_text = scale_external_images($link_text, true,
1621 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1623 if(strpos($parent_item['body'],$link_text) === false) {
1624 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1625 dbesc($link_text . $parent_item['body']),
1626 intval($parent_item['id']),
1627 intval($parent_item['uid'])
1637 function diaspora_like($importer,$xml,$msg) {
1640 $guid = notags(unxmlify($xml->guid));
1641 $parent_guid = notags(unxmlify($xml->parent_guid));
1642 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1643 $target_type = notags(unxmlify($xml->target_type));
1644 $positive = notags(unxmlify($xml->positive));
1645 $author_signature = notags(unxmlify($xml->author_signature));
1647 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1649 // likes on comments not supported here and likes on photos not supported by Diaspora
1651 if($target_type !== 'Post')
1654 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1656 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1660 if(! diaspora_post_allow($importer,$contact)) {
1661 logger('diaspora_like: Ignoring this author.');
1665 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1666 intval($importer['uid']),
1670 logger('diaspora_like: parent item not found: ' . $guid);
1674 $parent_item = $r[0];
1676 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1677 intval($importer['uid']),
1681 if($positive === 'true') {
1682 logger('diaspora_like: duplicate like: ' . $guid);
1685 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1686 // It looks like "RelayableRetractions" are used for "unlike" instead
1687 if($positive === 'false') {
1688 logger('diaspora_like: received a like with positive set to "false"...ignoring');
1689 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1690 intval($r[0]['id']),
1691 intval($importer['uid'])
1693 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1694 // send notification via proc_run()
1698 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1699 // It looks like "RelayableRetractions" are used for "unlike" instead
1700 if($positive === 'false') {
1701 logger('diaspora_like: received a like with positive set to "false"');
1702 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1707 /* How Diaspora performs "like" signature checking:
1709 - If an item has been sent by the like author to the top-level post owner to relay on
1710 to the rest of the contacts on the top-level post, the top-level post owner should check
1711 the author_signature, then create a parent_author_signature before relaying the like on
1712 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1713 check only the parent_author_signature. Basically, they trust that the top-level post
1714 owner has already verified the authenticity of anything he/she sends out
1715 - In either case, the signature that get checked is the signature created by the person
1719 $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1722 if($parent_author_signature) {
1723 // If a parent_author_signature exists, then we've received the like
1724 // relayed from the top-level post owner. There's no need to check the
1725 // author_signature if the parent_author_signature is valid
1727 $parent_author_signature = base64_decode($parent_author_signature);
1729 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1730 logger('diaspora_like: top-level owner verification failed.');
1735 // If there's no parent_author_signature, then we've received the like
1736 // from the like creator. In that case, the person is "like"ing
1737 // our post, so he/she must be a contact of ours and his/her public key
1738 // should be in $msg['key']
1740 $author_signature = base64_decode($author_signature);
1742 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1743 logger('diaspora_like: like creator verification failed.');
1748 // Phew! Everything checks out. Now create an item.
1750 // Find the original comment author information.
1751 // We need this to make sure we display the comment author
1752 // information (name and avatar) correctly.
1753 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1756 $person = find_diaspora_person_by_handle($diaspora_handle);
1758 if(! is_array($person)) {
1759 logger('diaspora_like: unable to find author details');
1764 $uri = $diaspora_handle . ':' . $guid;
1766 $activity = ACTIVITY_LIKE;
1767 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1768 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1769 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1770 $body = $parent_item['body'];
1775 <type>$objtype</type>
1777 <id>{$parent_item['uri']}</id>
1780 <content>$body</content>
1783 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1788 $arr['uid'] = $importer['uid'];
1789 $arr['guid'] = $guid;
1790 $arr['contact-id'] = $contact['id'];
1791 $arr['type'] = 'activity';
1792 $arr['wall'] = $parent_item['wall'];
1793 $arr['gravity'] = GRAVITY_LIKE;
1794 $arr['parent'] = $parent_item['id'];
1795 $arr['parent-uri'] = $parent_item['uri'];
1797 $arr['owner-name'] = $parent_item['name'];
1798 $arr['owner-link'] = $parent_item['url'];
1799 $arr['owner-avatar'] = $parent_item['thumb'];
1801 $arr['author-name'] = $person['name'];
1802 $arr['author-link'] = $person['url'];
1803 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1805 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1806 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1807 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1808 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1810 $arr['app'] = 'Diaspora';
1812 $arr['private'] = $parent_item['private'];
1813 $arr['verb'] = $activity;
1814 $arr['object-type'] = $objtype;
1815 $arr['object'] = $obj;
1816 $arr['visible'] = 1;
1818 $arr['last-child'] = 0;
1820 $message_id = item_store($arr);
1824 q("update item set plink = '%s' where id = %d limit 1",
1825 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1830 if(! $parent_author_signature) {
1831 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1832 intval($message_id),
1833 dbesc($author_signed_data),
1834 dbesc(base64_encode($author_signature)),
1835 dbesc($diaspora_handle)
1839 // if the message isn't already being relayed, notify others
1840 // the existence of parent_author_signature means the parent_author or owner
1841 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1843 if(($parent_item['origin']) && (! $parent_author_signature))
1844 proc_run('php','include/notifier.php','comment',$message_id);
1849 function diaspora_retraction($importer,$xml) {
1852 $guid = notags(unxmlify($xml->guid));
1853 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1854 $type = notags(unxmlify($xml->type));
1856 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1860 if($type === 'Person') {
1861 require_once('include/Contact.php');
1862 contact_remove($contact['id']);
1864 elseif($type === 'Post') {
1865 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1867 intval($importer['uid'])
1870 if(link_compare($r[0]['author-link'],$contact['url'])) {
1871 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1872 dbesc(datetime_convert()),
1883 function diaspora_signed_retraction($importer,$xml,$msg) {
1886 $guid = notags(unxmlify($xml->target_guid));
1887 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1888 $type = notags(unxmlify($xml->target_type));
1889 $sig = notags(unxmlify($xml->target_author_signature));
1891 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1893 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1895 logger('diaspora_signed_retraction: no contact');
1900 $signed_data = $guid . ';' . $type ;
1903 /* How Diaspora performs relayable_retraction signature checking:
1905 - If an item has been sent by the item author to the top-level post owner to relay on
1906 to the rest of the contacts on the top-level post, the top-level post owner checks
1907 the author_signature, then creates a parent_author_signature before relaying the item on
1908 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1909 check only the parent_author_signature. Basically, they trust that the top-level post
1910 owner has already verified the authenticity of anything he/she sends out
1911 - In either case, the signature that get checked is the signature created by the person
1915 if($parent_author_signature) {
1917 $parent_author_signature = base64_decode($parent_author_signature);
1919 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1920 logger('diaspora_signed_retraction: top-level post owner verification failed');
1927 $sig_decode = base64_decode($sig);
1929 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
1930 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
1935 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
1936 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1938 intval($importer['uid'])
1941 if(link_compare($r[0]['author-link'],$contact['url'])) {
1942 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d limit 1",
1943 dbesc(datetime_convert()),
1944 dbesc(datetime_convert()),
1948 // Now check if the retraction needs to be relayed by us
1950 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
1951 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
1952 // The only item with `parent` and `id` as the parent id is the parent item.
1953 $p = q("select origin from item where parent = %d and id = %d limit 1",
1958 if(($p[0]['origin']) && (! $parent_author_signature)) {
1959 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1961 dbesc($signed_data),
1963 dbesc($diaspora_handle)
1966 // the existence of parent_author_signature would have meant the parent_author or owner
1967 // is already relaying.
1968 logger('diaspora_signed_retraction: relaying relayable_retraction');
1970 proc_run('php','include/notifier.php','relayable_retraction',$r[0]['id']);
1977 logger('diaspora_signed_retraction: unknown type: ' . $type);
1983 function diaspora_profile($importer,$xml) {
1986 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1988 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1992 if($contact['blocked']) {
1993 logger('diaspora_post: Ignoring this author.');
1997 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1998 $image_url = unxmlify($xml->image_url);
1999 $birthday = unxmlify($xml->birthday);
2001 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2002 intval($importer['uid']),
2003 intval($contact['id'])
2005 $oldphotos = ((count($r)) ? $r : null);
2007 require_once('include/Photo.php');
2009 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2011 // Generic birthday. We don't know the timezone. The year is irrelevant.
2013 $birthday = str_replace('1000','1901',$birthday);
2015 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2017 // this is to prevent multiple birthday notifications in a single year
2018 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2020 if(substr($birthday,5) === substr($contact['bd'],5))
2021 $birthday = $contact['bd'];
2023 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2024 // Not doing this currently because D* protocol is scheduled for revision soon.
2026 $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",
2028 dbesc(datetime_convert()),
2032 dbesc(datetime_convert()),
2034 intval($contact['id']),
2035 intval($importer['uid'])
2040 foreach($oldphotos as $ph) {
2041 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2042 intval($importer['uid']),
2043 intval($contact['id']),
2044 dbesc($ph['resource-id'])
2054 function diaspora_share($me,$contact) {
2056 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2057 $theiraddr = $contact['addr'];
2059 $tpl = get_markup_template('diaspora_share.tpl');
2060 $msg = replace_macros($tpl, array(
2061 '$sender' => $myaddr,
2062 '$recipient' => $theiraddr
2065 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2066 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2068 return(diaspora_transmit($owner,$contact,$slap, false));
2071 function diaspora_unshare($me,$contact) {
2074 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2076 $tpl = get_markup_template('diaspora_retract.tpl');
2077 $msg = replace_macros($tpl, array(
2078 '$guid' => $me['guid'],
2079 '$type' => 'Person',
2080 '$handle' => $myaddr
2083 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2084 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2086 return(diaspora_transmit($owner,$contact,$slap, false));
2092 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2095 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2096 $theiraddr = $contact['addr'];
2100 $title = $item['title'];
2101 $body = $item['body'];
2104 // We're trying to match Diaspora's split message/photo protocol but
2105 // all the photos are displayed on D* as links and not img's - even
2106 // though we're sending pretty much precisely what they send us when
2107 // doing the same operation.
2108 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2109 // which seems to get through intact.
2111 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2113 foreach($matches as $mtch) {
2115 $detail['str'] = $mtch[0];
2116 $detail['path'] = dirname($mtch[1]) . '/';
2117 $detail['file'] = basename($mtch[1]);
2118 $detail['guid'] = $item['guid'];
2119 $detail['handle'] = $myaddr;
2120 $images[] = $detail;
2121 $body = str_replace($detail['str'],$mtch[1],$body);
2126 $body = preg_replace('/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $body);
2128 //if(strlen($title))
2129 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2131 // convert to markdown
2132 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2133 //$body = bb2diaspora($body);
2137 $body = "## ".html_entity_decode($title)."\n\n".$body;
2139 if($item['attach']) {
2140 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2142 $body .= "\n" . t('Attachments:') . "\n";
2143 foreach($matches as $mtch) {
2144 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2150 $public = (($item['private']) ? 'false' : 'true');
2152 require_once('include/datetime.php');
2153 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2155 $tpl = get_markup_template('diaspora_post.tpl');
2156 $msg = replace_macros($tpl, array(
2158 '$guid' => $item['guid'],
2159 '$handle' => xmlify($myaddr),
2160 '$public' => $public,
2161 '$created' => $created
2164 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
2166 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2167 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2169 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2171 if(count($images)) {
2172 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2175 return $return_code;
2179 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2181 if(! count($images))
2183 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2185 $tpl = get_markup_template('diaspora_photo.tpl');
2186 foreach($images as $image) {
2187 if(! stristr($image['path'],$mysite))
2189 $resource = str_replace('.jpg','',$image['file']);
2190 $resource = substr($resource,0,strpos($resource,'-'));
2192 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2194 intval($owner['uid'])
2198 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2199 $msg = replace_macros($tpl,array(
2200 '$path' => xmlify($image['path']),
2201 '$filename' => xmlify($image['file']),
2202 '$msg_guid' => xmlify($image['guid']),
2203 '$guid' => xmlify($r[0]['guid']),
2204 '$handle' => xmlify($image['handle']),
2205 '$public' => xmlify($public),
2206 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2210 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2211 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2212 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2214 diaspora_transmit($owner,$contact,$slap,$public_batch);
2219 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2222 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2223 // $theiraddr = $contact['addr'];
2225 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2226 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2227 // The only item with `parent` and `id` as the parent id is the parent item.
2228 $p = q("select guid from item where parent = %d and id = %d limit 1",
2229 intval($item['parent']),
2230 intval($item['parent'])
2233 $parent_guid = $p[0]['guid'];
2237 if($item['verb'] === ACTIVITY_LIKE) {
2238 $tpl = get_markup_template('diaspora_like.tpl');
2240 $target_type = 'Post';
2241 // $positive = (($item['deleted']) ? 'false' : 'true');
2244 if(($item['deleted']))
2245 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2248 $tpl = get_markup_template('diaspora_comment.tpl');
2252 $text = html_entity_decode(bb2diaspora($item['body']));
2257 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
2259 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
2261 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2263 $msg = replace_macros($tpl,array(
2264 '$guid' => xmlify($item['guid']),
2265 '$parent_guid' => xmlify($parent_guid),
2266 '$target_type' =>xmlify($target_type),
2267 '$authorsig' => xmlify($authorsig),
2268 '$body' => xmlify($text),
2269 '$positive' => xmlify($positive),
2270 '$handle' => xmlify($myaddr)
2273 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2275 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2276 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2278 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2282 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2286 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2287 // $theiraddr = $contact['addr'];
2289 $body = $item['body'];
2290 $text = html_entity_decode(bb2diaspora($body));
2293 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2294 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2295 // The only item with `parent` and `id` as the parent id is the parent item.
2296 $p = q("select guid from item where parent = %d and id = %d limit 1",
2297 intval($item['parent']),
2298 intval($item['parent'])
2301 $parent_guid = $p[0]['guid'];
2306 $relay_retract = false;
2307 $sql_sign_id = 'iid';
2308 if( $item['deleted']) {
2309 $relay_retract = true;
2311 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2313 $sql_sign_id = 'retract_iid';
2314 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2316 elseif($item['verb'] === ACTIVITY_LIKE) {
2319 $target_type = 'Post';
2320 // $positive = (($item['deleted']) ? 'false' : 'true');
2323 $tpl = get_markup_template('diaspora_like_relay.tpl');
2325 else { // item is a comment
2326 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2330 // fetch the original signature if the relayable was created by a Diaspora
2331 // or DFRN user. Relayables for other networks are not supported.
2333 $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2338 $signed_text = $orig_sign['signed_text'];
2339 $authorsig = $orig_sign['signature'];
2340 $handle = $orig_sign['signer'];
2344 // Author signature information (for likes, comments, and retractions of likes or comments,
2345 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2346 // function is called
2347 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2352 $sender_signed_text = $item['guid'] . ';' . $target_type;
2354 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $handle;
2356 $sender_signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $handle;
2358 // Sign the relayable with the top-level owner's signature
2360 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2361 // stored in the database, because that provides the best chance that Diaspora will
2362 // be able to reconstruct the signed text the same way we did. This is particularly a
2363 // concern for the comment, whose signed text includes the text of the comment. The
2364 // smallest change in the text of the comment, including removing whitespace, will
2365 // make the signature verification fail. Since we translate from BB code to Diaspora's
2366 // markup at the top of this function, which is AFTER we placed the original $signed_text
2367 // in the database, it's hazardous to trust the original $signed_text.
2369 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2371 $msg = replace_macros($tpl,array(
2372 '$guid' => xmlify($item['guid']),
2373 '$parent_guid' => xmlify($parent_guid),
2374 '$target_type' =>xmlify($target_type),
2375 '$authorsig' => xmlify($authorsig),
2376 '$parentsig' => xmlify($parentauthorsig),
2377 '$body' => xmlify($text),
2378 '$positive' => xmlify($positive),
2379 '$handle' => xmlify($handle)
2382 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2385 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2386 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2388 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2394 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2397 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2399 // Check whether the retraction is for a top-level post or whether it's a relayable
2400 if( $item['uri'] !== $item['parent-uri'] ) {
2402 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2403 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2407 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2408 $target_type = 'StatusMessage';
2411 $signed_text = $item['guid'] . ';' . $target_type;
2413 $msg = replace_macros($tpl, array(
2414 '$guid' => xmlify($item['guid']),
2415 '$type' => xmlify($target_type),
2416 '$handle' => xmlify($myaddr),
2417 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2420 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2421 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2423 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2426 function diaspora_send_mail($item,$owner,$contact) {
2429 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2431 $r = q("select * from conv where id = %d and uid = %d limit 1",
2432 intval($item['convid']),
2433 intval($item['uid'])
2437 logger('diaspora_send_mail: conversation not found.');
2443 'guid' => xmlify($cnv['guid']),
2444 'subject' => xmlify($cnv['subject']),
2445 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2446 'diaspora_handle' => xmlify($cnv['creator']),
2447 'participant_handles' => xmlify($cnv['recips'])
2450 $body = bb2diaspora($item['body']);
2451 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2453 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2454 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2456 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2459 'guid' => xmlify($item['guid']),
2460 'parent_guid' => xmlify($cnv['guid']),
2461 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2462 'author_signature' => xmlify($sig),
2463 'text' => xmlify($body),
2464 'created_at' => xmlify($created),
2465 'diaspora_handle' => xmlify($myaddr),
2466 'conversation_guid' => xmlify($cnv['guid'])
2469 if($item['reply']) {
2470 $tpl = get_markup_template('diaspora_message.tpl');
2471 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2474 $conv['messages'] = array($msg);
2475 $tpl = get_markup_template('diaspora_conversation.tpl');
2476 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2479 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2481 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2482 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2484 return(diaspora_transmit($owner,$contact,$slap,false));
2489 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
2491 $enabled = intval(get_config('system','diaspora_enabled'));
2497 $logid = random_string(4);
2498 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2500 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2504 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2506 if(was_recently_delayed($contact['id'])) {
2510 if(! intval(get_config('system','diaspora_test'))) {
2511 post_url($dest_url . '/', $slap);
2512 $return_code = $a->get_curl_code();
2515 logger('diaspora_transmit: test_mode');
2520 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2522 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2523 logger('diaspora_transmit: queue message');
2525 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2526 intval($contact['id']),
2527 dbesc(NETWORK_DIASPORA),
2529 intval($public_batch)
2532 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2535 // queue message for redelivery
2536 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2541 return(($return_code) ? $return_code : (-1));