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');
10 function diaspora_dispatch_public($msg) {
12 $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 ",
13 dbesc(NETWORK_DIASPORA),
18 logger('diaspora_public: delivering to: ' . $rr['username']);
19 diaspora_dispatch($rr,$msg);
23 logger('diaspora_public: no subscribers');
28 function diaspora_dispatch($importer,$msg) {
32 // php doesn't like dashes in variable names
34 $msg['message'] = str_replace(
35 array('<activity_streams-photo>','</activity_streams-photo>'),
36 array('<asphoto>','</asphoto>'),
40 $parsed_xml = parse_xml_string($msg['message'],false);
42 $xmlbase = $parsed_xml->post;
44 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
47 if($xmlbase->request) {
48 $ret = diaspora_request($importer,$xmlbase->request);
50 elseif($xmlbase->status_message) {
51 $ret = diaspora_post($importer,$xmlbase->status_message);
53 elseif($xmlbase->profile) {
54 $ret = diaspora_profile($importer,$xmlbase->profile);
56 elseif($xmlbase->comment) {
57 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
59 elseif($xmlbase->like) {
60 $ret = diaspora_like($importer,$xmlbase->like,$msg);
62 elseif($xmlbase->asphoto) {
63 $ret = diaspora_asphoto($importer,$xmlbase->asphoto);
65 elseif($xmlbase->reshare) {
66 $ret = diaspora_reshare($importer,$xmlbase->reshare);
68 elseif($xmlbase->retraction) {
69 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
71 elseif($xmlbase->signed_retraction) {
72 $ret = diaspora_signed_retraction($importer,$xmlbase->retraction,$msg);
74 elseif($xmlbase->photo) {
75 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
77 elseif($xmlbase->conversation) {
78 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
81 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
86 function diaspora_get_contact_by_handle($uid,$handle) {
87 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
88 dbesc(NETWORK_DIASPORA),
97 function find_diaspora_person_by_handle($handle) {
99 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
100 dbesc(NETWORK_DIASPORA),
104 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
105 // update record occasionally so it doesn't get stale
106 $d = strtotime($r[0]['updated'] . ' +00:00');
107 if($d > strtotime('now - 14 days'))
111 logger('find_diaspora_person_by_handle: refresh',LOGGER_DEBUG);
112 require_once('include/Scrape.php');
113 $r = probe_url($handle, PROBE_DIASPORA);
114 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
115 add_fcontact($r,$update);
122 function get_diaspora_key($uri) {
123 logger('Fetching diaspora key for: ' . $uri);
125 $r = find_diaspora_person_by_handle($uri);
132 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
135 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
138 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
140 // $b64_data = base64_encode($msg);
141 // $b64url_data = base64url_encode($b64_data);
143 $b64url_data = base64url_encode($msg);
145 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
147 $type = 'application/xml';
148 $encoding = 'base64url';
151 $signable_data = $data . '.' . base64url_encode($type) . '.'
152 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
154 $signature = rsa_sign($signable_data,$prvkey);
155 $sig = base64url_encode($signature);
158 <?xml version='1.0' encoding='UTF-8'?>
159 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
161 <author_id>$handle</author_id>
164 <me:encoding>base64url</me:encoding>
165 <me:alg>RSA-SHA256</me:alg>
166 <me:data type="application/xml">$data</me:data>
167 <me:sig>$sig</me:sig>
172 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
180 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
184 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
186 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
188 $inner_aes_key = random_string(32);
189 $b_inner_aes_key = base64_encode($inner_aes_key);
190 $inner_iv = random_string(16);
191 $b_inner_iv = base64_encode($inner_iv);
193 $outer_aes_key = random_string(32);
194 $b_outer_aes_key = base64_encode($outer_aes_key);
195 $outer_iv = random_string(16);
196 $b_outer_iv = base64_encode($outer_iv);
198 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
200 $padded_data = pkcs5_pad($msg,16);
201 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
203 $b64_data = base64_encode($inner_encrypted);
206 $b64url_data = base64url_encode($b64_data);
207 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
209 $type = 'application/xml';
210 $encoding = 'base64url';
213 $signable_data = $data . '.' . base64url_encode($type) . '.'
214 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
216 $signature = rsa_sign($signable_data,$prvkey);
217 $sig = base64url_encode($signature);
219 $decrypted_header = <<< EOT
222 <aes_key>$b_inner_aes_key</aes_key>
223 <author_id>$handle</author_id>
227 $decrypted_header = pkcs5_pad($decrypted_header,16);
229 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
231 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
233 $encrypted_outer_key_bundle = '';
234 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
236 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
238 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
240 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
241 'ciphertext' => base64_encode($ciphertext)));
242 $cipher_json = base64_encode($encrypted_header_json_object);
244 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
247 <?xml version='1.0' encoding='UTF-8'?>
248 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
251 <me:encoding>base64url</me:encoding>
252 <me:alg>RSA-SHA256</me:alg>
253 <me:data type="application/xml">$data</me:data>
254 <me:sig>$sig</me:sig>
259 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
266 * diaspora_decode($importer,$xml)
267 * array $importer -> from user table
268 * string $xml -> urldecoded Diaspora salmon
271 * 'message' -> decoded Diaspora XML message
272 * 'author' -> author diaspora handle
273 * 'key' -> author public key (converted to pkcs#8)
275 * Author and key are used elsewhere to save a lookup for verifying replies and likes
279 function diaspora_decode($importer,$xml) {
282 $basedom = parse_xml_string($xml);
284 $children = $basedom->children('https://joindiaspora.com/protocol');
286 if($children->header) {
288 $author_link = str_replace('acct:','',$children->header->author_id);
292 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
294 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
295 $ciphertext = base64_decode($encrypted_header->ciphertext);
297 $outer_key_bundle = '';
298 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
300 $j_outer_key_bundle = json_decode($outer_key_bundle);
302 $outer_iv = base64_decode($j_outer_key_bundle->iv);
303 $outer_key = base64_decode($j_outer_key_bundle->key);
305 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
308 $decrypted = pkcs5_unpad($decrypted);
311 * $decrypted now contains something like
314 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
315 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
320 * <name>Ryan Hughes</name>
321 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
326 * <author_id>galaxor@diaspora.priateship.org</author_id>
330 * </decrypted_header>
333 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
334 $idom = parse_xml_string($decrypted,false);
336 $inner_iv = base64_decode($idom->iv);
337 $inner_aes_key = base64_decode($idom->aes_key);
339 $author_link = str_replace('acct:','',$idom->author_id);
343 $dom = $basedom->children(NAMESPACE_SALMON_ME);
345 // figure out where in the DOM tree our data is hiding
347 if($dom->provenance->data)
348 $base = $dom->provenance;
349 elseif($dom->env->data)
355 logger('mod-diaspora: unable to locate salmon data in xml ');
356 http_status_exit(400);
360 // Stash the signature away for now. We have to find their key or it won't be good for anything.
361 $signature = base64url_decode($base->sig);
365 // strip whitespace so our data element will return to one big base64 blob
366 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
369 // stash away some other stuff for later
371 $type = $base->data[0]->attributes()->type[0];
372 $keyhash = $base->sig[0]->attributes()->keyhash[0];
373 $encoding = $base->encoding;
377 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
381 $data = base64url_decode($data);
385 $inner_decrypted = $data;
389 // Decode the encrypted blob
391 $inner_encrypted = base64_decode($data);
392 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
393 $inner_decrypted = pkcs5_unpad($inner_decrypted);
397 logger('mod-diaspora: Could not retrieve author URI.');
398 http_status_exit(400);
401 // Once we have the author URI, go to the web and try to find their public key
402 // (first this will look it up locally if it is in the fcontact cache)
403 // This will also convert diaspora public key from pkcs#1 to pkcs#8
405 logger('mod-diaspora: Fetching key for ' . $author_link );
406 $key = get_diaspora_key($author_link);
409 logger('mod-diaspora: Could not retrieve author key.');
410 http_status_exit(400);
413 $verify = rsa_verify($signed_data,$signature,$key);
416 logger('mod-diaspora: Message did not verify. Discarding.');
417 http_status_exit(400);
420 logger('mod-diaspora: Message verified.');
422 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
427 function diaspora_request($importer,$xml) {
431 $sender_handle = unxmlify($xml->sender_handle);
432 $recipient_handle = unxmlify($xml->recipient_handle);
434 if(! $sender_handle || ! $recipient_handle)
437 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
441 // perhaps we were already sharing with this person. Now they're sharing with us.
442 // That makes us friends.
444 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
445 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
446 intval(CONTACT_IS_FRIEND),
447 intval($contact['id']),
448 intval($importer['uid'])
453 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
454 intval($importer['uid'])
457 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
458 require_once('include/items.php');
460 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
461 intval($importer['uid'])
464 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
466 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
469 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
470 $arr['uid'] = $importer['uid'];
471 $arr['contact-id'] = $self[0]['id'];
473 $arr['type'] = 'wall';
476 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
477 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
478 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
479 $arr['verb'] = ACTIVITY_FRIEND;
480 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
482 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
483 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
484 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
485 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
487 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
488 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
489 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
490 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
491 $arr['object'] .= '</link></object>' . "\n";
492 $arr['last-child'] = 1;
494 $arr['allow_cid'] = $user[0]['allow_cid'];
495 $arr['allow_gid'] = $user[0]['allow_gid'];
496 $arr['deny_cid'] = $user[0]['deny_cid'];
497 $arr['deny_gid'] = $user[0]['deny_gid'];
499 $i = item_store($arr);
501 proc_run('php',"include/notifier.php","activity","$i");
510 $ret = find_diaspora_person_by_handle($sender_handle);
513 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
514 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
518 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
520 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
521 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
522 intval($importer['uid']),
523 dbesc($ret['network']),
527 dbesc(normalise_link($ret['url'])),
531 dbesc($ret['photo']),
532 dbesc($ret['pubkey']),
533 dbesc($ret['notify']),
539 // find the contact record we just created
541 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
543 $hash = random_string() . (string) time(); // Generate a confirm_key
545 if($contact_record) {
546 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
547 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
548 intval($importer['uid']),
549 intval($contact_record['id']),
552 dbesc( t('Sharing notification from Diaspora network')),
554 dbesc(datetime_convert())
561 function diaspora_post($importer,$xml) {
564 $guid = notags(unxmlify($xml->guid));
565 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
567 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
571 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
572 logger('diaspora_post: Ignoring this author.');
576 $message_id = $diaspora_handle . ':' . $guid;
577 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
578 intval($importer['uid']),
583 logger('diaspora_post: message exists: ' . $guid);
587 // allocate a guid on our system - we aren't fixing any collisions.
588 // we're ignoring them
590 $g = q("select * from guid where guid = '%s' limit 1",
594 q("insert into guid ( guid ) values ( '%s' )",
599 $created = unxmlify($xml->created_at);
600 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
602 $body = diaspora2bb($xml->raw_message);
608 $tags = get_tags($body);
611 foreach($tags as $tag) {
612 if(strpos($tag,'#') === 0) {
613 if(strpos($tag,'[url='))
615 $basetag = str_replace('_',' ',substr($tag,1));
616 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
617 if(strlen($str_tags))
619 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
625 $datarray['uid'] = $importer['uid'];
626 $datarray['contact-id'] = $contact['id'];
627 $datarray['wall'] = 0;
628 $datarray['guid'] = $guid;
629 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
630 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
631 $datarray['private'] = $private;
632 $datarray['parent'] = 0;
633 $datarray['owner-name'] = $contact['name'];
634 $datarray['owner-link'] = $contact['url'];
635 $datarray['owner-avatar'] = $contact['thumb'];
636 $datarray['author-name'] = $contact['name'];
637 $datarray['author-link'] = $contact['url'];
638 $datarray['author-avatar'] = $contact['thumb'];
639 $datarray['body'] = $body;
640 $datarray['tag'] = $str_tags;
641 $datarray['app'] = 'Diaspora';
643 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
645 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
647 $message_id = item_store($datarray);
650 q("update item set plink = '%s' where id = %d limit 1",
651 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
660 function diaspora_reshare($importer,$xml) {
662 logger('diaspora_reshare: init: ' . print_r($xml,true));
665 $guid = notags(unxmlify($xml->guid));
666 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
669 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
673 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
674 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
678 $message_id = $diaspora_handle . ':' . $guid;
679 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
680 intval($importer['uid']),
685 logger('diaspora_reshare: message exists: ' . $guid);
689 $orig_author = notags(unxmlify($xml->root_diaspora_id));
690 $orig_guid = notags(unxmlify($xml->root_guid));
692 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
693 $x = fetch_url($source_url);
695 $x = fetch_url(str_replace('https://','http://',$source_url));
697 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
700 logger('diaspora_reshare: source: ' . $x);
702 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
703 $source_xml = parse_xml_string($x,false);
705 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
706 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
707 $body = scale_diaspora_images($body,false);
709 elseif($source_xml->post->asphoto->image_url) {
710 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
711 $body = scale_diaspora_images($body);
713 elseif($source_xml->post->status_message) {
714 $body = diaspora2bb($source_xml->post->status_message->raw_message);
715 $body = scale_diaspora_images($body);
719 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
723 logger('diaspora_reshare: empty body: source= ' . $x);
727 $person = find_diaspora_person_by_handle($orig_author);
729 if(is_array($person) && x($person,'name') && x($person,'url'))
730 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
732 $details = $orig_author;
734 $prefix = '♲ ' . $details . "\n";
737 // allocate a guid on our system - we aren't fixing any collisions.
738 // we're ignoring them
740 $g = q("select * from guid where guid = '%s' limit 1",
744 q("insert into guid ( guid ) values ( '%s' )",
749 $created = unxmlify($xml->created_at);
750 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
756 $tags = get_tags($body);
759 foreach($tags as $tag) {
760 if(strpos($tag,'#') === 0) {
761 if(strpos($tag,'[url='))
763 $basetag = str_replace('_',' ',substr($tag,1));
764 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
765 if(strlen($str_tags))
767 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
773 $datarray['uid'] = $importer['uid'];
774 $datarray['contact-id'] = $contact['id'];
775 $datarray['wall'] = 0;
776 $datarray['guid'] = $guid;
777 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
778 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
779 $datarray['private'] = $private;
780 $datarray['parent'] = 0;
781 $datarray['owner-name'] = $contact['name'];
782 $datarray['owner-link'] = $contact['url'];
783 $datarray['owner-avatar'] = $contact['thumb'];
784 $datarray['author-name'] = $contact['name'];
785 $datarray['author-link'] = $contact['url'];
786 $datarray['author-avatar'] = $contact['thumb'];
787 $datarray['body'] = $prefix . $body;
788 $datarray['tag'] = $str_tags;
789 $datarray['app'] = 'Diaspora';
791 $message_id = item_store($datarray);
794 q("update item set plink = '%s' where id = %d limit 1",
795 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
805 function diaspora_asphoto($importer,$xml) {
806 logger('diaspora_asphoto called');
809 $guid = notags(unxmlify($xml->guid));
810 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
812 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
816 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
817 logger('diaspora_asphoto: Ignoring this author.');
821 $message_id = $diaspora_handle . ':' . $guid;
822 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
823 intval($importer['uid']),
828 logger('diaspora_asphoto: message exists: ' . $guid);
832 // allocate a guid on our system - we aren't fixing any collisions.
833 // we're ignoring them
835 $g = q("select * from guid where guid = '%s' limit 1",
839 q("insert into guid ( guid ) values ( '%s' )",
844 $created = unxmlify($xml->created_at);
845 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
847 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
848 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
849 $body = scale_diaspora_images($body,false);
851 elseif($xml->image_url) {
852 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
853 $body = scale_diaspora_images($body);
856 logger('diaspora_asphoto: no photo url found.');
863 $datarray['uid'] = $importer['uid'];
864 $datarray['contact-id'] = $contact['id'];
865 $datarray['wall'] = 0;
866 $datarray['guid'] = $guid;
867 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
868 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
869 $datarray['private'] = $private;
870 $datarray['parent'] = 0;
871 $datarray['owner-name'] = $contact['name'];
872 $datarray['owner-link'] = $contact['url'];
873 $datarray['owner-avatar'] = $contact['thumb'];
874 $datarray['author-name'] = $contact['name'];
875 $datarray['author-link'] = $contact['url'];
876 $datarray['author-avatar'] = $contact['thumb'];
877 $datarray['body'] = $body;
879 $datarray['app'] = 'Diaspora/Cubbi.es';
881 $message_id = item_store($datarray);
884 q("update item set plink = '%s' where id = %d limit 1",
885 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
899 function diaspora_comment($importer,$xml,$msg) {
902 $guid = notags(unxmlify($xml->guid));
903 $parent_guid = notags(unxmlify($xml->parent_guid));
904 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
905 $target_type = notags(unxmlify($xml->target_type));
906 $text = unxmlify($xml->text);
907 $author_signature = notags(unxmlify($xml->author_signature));
909 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
911 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
913 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
917 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
918 logger('diaspora_comment: Ignoring this author.');
922 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
923 intval($importer['uid']),
927 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
931 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
932 intval($importer['uid']),
936 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
939 $parent_item = $r[0];
941 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
943 $author_signature = base64_decode($author_signature);
945 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
950 $person = find_diaspora_person_by_handle($diaspora_handle);
952 if(is_array($person) && x($person,'pubkey'))
953 $key = $person['pubkey'];
955 logger('diaspora_comment: unable to find author details');
960 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
961 logger('diaspora_comment: verification failed.');
965 if($parent_author_signature) {
966 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
968 $parent_author_signature = base64_decode($parent_author_signature);
972 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
973 logger('diaspora_comment: owner verification failed.');
978 // Phew! Everything checks out. Now create an item.
980 $body = diaspora2bb($text);
982 $message_id = $diaspora_handle . ':' . $guid;
988 $tags = get_tags($body);
991 foreach($tags as $tag) {
992 if(strpos($tag,'#') === 0) {
993 if(strpos($tag,'[url='))
995 $basetag = str_replace('_',' ',substr($tag,1));
996 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
997 if(strlen($str_tags))
999 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1005 $datarray['uid'] = $importer['uid'];
1006 $datarray['contact-id'] = $contact['id'];
1007 $datarray['wall'] = $parent_item['wall'];
1008 $datarray['gravity'] = GRAVITY_COMMENT;
1009 $datarray['guid'] = $guid;
1010 $datarray['uri'] = $message_id;
1011 $datarray['parent-uri'] = $parent_item['uri'];
1013 // No timestamps for comments? OK, we'll the use current time.
1014 $datarray['created'] = $datarray['edited'] = datetime_convert();
1015 $datarray['private'] = $parent_item['private'];
1017 $datarray['owner-name'] = $parent_item['owner-name'];
1018 $datarray['owner-link'] = $parent_item['owner-link'];
1019 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1021 $datarray['author-name'] = $person['name'];
1022 $datarray['author-link'] = $person['url'];
1023 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1024 $datarray['body'] = $body;
1025 $datarray['tag'] = $str_tags;
1027 // We can't be certain what the original app is if the message is relayed.
1028 if(($parent_item['origin']) && (! $parent_author_signature))
1029 $datarray['app'] = 'Diaspora';
1031 $message_id = item_store($datarray);
1034 q("update item set plink = '%s' where id = %d limit 1",
1035 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1040 if(($parent_item['origin']) && (! $parent_author_signature)) {
1041 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1042 intval($message_id),
1043 dbesc($author_signed_data),
1044 dbesc(base64_encode($author_signature)),
1045 dbesc($diaspora_handle)
1048 // if the message isn't already being relayed, notify others
1049 // the existence of parent_author_signature means the parent_author or owner
1050 // is already relaying.
1052 proc_run('php','include/notifier.php','comment',$message_id);
1060 function diaspora_conversation($importer,$xml,$msg) {
1064 $guid = notags(unxmlify($xml->guid));
1065 $subject = notags(unxmlify($xml->subject));
1066 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1067 $participant_handles = notags(unxmlify($xml->participant_handles));
1068 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1070 $parent_uri = $diaspora_handle . ':' . $guid;
1072 $messages = $xml->message;
1074 if(! count($messages)) {
1075 logger('diaspora_conversation: empty conversation');
1079 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1081 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1085 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1086 logger('diaspora_conversation: Ignoring this author.');
1090 $conversation = null;
1092 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1093 intval($importer['uid']),
1097 $conversation = $c[0];
1099 $r = q("insert into conv (uid,guid,recips) values(%d, '%s', '%s') ",
1100 intval($importer['uid']),
1102 dbesc($participant_handles)
1105 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1106 intval($importer['uid']),
1110 $conversation = $c[0];
1112 if(! $conversation) {
1113 logger('diaspora_conversation: unable to create conversation.');
1118 foreach($messages as $mesg) {
1122 $msg_guid = notags(unxmlify($mesg->guid));
1123 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1124 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1125 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1126 $msg_text = unxmlify($mesg->text);
1127 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1128 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1129 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1130 if($msg_conversation_guid != $guid) {
1131 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1137 if($msg_parent_guid != $guid)
1140 $body = diaspora2bb($msg_text);
1141 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1143 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1144 // $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . $msg_diaspora_handle;
1146 $author_signature = base64_decode($msg_author_signature);
1148 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1153 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1155 if(is_array($person) && x($person,'pubkey'))
1156 $key = $person['pubkey'];
1158 logger('diaspora_conversation: unable to find author details');
1163 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1164 logger('diaspora_conversation: verification failed.');
1168 if($msg_parent_author_signature) {
1169 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1171 $parent_author_signature = base64_decode($msg_parent_author_signature);
1175 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1176 logger('diaspora_conversation: owner verification failed.');
1181 $r = q("select id from mail where `uri` = '%s' limit 1",
1185 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1189 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`replied`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1190 intval($importer['uid']),
1192 intval($conversation['id']),
1193 dbesc($person['name']),
1194 dbesc($person['photo']),
1195 dbesc($person['url']),
1196 intval($contact['id']),
1203 dbesc($msg_created_at)
1216 function diaspora_photo($importer,$xml,$msg) {
1219 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1221 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1223 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1225 $guid = notags(unxmlify($xml->guid));
1227 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1229 $public = notags(unxmlify($xml->public));
1231 $created_at = notags(unxmlify($xml_created_at));
1234 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1238 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1239 logger('diaspora_photo: Ignoring this author.');
1243 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1244 intval($importer['uid']),
1245 dbesc($status_message_guid)
1248 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1251 $parent_item = $r[0];
1253 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1255 $link_text = scale_diaspora_images($link_text);
1257 if(strpos($parent_item['body'],$link_text) === false) {
1258 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1259 dbesc($link_text . $parent_item['body']),
1260 intval($parent_item['id']),
1261 intval($parent_item['uid'])
1271 function diaspora_like($importer,$xml,$msg) {
1274 $guid = notags(unxmlify($xml->guid));
1275 $parent_guid = notags(unxmlify($xml->parent_guid));
1276 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1277 $target_type = notags(unxmlify($xml->target_type));
1278 $positive = notags(unxmlify($xml->positive));
1279 $author_signature = notags(unxmlify($xml->author_signature));
1281 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1283 // likes on comments not supported here and likes on photos not supported by Diaspora
1285 if($target_type !== 'Post')
1288 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1290 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1294 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1295 logger('diaspora_like: Ignoring this author.');
1299 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1300 intval($importer['uid']),
1304 logger('diaspora_like: parent item not found: ' . $guid);
1308 $parent_item = $r[0];
1310 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1311 intval($importer['uid']),
1315 if($positive === 'true') {
1316 logger('diaspora_like: duplicate like: ' . $guid);
1319 if($positive === 'false') {
1320 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1321 intval($r[0]['id']),
1322 intval($importer['uid'])
1325 // send notification via proc_run()
1329 if($positive === 'false') {
1330 logger('diaspora_like: unlike received with no corresponding like');
1334 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1336 $author_signature = base64_decode($author_signature);
1338 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1343 $person = find_diaspora_person_by_handle($diaspora_handle);
1344 if(is_array($person) && x($person,'pubkey'))
1345 $key = $person['pubkey'];
1347 logger('diaspora_like: unable to find author details');
1352 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1353 logger('diaspora_like: verification failed.');
1357 if($parent_author_signature) {
1359 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1361 $parent_author_signature = base64_decode($parent_author_signature);
1365 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1366 logger('diaspora_like: owner verification failed.');
1371 // Phew! Everything checks out. Now create an item.
1373 $uri = $diaspora_handle . ':' . $guid;
1375 $activity = ACTIVITY_LIKE;
1376 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1377 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1378 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1379 $body = $parent_item['body'];
1384 <type>$objtype</type>
1386 <id>{$parent_item['uri']}</id>
1389 <content>$body</content>
1392 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1397 $arr['uid'] = $importer['uid'];
1398 $arr['guid'] = $guid;
1399 $arr['contact-id'] = $contact['id'];
1400 $arr['type'] = 'activity';
1401 $arr['wall'] = $parent_item['wall'];
1402 $arr['gravity'] = GRAVITY_LIKE;
1403 $arr['parent'] = $parent_item['id'];
1404 $arr['parent-uri'] = $parent_item['uri'];
1406 $arr['owner-name'] = $parent_item['name'];
1407 $arr['owner-link'] = $parent_item['url'];
1408 $arr['owner-avatar'] = $parent_item['thumb'];
1410 $arr['author-name'] = $person['name'];
1411 $arr['author-link'] = $person['url'];
1412 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1414 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1415 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1416 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1417 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1419 $arr['app'] = 'Diaspora';
1421 $arr['private'] = $parent_item['private'];
1422 $arr['verb'] = $activity;
1423 $arr['object-type'] = $objtype;
1424 $arr['object'] = $obj;
1425 $arr['visible'] = 1;
1427 $arr['last-child'] = 0;
1429 $message_id = item_store($arr);
1433 q("update item set plink = '%s' where id = %d limit 1",
1434 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1439 if(! $parent_author_signature) {
1440 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1441 intval($message_id),
1442 dbesc($author_signed_data),
1443 dbesc(base64_encode($author_signature)),
1444 dbesc($diaspora_handle)
1448 // if the message isn't already being relayed, notify others
1449 // the existence of parent_author_signature means the parent_author or owner
1450 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1452 if(($parent_item['origin']) && (! $parent_author_signature))
1453 proc_run('php','include/notifier.php','comment',$message_id);
1458 function diaspora_retraction($importer,$xml) {
1460 $guid = notags(unxmlify($xml->guid));
1461 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1462 $type = notags(unxmlify($xml->type));
1464 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1468 if($type === 'Person') {
1469 require_once('include/Contact.php');
1470 contact_remove($contact['id']);
1472 elseif($type === 'Post') {
1473 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1475 intval($importer['uid'])
1478 if(link_compare($r[0]['author-link'],$contact['url'])) {
1479 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1480 dbesc(datetime_convert()),
1491 function diaspora_signed_retraction($importer,$xml) {
1493 $guid = notags(unxmlify($xml->target_guid));
1494 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1495 $type = notags(unxmlify($xml->target_type));
1496 $sig = notags(unxmlify($xml->target_author_signature));
1498 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1502 // this may not yet work for comments. Need to see how the relaying works
1503 // and figure out who signs it.
1506 $signed_data = $guid . ';' . $type ;
1508 $sig = base64_decode($sig);
1512 if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1513 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1517 if($type === 'StatusMessage') {
1518 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1520 intval($importer['uid'])
1523 if(link_compare($r[0]['author-link'],$contact['url'])) {
1524 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1525 dbesc(datetime_convert()),
1536 function diaspora_profile($importer,$xml) {
1539 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1541 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1545 if($contact['blocked']) {
1546 logger('diaspora_post: Ignoring this author.');
1550 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1551 $image_url = unxmlify($xml->image_url);
1552 $birthday = unxmlify($xml->birthday);
1554 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1555 intval($importer['uid']),
1556 intval($contact['id'])
1558 $oldphotos = ((count($r)) ? $r : null);
1560 require_once('include/Photo.php');
1562 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1564 // Generic birthday. We don't know the timezone. The year is irrelevant.
1566 $birthday = str_replace('1000','1901',$birthday);
1568 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1570 $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",
1572 dbesc(datetime_convert()),
1576 dbesc(datetime_convert()),
1578 intval($contact['id']),
1579 intval($importer['uid'])
1584 foreach($oldphotos as $ph) {
1585 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1586 intval($importer['uid']),
1587 intval($contact['id']),
1588 dbesc($ph['resource-id'])
1619 function diaspora_share($me,$contact) {
1621 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1622 $theiraddr = $contact['addr'];
1624 $tpl = get_markup_template('diaspora_share.tpl');
1625 $msg = replace_macros($tpl, array(
1626 '$sender' => $myaddr,
1627 '$recipient' => $theiraddr
1630 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1632 return(diaspora_transmit($owner,$contact,$slap, false));
1635 function diaspora_unshare($me,$contact) {
1638 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1640 $tpl = get_markup_template('diaspora_retract.tpl');
1641 $msg = replace_macros($tpl, array(
1642 '$guid' => $me['guid'],
1643 '$type' => 'Person',
1644 '$handle' => $myaddr
1647 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1649 return(diaspora_transmit($owner,$contact,$slap, false));
1655 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1658 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1659 $theiraddr = $contact['addr'];
1663 $body = $item['body'];
1666 // We're trying to match Diaspora's split message/photo protocol but
1667 // all the photos are displayed on D* as links and not img's - even
1668 // though we're sending pretty much precisely what they send us when
1669 // doing the same operation.
1670 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1671 // which seems to get through intact.
1673 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1675 foreach($matches as $mtch) {
1677 $detail['str'] = $mtch[0];
1678 $detail['path'] = dirname($mtch[1]) . '/';
1679 $detail['file'] = basename($mtch[1]);
1680 $detail['guid'] = $item['guid'];
1681 $detail['handle'] = $myaddr;
1682 $images[] = $detail;
1683 $body = str_replace($detail['str'],$mtch[1],$body);
1688 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1690 if($item['attach']) {
1691 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1693 $body .= "\n" . t('Attachments:') . "\n";
1694 foreach($matches as $mtch) {
1695 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1701 $public = (($item['private']) ? 'false' : 'true');
1703 require_once('include/datetime.php');
1704 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1706 $tpl = get_markup_template('diaspora_post.tpl');
1707 $msg = replace_macros($tpl, array(
1709 '$guid' => $item['guid'],
1710 '$handle' => xmlify($myaddr),
1711 '$public' => $public,
1712 '$created' => $created
1715 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1717 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1719 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1721 if(count($images)) {
1722 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1725 return $return_code;
1729 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1731 if(! count($images))
1733 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1735 $tpl = get_markup_template('diaspora_photo.tpl');
1736 foreach($images as $image) {
1737 if(! stristr($image['path'],$mysite))
1739 $resource = str_replace('.jpg','',$image['file']);
1740 $resource = substr($resource,0,strpos($resource,'-'));
1742 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1744 intval($owner['uid'])
1748 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1749 $msg = replace_macros($tpl,array(
1750 '$path' => xmlify($image['path']),
1751 '$filename' => xmlify($image['file']),
1752 '$msg_guid' => xmlify($image['guid']),
1753 '$guid' => xmlify($r[0]['guid']),
1754 '$handle' => xmlify($image['handle']),
1755 '$public' => xmlify($public),
1756 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1760 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1761 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1763 diaspora_transmit($owner,$contact,$slap,$public_batch);
1768 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1771 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1772 $theiraddr = $contact['addr'];
1774 $p = q("select guid from item where parent = %d limit 1",
1778 $parent_guid = $p[0]['guid'];
1782 if($item['verb'] === ACTIVITY_LIKE) {
1783 $tpl = get_markup_template('diaspora_like.tpl');
1785 $target_type = 'Post';
1786 $positive = (($item['deleted']) ? 'false' : 'true');
1789 $tpl = get_markup_template('diaspora_comment.tpl');
1793 $text = html_entity_decode(bb2diaspora($item['body']));
1798 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1800 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1802 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1804 $msg = replace_macros($tpl,array(
1805 '$guid' => xmlify($item['guid']),
1806 '$parent_guid' => xmlify($parent_guid),
1807 '$target_type' =>xmlify($target_type),
1808 '$authorsig' => xmlify($authorsig),
1809 '$body' => xmlify($text),
1810 '$positive' => xmlify($positive),
1811 '$handle' => xmlify($myaddr)
1814 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1816 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1818 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1822 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1826 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1827 $theiraddr = $contact['addr'];
1830 $p = q("select guid from item where parent = %d limit 1",
1834 $parent_guid = $p[0]['guid'];
1838 if($item['verb'] === ACTIVITY_LIKE) {
1839 $tpl = get_markup_template('diaspora_like_relay.tpl');
1841 $target_type = 'Post';
1842 $positive = (($item['deleted']) ? 'false' : 'true');
1845 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1849 $body = $item['body'];
1851 $text = html_entity_decode(bb2diaspora($body));
1853 // fetch the original signature if somebody sent the post to us to relay
1854 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1855 // action. It wasn't needed. In that case create the original signature and the
1856 // owner (parent author) signature
1857 // comments from other networks will be relayed under our name, with a brief
1858 // preamble to describe what's happening and noting the real author
1860 $r = q("select * from sign where iid = %d limit 1",
1865 $signed_text = $orig_sign['signed_text'];
1866 $authorsig = $orig_sign['signature'];
1867 $handle = $orig_sign['signer'];
1871 $itemcontact = q("select * from contact where `id` = %d limit 1",
1872 intval($item['contact-id'])
1874 if(count($itemcontact)) {
1875 if(! $itemcontact[0]['self']) {
1876 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1877 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1878 network_to_name($itemcontact['network'])) . "\n";
1879 $body = $prefix . $body;
1885 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1887 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1889 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1891 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1892 intval($item['id']),
1893 dbesc($signed_text),
1894 dbesc(base64_encode($authorsig)),
1903 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1905 $msg = replace_macros($tpl,array(
1906 '$guid' => xmlify($item['guid']),
1907 '$parent_guid' => xmlify($parent_guid),
1908 '$target_type' =>xmlify($target_type),
1909 '$authorsig' => xmlify($orig_sign['signature']),
1910 '$parentsig' => xmlify($parentauthorsig),
1911 '$body' => xmlify($text),
1912 '$positive' => xmlify($positive),
1913 '$handle' => xmlify($handle)
1916 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1918 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1920 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1926 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1929 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1931 $signed_text = $item['guid'] . ';' . 'StatusMessage';
1933 $tpl = get_markup_template('diaspora_signed_retract.tpl');
1934 $msg = replace_macros($tpl, array(
1935 '$guid' => $item['guid'],
1936 '$type' => 'StatusMessage',
1937 '$handle' => $myaddr,
1938 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1941 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1943 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1948 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1951 $logid = random_string(4);
1952 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
1954 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
1958 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
1960 post_url($dest_url . '/', $slap);
1962 $return_code = $a->get_curl_code();
1963 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1965 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1966 logger('diaspora_transmit: queue message');
1968 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
1969 intval($contact['id']),
1970 dbesc(NETWORK_DIASPORA),
1972 intval($public_batch)
1975 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
1978 // queue message for redelivery
1979 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
1984 return(($return_code) ? $return_code : (-1));