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 if($xmlbase->request) {
45 $ret = diaspora_request($importer,$xmlbase->request);
47 elseif($xmlbase->status_message) {
48 $ret = diaspora_post($importer,$xmlbase->status_message);
50 elseif($xmlbase->profile) {
51 $ret = diaspora_profile($importer,$xmlbase->profile);
53 elseif($xmlbase->comment) {
54 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
56 elseif($xmlbase->like) {
57 $ret = diaspora_like($importer,$xmlbase->like,$msg);
59 elseif($xmlbase->asphoto) {
60 $ret = diaspora_asphoto($importer,$xmlbase->asphoto);
62 elseif($xmlbase->reshare) {
63 $ret = diaspora_reshare($importer,$xmlbase->reshare);
65 elseif($xmlbase->retraction) {
66 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
68 elseif($xmlbase->signed_retraction) {
69 $ret = diaspora_signed_retraction($importer,$xmlbase->retraction,$msg);
71 elseif($xmlbase->photo) {
72 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
74 elseif($xmlbase->conversation) {
75 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
78 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
83 function diaspora_get_contact_by_handle($uid,$handle) {
84 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
85 dbesc(NETWORK_DIASPORA),
94 function find_diaspora_person_by_handle($handle) {
96 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
97 dbesc(NETWORK_DIASPORA),
101 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
102 // update record occasionally so it doesn't get stale
103 $d = strtotime($r[0]['updated'] . ' +00:00');
104 if($d > strtotime('now - 14 days'))
108 logger('find_diaspora_person_by_handle: refresh',LOGGER_DEBUG);
109 require_once('include/Scrape.php');
110 $r = probe_url($handle, PROBE_DIASPORA);
111 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
112 add_fcontact($r,$update);
119 function get_diaspora_key($uri) {
120 logger('Fetching diaspora key for: ' . $uri);
122 $r = find_diaspora_person_by_handle($uri);
129 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
132 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
135 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
137 // $b64_data = base64_encode($msg);
138 // $b64url_data = base64url_encode($b64_data);
140 $b64url_data = base64url_encode($msg);
142 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
144 $type = 'application/xml';
145 $encoding = 'base64url';
148 $signable_data = $data . '.' . base64url_encode($type) . '.'
149 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
151 $signature = rsa_sign($signable_data,$prvkey);
152 $sig = base64url_encode($signature);
155 <?xml version='1.0' encoding='UTF-8'?>
156 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
158 <author_id>$handle</author_id>
161 <me:encoding>base64url</me:encoding>
162 <me:alg>RSA-SHA256</me:alg>
163 <me:data type="application/xml">$data</me:data>
164 <me:sig>$sig</me:sig>
169 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
177 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
181 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
183 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
185 $inner_aes_key = random_string(32);
186 $b_inner_aes_key = base64_encode($inner_aes_key);
187 $inner_iv = random_string(16);
188 $b_inner_iv = base64_encode($inner_iv);
190 $outer_aes_key = random_string(32);
191 $b_outer_aes_key = base64_encode($outer_aes_key);
192 $outer_iv = random_string(16);
193 $b_outer_iv = base64_encode($outer_iv);
195 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
197 $padded_data = pkcs5_pad($msg,16);
198 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
200 $b64_data = base64_encode($inner_encrypted);
203 $b64url_data = base64url_encode($b64_data);
204 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
206 $type = 'application/xml';
207 $encoding = 'base64url';
210 $signable_data = $data . '.' . base64url_encode($type) . '.'
211 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
213 $signature = rsa_sign($signable_data,$prvkey);
214 $sig = base64url_encode($signature);
216 $decrypted_header = <<< EOT
219 <aes_key>$b_inner_aes_key</aes_key>
220 <author_id>$handle</author_id>
224 $decrypted_header = pkcs5_pad($decrypted_header,16);
226 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
228 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
230 $encrypted_outer_key_bundle = '';
231 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
233 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
235 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
237 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
238 'ciphertext' => base64_encode($ciphertext)));
239 $cipher_json = base64_encode($encrypted_header_json_object);
241 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
244 <?xml version='1.0' encoding='UTF-8'?>
245 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
248 <me:encoding>base64url</me:encoding>
249 <me:alg>RSA-SHA256</me:alg>
250 <me:data type="application/xml">$data</me:data>
251 <me:sig>$sig</me:sig>
256 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
263 * diaspora_decode($importer,$xml)
264 * array $importer -> from user table
265 * string $xml -> urldecoded Diaspora salmon
268 * 'message' -> decoded Diaspora XML message
269 * 'author' -> author diaspora handle
270 * 'key' -> author public key (converted to pkcs#8)
272 * Author and key are used elsewhere to save a lookup for verifying replies and likes
276 function diaspora_decode($importer,$xml) {
279 $basedom = parse_xml_string($xml);
281 $children = $basedom->children('https://joindiaspora.com/protocol');
283 if($children->header) {
285 $author_link = str_replace('acct:','',$children->header->author_id);
289 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
291 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
292 $ciphertext = base64_decode($encrypted_header->ciphertext);
294 $outer_key_bundle = '';
295 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
297 $j_outer_key_bundle = json_decode($outer_key_bundle);
299 $outer_iv = base64_decode($j_outer_key_bundle->iv);
300 $outer_key = base64_decode($j_outer_key_bundle->key);
302 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
305 $decrypted = pkcs5_unpad($decrypted);
308 * $decrypted now contains something like
311 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
312 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
317 * <name>Ryan Hughes</name>
318 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
323 * <author_id>galaxor@diaspora.priateship.org</author_id>
327 * </decrypted_header>
330 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
331 $idom = parse_xml_string($decrypted,false);
333 $inner_iv = base64_decode($idom->iv);
334 $inner_aes_key = base64_decode($idom->aes_key);
336 $author_link = str_replace('acct:','',$idom->author_id);
340 $dom = $basedom->children(NAMESPACE_SALMON_ME);
342 // figure out where in the DOM tree our data is hiding
344 if($dom->provenance->data)
345 $base = $dom->provenance;
346 elseif($dom->env->data)
352 logger('mod-diaspora: unable to locate salmon data in xml ');
353 http_status_exit(400);
357 // Stash the signature away for now. We have to find their key or it won't be good for anything.
358 $signature = base64url_decode($base->sig);
362 // strip whitespace so our data element will return to one big base64 blob
363 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
366 // stash away some other stuff for later
368 $type = $base->data[0]->attributes()->type[0];
369 $keyhash = $base->sig[0]->attributes()->keyhash[0];
370 $encoding = $base->encoding;
374 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
378 $data = base64url_decode($data);
382 $inner_decrypted = $data;
386 // Decode the encrypted blob
388 $inner_encrypted = base64_decode($data);
389 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
390 $inner_decrypted = pkcs5_unpad($inner_decrypted);
394 logger('mod-diaspora: Could not retrieve author URI.');
395 http_status_exit(400);
398 // Once we have the author URI, go to the web and try to find their public key
399 // (first this will look it up locally if it is in the fcontact cache)
400 // This will also convert diaspora public key from pkcs#1 to pkcs#8
402 logger('mod-diaspora: Fetching key for ' . $author_link );
403 $key = get_diaspora_key($author_link);
406 logger('mod-diaspora: Could not retrieve author key.');
407 http_status_exit(400);
410 $verify = rsa_verify($signed_data,$signature,$key);
413 logger('mod-diaspora: Message did not verify. Discarding.');
414 http_status_exit(400);
417 logger('mod-diaspora: Message verified.');
419 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
424 function diaspora_request($importer,$xml) {
428 $sender_handle = unxmlify($xml->sender_handle);
429 $recipient_handle = unxmlify($xml->recipient_handle);
431 if(! $sender_handle || ! $recipient_handle)
434 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
438 // perhaps we were already sharing with this person. Now they're sharing with us.
439 // That makes us friends.
441 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
442 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
443 intval(CONTACT_IS_FRIEND),
444 intval($contact['id']),
445 intval($importer['uid'])
450 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
451 intval($importer['uid'])
454 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
455 require_once('include/items.php');
457 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
458 intval($importer['uid'])
461 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
463 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
466 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
467 $arr['uid'] = $importer['uid'];
468 $arr['contact-id'] = $self[0]['id'];
470 $arr['type'] = 'wall';
473 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
474 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
475 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
476 $arr['verb'] = ACTIVITY_FRIEND;
477 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
479 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
480 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
481 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
482 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
484 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
485 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
486 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
487 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
488 $arr['object'] .= '</link></object>' . "\n";
489 $arr['last-child'] = 1;
491 $arr['allow_cid'] = $user[0]['allow_cid'];
492 $arr['allow_gid'] = $user[0]['allow_gid'];
493 $arr['deny_cid'] = $user[0]['deny_cid'];
494 $arr['deny_gid'] = $user[0]['deny_gid'];
496 $i = item_store($arr);
498 proc_run('php',"include/notifier.php","activity","$i");
507 $ret = find_diaspora_person_by_handle($sender_handle);
510 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
511 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
515 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
517 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
518 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
519 intval($importer['uid']),
520 dbesc($ret['network']),
524 dbesc(normalise_link($ret['url'])),
528 dbesc($ret['photo']),
529 dbesc($ret['pubkey']),
530 dbesc($ret['notify']),
536 // find the contact record we just created
538 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
540 $hash = random_string() . (string) time(); // Generate a confirm_key
542 if($contact_record) {
543 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
544 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
545 intval($importer['uid']),
546 intval($contact_record['id']),
549 dbesc( t('Sharing notification from Diaspora network')),
551 dbesc(datetime_convert())
558 function diaspora_post($importer,$xml) {
561 $guid = notags(unxmlify($xml->guid));
562 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
564 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
568 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
569 logger('diaspora_post: Ignoring this author.');
573 $message_id = $diaspora_handle . ':' . $guid;
574 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
575 intval($importer['uid']),
580 logger('diaspora_post: message exists: ' . $guid);
584 // allocate a guid on our system - we aren't fixing any collisions.
585 // we're ignoring them
587 $g = q("select * from guid where guid = '%s' limit 1",
591 q("insert into guid ( guid ) values ( '%s' )",
596 $created = unxmlify($xml->created_at);
597 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
599 $body = diaspora2bb($xml->raw_message);
605 $tags = get_tags($body);
608 foreach($tags as $tag) {
609 if(strpos($tag,'#') === 0) {
610 if(strpos($tag,'[url='))
612 $basetag = str_replace('_',' ',substr($tag,1));
613 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
614 if(strlen($str_tags))
616 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
622 $datarray['uid'] = $importer['uid'];
623 $datarray['contact-id'] = $contact['id'];
624 $datarray['wall'] = 0;
625 $datarray['guid'] = $guid;
626 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
627 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
628 $datarray['private'] = $private;
629 $datarray['parent'] = 0;
630 $datarray['owner-name'] = $contact['name'];
631 $datarray['owner-link'] = $contact['url'];
632 $datarray['owner-avatar'] = $contact['thumb'];
633 $datarray['author-name'] = $contact['name'];
634 $datarray['author-link'] = $contact['url'];
635 $datarray['author-avatar'] = $contact['thumb'];
636 $datarray['body'] = $body;
637 $datarray['tag'] = $str_tags;
638 $datarray['app'] = 'Diaspora';
640 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
642 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
644 $message_id = item_store($datarray);
647 q("update item set plink = '%s' where id = %d limit 1",
648 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
657 function diaspora_reshare($importer,$xml) {
659 logger('diaspora_reshare: init: ' . print_r($xml,true));
662 $guid = notags(unxmlify($xml->guid));
663 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
666 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
670 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
671 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
675 $message_id = $diaspora_handle . ':' . $guid;
676 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
677 intval($importer['uid']),
682 logger('diaspora_reshare: message exists: ' . $guid);
686 $orig_author = notags(unxmlify($xml->root_diaspora_id));
687 $orig_guid = notags(unxmlify($xml->root_guid));
689 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
690 $x = fetch_url($source_url);
692 $x = fetch_url(str_replace('https://','http://',$source_url));
694 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
697 logger('diaspora_reshare: source: ' . $x);
699 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
700 $source_xml = parse_xml_string($x,false);
702 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
703 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
704 $body = scale_diaspora_images($body,false);
706 elseif($source_xml->post->asphoto->image_url) {
707 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
708 $body = scale_diaspora_images($body);
710 elseif($source_xml->post->status_message) {
711 $body = diaspora2bb($source_xml->post->status_message->raw_message);
712 $body = scale_diaspora_images($body);
716 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
720 logger('diaspora_reshare: empty body: source= ' . $x);
724 $person = find_diaspora_person_by_handle($orig_author);
726 if(is_array($person) && x($person,'name') && x($person,'url'))
727 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
729 $details = $orig_author;
731 $prefix = '♲ ' . $details . "\n";
734 // allocate a guid on our system - we aren't fixing any collisions.
735 // we're ignoring them
737 $g = q("select * from guid where guid = '%s' limit 1",
741 q("insert into guid ( guid ) values ( '%s' )",
746 $created = unxmlify($xml->created_at);
747 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
753 $tags = get_tags($body);
756 foreach($tags as $tag) {
757 if(strpos($tag,'#') === 0) {
758 if(strpos($tag,'[url='))
760 $basetag = str_replace('_',' ',substr($tag,1));
761 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
762 if(strlen($str_tags))
764 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
770 $datarray['uid'] = $importer['uid'];
771 $datarray['contact-id'] = $contact['id'];
772 $datarray['wall'] = 0;
773 $datarray['guid'] = $guid;
774 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
775 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
776 $datarray['private'] = $private;
777 $datarray['parent'] = 0;
778 $datarray['owner-name'] = $contact['name'];
779 $datarray['owner-link'] = $contact['url'];
780 $datarray['owner-avatar'] = $contact['thumb'];
781 $datarray['author-name'] = $contact['name'];
782 $datarray['author-link'] = $contact['url'];
783 $datarray['author-avatar'] = $contact['thumb'];
784 $datarray['body'] = $prefix . $body;
785 $datarray['tag'] = $str_tags;
786 $datarray['app'] = 'Diaspora';
788 $message_id = item_store($datarray);
791 q("update item set plink = '%s' where id = %d limit 1",
792 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
802 function diaspora_asphoto($importer,$xml) {
803 logger('diaspora_asphoto called');
806 $guid = notags(unxmlify($xml->guid));
807 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
809 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
813 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
814 logger('diaspora_asphoto: Ignoring this author.');
818 $message_id = $diaspora_handle . ':' . $guid;
819 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
820 intval($importer['uid']),
825 logger('diaspora_asphoto: message exists: ' . $guid);
829 // allocate a guid on our system - we aren't fixing any collisions.
830 // we're ignoring them
832 $g = q("select * from guid where guid = '%s' limit 1",
836 q("insert into guid ( guid ) values ( '%s' )",
841 $created = unxmlify($xml->created_at);
842 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
844 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
845 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
846 $body = scale_diaspora_images($body,false);
848 elseif($xml->image_url) {
849 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
850 $body = scale_diaspora_images($body);
853 logger('diaspora_asphoto: no photo url found.');
860 $datarray['uid'] = $importer['uid'];
861 $datarray['contact-id'] = $contact['id'];
862 $datarray['wall'] = 0;
863 $datarray['guid'] = $guid;
864 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
865 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
866 $datarray['private'] = $private;
867 $datarray['parent'] = 0;
868 $datarray['owner-name'] = $contact['name'];
869 $datarray['owner-link'] = $contact['url'];
870 $datarray['owner-avatar'] = $contact['thumb'];
871 $datarray['author-name'] = $contact['name'];
872 $datarray['author-link'] = $contact['url'];
873 $datarray['author-avatar'] = $contact['thumb'];
874 $datarray['body'] = $body;
876 $datarray['app'] = 'Diaspora/Cubbi.es';
878 $message_id = item_store($datarray);
881 q("update item set plink = '%s' where id = %d limit 1",
882 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
896 function diaspora_comment($importer,$xml,$msg) {
899 $guid = notags(unxmlify($xml->guid));
900 $parent_guid = notags(unxmlify($xml->parent_guid));
901 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
902 $target_type = notags(unxmlify($xml->target_type));
903 $text = unxmlify($xml->text);
904 $author_signature = notags(unxmlify($xml->author_signature));
906 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
908 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
910 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
914 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
915 logger('diaspora_comment: Ignoring this author.');
919 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
920 intval($importer['uid']),
924 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
928 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
929 intval($importer['uid']),
933 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
936 $parent_item = $r[0];
938 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
940 $author_signature = base64_decode($author_signature);
942 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
947 $person = find_diaspora_person_by_handle($diaspora_handle);
949 if(is_array($person) && x($person,'pubkey'))
950 $key = $person['pubkey'];
952 logger('diaspora_comment: unable to find author details');
957 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
958 logger('diaspora_comment: verification failed.');
962 if($parent_author_signature) {
963 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
965 $parent_author_signature = base64_decode($parent_author_signature);
969 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
970 logger('diaspora_comment: owner verification failed.');
975 // Phew! Everything checks out. Now create an item.
977 $body = diaspora2bb($text);
979 $message_id = $diaspora_handle . ':' . $guid;
985 $tags = get_tags($body);
988 foreach($tags as $tag) {
989 if(strpos($tag,'#') === 0) {
990 if(strpos($tag,'[url='))
992 $basetag = str_replace('_',' ',substr($tag,1));
993 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
994 if(strlen($str_tags))
996 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1002 $datarray['uid'] = $importer['uid'];
1003 $datarray['contact-id'] = $contact['id'];
1004 $datarray['wall'] = $parent_item['wall'];
1005 $datarray['gravity'] = GRAVITY_COMMENT;
1006 $datarray['guid'] = $guid;
1007 $datarray['uri'] = $message_id;
1008 $datarray['parent-uri'] = $parent_item['uri'];
1010 // No timestamps for comments? OK, we'll the use current time.
1011 $datarray['created'] = $datarray['edited'] = datetime_convert();
1012 $datarray['private'] = $parent_item['private'];
1014 $datarray['owner-name'] = $parent_item['owner-name'];
1015 $datarray['owner-link'] = $parent_item['owner-link'];
1016 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1018 $datarray['author-name'] = $person['name'];
1019 $datarray['author-link'] = $person['url'];
1020 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1021 $datarray['body'] = $body;
1022 $datarray['tag'] = $str_tags;
1024 // We can't be certain what the original app is if the message is relayed.
1025 if(($parent_item['origin']) && (! $parent_author_signature))
1026 $datarray['app'] = 'Diaspora';
1028 $message_id = item_store($datarray);
1031 q("update item set plink = '%s' where id = %d limit 1",
1032 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1037 if(($parent_item['origin']) && (! $parent_author_signature)) {
1038 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1039 intval($message_id),
1040 dbesc($author_signed_data),
1041 dbesc(base64_encode($author_signature)),
1042 dbesc($diaspora_handle)
1045 // if the message isn't already being relayed, notify others
1046 // the existence of parent_author_signature means the parent_author or owner
1047 // is already relaying.
1049 proc_run('php','include/notifier.php','comment',$message_id);
1057 function diaspora_conversation($importer,$xml,$msg) {
1061 $guid = notags(unxmlify($xml->guid));
1062 $subject = notags(unxmlify($xml->subject));
1063 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1064 $participant_handles = notags(unxmlify($xml->participant_handles));
1065 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1067 $parent_uri = $diaspora_handle . ':' . $guid;
1069 $messages = $xml->message;
1071 if(! count($messages)) {
1072 logger('diaspora_conversation: empty conversation');
1076 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1078 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1082 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1083 logger('diaspora_conversation: Ignoring this author.');
1087 $conversation = null;
1089 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1090 intval($importer['uid']),
1094 $conversation = $c[0];
1096 $r = q("insert into conv (uid,guid,recips) values('%d, '%s', '%s') ",
1097 intval($importer['uid']),
1099 dbesc($participant_handles)
1102 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1103 intval($importer['uid']),
1107 $conversation = $c[0];
1109 if(! $conversation) {
1110 logger('diaspora_conversation: unable to create conversation.');
1115 foreach($messages as $msg) {
1119 $msg_guid = notags(unxmlify($msg->guid));
1120 $msg_parent_guid = notags(unxmlify($msg->parent_guid));
1121 $msg_parent_author_signature = notags(unxmlify($msg->parent_author_signature));
1122 $msg_author_signature = notags(unxmlify($msg->author_signature));
1123 $msg_text = unxmlify($msg->text);
1124 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($msg->created_at)));
1125 $msg_diaspora_handle = notags(unxmlify($msg->diaspora_handle));
1126 $msg_conversation_guid = notags(unxmlify($msg->conversation_guid));
1127 if($msg_conversation_guid != $guid) {
1128 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1134 if($msg_parent_guid != $guid)
1137 $body = diaspora2bb($msg_text);
1138 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1140 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1141 if(is_array($person) && x($person,'pubkey'))
1142 $key = $person['pubkey'];
1144 logger('diaspora_conversation: unable to find author details');
1148 $r = q("select id from mail where `uri` = '%s' limit 1",
1152 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1156 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')",
1157 intval($importer['uid']),
1159 intval($conversation['id']),
1160 dbesc($person['name']),
1161 dbesc($person['photo']),
1162 dbesc($person['url']),
1163 intval($contact['id']),
1170 dbesc($msg_created_at)
1177 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1179 $author_signature = base64_decode($author_signature);
1181 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1186 $person = find_diaspora_person_by_handle($diaspora_handle);
1188 if(is_array($person) && x($person,'pubkey'))
1189 $key = $person['pubkey'];
1191 logger('diaspora_comment: unable to find author details');
1196 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1197 logger('diaspora_comment: verification failed.');
1201 if($parent_author_signature) {
1202 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1204 $parent_author_signature = base64_decode($parent_author_signature);
1208 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1209 logger('diaspora_comment: owner verification failed.');
1214 // Phew! Everything checks out. Now create an item.
1216 $body = diaspora2bb($text);
1218 $message_id = $diaspora_handle . ':' . $guid;
1220 $datarray = array();
1224 $tags = get_tags($body);
1227 foreach($tags as $tag) {
1228 if(strpos($tag,'#') === 0) {
1229 if(strpos($tag,'[url='))
1231 $basetag = str_replace('_',' ',substr($tag,1));
1232 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1233 if(strlen($str_tags))
1235 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1251 function diaspora_photo($importer,$xml,$msg) {
1254 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1256 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1258 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1260 $guid = notags(unxmlify($xml->guid));
1262 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1264 $public = notags(unxmlify($xml->public));
1266 $created_at = notags(unxmlify($xml_created_at));
1269 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1273 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1274 logger('diaspora_photo: Ignoring this author.');
1278 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1279 intval($importer['uid']),
1280 dbesc($status_message_guid)
1283 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1286 $parent_item = $r[0];
1288 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1290 $link_text = scale_diaspora_images($link_text);
1292 if(strpos($parent_item['body'],$link_text) === false) {
1293 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1294 dbesc($link_text . $parent_item['body']),
1295 intval($parent_item['id']),
1296 intval($parent_item['uid'])
1306 function diaspora_like($importer,$xml,$msg) {
1309 $guid = notags(unxmlify($xml->guid));
1310 $parent_guid = notags(unxmlify($xml->parent_guid));
1311 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1312 $target_type = notags(unxmlify($xml->target_type));
1313 $positive = notags(unxmlify($xml->positive));
1314 $author_signature = notags(unxmlify($xml->author_signature));
1316 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1318 // likes on comments not supported here and likes on photos not supported by Diaspora
1320 if($target_type !== 'Post')
1323 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1325 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1329 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1330 logger('diaspora_like: Ignoring this author.');
1334 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1335 intval($importer['uid']),
1339 logger('diaspora_like: parent item not found: ' . $guid);
1343 $parent_item = $r[0];
1345 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1346 intval($importer['uid']),
1350 if($positive === 'true') {
1351 logger('diaspora_like: duplicate like: ' . $guid);
1354 if($positive === 'false') {
1355 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1356 intval($r[0]['id']),
1357 intval($importer['uid'])
1360 // send notification via proc_run()
1364 if($positive === 'false') {
1365 logger('diaspora_like: unlike received with no corresponding like');
1369 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1371 $author_signature = base64_decode($author_signature);
1373 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1378 $person = find_diaspora_person_by_handle($diaspora_handle);
1379 if(is_array($person) && x($person,'pubkey'))
1380 $key = $person['pubkey'];
1382 logger('diaspora_like: unable to find author details');
1387 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1388 logger('diaspora_like: verification failed.');
1392 if($parent_author_signature) {
1394 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1396 $parent_author_signature = base64_decode($parent_author_signature);
1400 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1401 logger('diaspora_like: owner verification failed.');
1406 // Phew! Everything checks out. Now create an item.
1408 $uri = $diaspora_handle . ':' . $guid;
1410 $activity = ACTIVITY_LIKE;
1411 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1412 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1413 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1414 $body = $parent_item['body'];
1419 <type>$objtype</type>
1421 <id>{$parent_item['uri']}</id>
1424 <content>$body</content>
1427 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1432 $arr['uid'] = $importer['uid'];
1433 $arr['guid'] = $guid;
1434 $arr['contact-id'] = $contact['id'];
1435 $arr['type'] = 'activity';
1436 $arr['wall'] = $parent_item['wall'];
1437 $arr['gravity'] = GRAVITY_LIKE;
1438 $arr['parent'] = $parent_item['id'];
1439 $arr['parent-uri'] = $parent_item['uri'];
1441 $arr['owner-name'] = $parent_item['name'];
1442 $arr['owner-link'] = $parent_item['url'];
1443 $arr['owner-avatar'] = $parent_item['thumb'];
1445 $arr['author-name'] = $person['name'];
1446 $arr['author-link'] = $person['url'];
1447 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1449 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1450 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1451 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1452 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1454 $arr['app'] = 'Diaspora';
1456 $arr['private'] = $parent_item['private'];
1457 $arr['verb'] = $activity;
1458 $arr['object-type'] = $objtype;
1459 $arr['object'] = $obj;
1460 $arr['visible'] = 1;
1462 $arr['last-child'] = 0;
1464 $message_id = item_store($arr);
1468 q("update item set plink = '%s' where id = %d limit 1",
1469 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1474 if(! $parent_author_signature) {
1475 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1476 intval($message_id),
1477 dbesc($author_signed_data),
1478 dbesc(base64_encode($author_signature)),
1479 dbesc($diaspora_handle)
1483 // if the message isn't already being relayed, notify others
1484 // the existence of parent_author_signature means the parent_author or owner
1485 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1487 if(($parent_item['origin']) && (! $parent_author_signature))
1488 proc_run('php','include/notifier.php','comment',$message_id);
1493 function diaspora_retraction($importer,$xml) {
1495 $guid = notags(unxmlify($xml->guid));
1496 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1497 $type = notags(unxmlify($xml->type));
1499 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1503 if($type === 'Person') {
1504 require_once('include/Contact.php');
1505 contact_remove($contact['id']);
1507 elseif($type === 'Post') {
1508 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1510 intval($importer['uid'])
1513 if(link_compare($r[0]['author-link'],$contact['url'])) {
1514 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1515 dbesc(datetime_convert()),
1526 function diaspora_signed_retraction($importer,$xml) {
1528 $guid = notags(unxmlify($xml->target_guid));
1529 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1530 $type = notags(unxmlify($xml->target_type));
1531 $sig = notags(unxmlify($xml->target_author_signature));
1533 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1537 // this may not yet work for comments. Need to see how the relaying works
1538 // and figure out who signs it.
1541 $signed_data = $guid . ';' . $type ;
1543 $sig = base64_decode($sig);
1547 if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1548 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1552 if($type === 'StatusMessage') {
1553 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1555 intval($importer['uid'])
1558 if(link_compare($r[0]['author-link'],$contact['url'])) {
1559 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1560 dbesc(datetime_convert()),
1571 function diaspora_profile($importer,$xml) {
1574 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1576 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1580 if($contact['blocked']) {
1581 logger('diaspora_post: Ignoring this author.');
1585 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1586 $image_url = unxmlify($xml->image_url);
1587 $birthday = unxmlify($xml->birthday);
1589 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1590 intval($importer['uid']),
1591 intval($contact['id'])
1593 $oldphotos = ((count($r)) ? $r : null);
1595 require_once('include/Photo.php');
1597 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1599 // Generic birthday. We don't know the timezone. The year is irrelevant.
1601 $birthday = str_replace('1000','1901',$birthday);
1603 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1605 $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",
1607 dbesc(datetime_convert()),
1611 dbesc(datetime_convert()),
1613 intval($contact['id']),
1614 intval($importer['uid'])
1619 foreach($oldphotos as $ph) {
1620 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1621 intval($importer['uid']),
1622 intval($contact['id']),
1623 dbesc($ph['resource-id'])
1654 function diaspora_share($me,$contact) {
1656 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1657 $theiraddr = $contact['addr'];
1659 $tpl = get_markup_template('diaspora_share.tpl');
1660 $msg = replace_macros($tpl, array(
1661 '$sender' => $myaddr,
1662 '$recipient' => $theiraddr
1665 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1667 return(diaspora_transmit($owner,$contact,$slap, false));
1670 function diaspora_unshare($me,$contact) {
1673 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1675 $tpl = get_markup_template('diaspora_retract.tpl');
1676 $msg = replace_macros($tpl, array(
1677 '$guid' => $me['guid'],
1678 '$type' => 'Person',
1679 '$handle' => $myaddr
1682 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1684 return(diaspora_transmit($owner,$contact,$slap, false));
1690 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1693 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1694 $theiraddr = $contact['addr'];
1698 $body = $item['body'];
1701 // We're trying to match Diaspora's split message/photo protocol but
1702 // all the photos are displayed on D* as links and not img's - even
1703 // though we're sending pretty much precisely what they send us when
1704 // doing the same operation.
1705 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1706 // which seems to get through intact.
1708 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1710 foreach($matches as $mtch) {
1712 $detail['str'] = $mtch[0];
1713 $detail['path'] = dirname($mtch[1]) . '/';
1714 $detail['file'] = basename($mtch[1]);
1715 $detail['guid'] = $item['guid'];
1716 $detail['handle'] = $myaddr;
1717 $images[] = $detail;
1718 $body = str_replace($detail['str'],$mtch[1],$body);
1723 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1725 if($item['attach']) {
1726 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1728 $body .= "\n" . t('Attachments:') . "\n";
1729 foreach($matches as $mtch) {
1730 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1736 $public = (($item['private']) ? 'false' : 'true');
1738 require_once('include/datetime.php');
1739 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1741 $tpl = get_markup_template('diaspora_post.tpl');
1742 $msg = replace_macros($tpl, array(
1744 '$guid' => $item['guid'],
1745 '$handle' => xmlify($myaddr),
1746 '$public' => $public,
1747 '$created' => $created
1750 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1752 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1754 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1756 if(count($images)) {
1757 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1760 return $return_code;
1764 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1766 if(! count($images))
1768 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1770 $tpl = get_markup_template('diaspora_photo.tpl');
1771 foreach($images as $image) {
1772 if(! stristr($image['path'],$mysite))
1774 $resource = str_replace('.jpg','',$image['file']);
1775 $resource = substr($resource,0,strpos($resource,'-'));
1777 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1779 intval($owner['uid'])
1783 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1784 $msg = replace_macros($tpl,array(
1785 '$path' => xmlify($image['path']),
1786 '$filename' => xmlify($image['file']),
1787 '$msg_guid' => xmlify($image['guid']),
1788 '$guid' => xmlify($r[0]['guid']),
1789 '$handle' => xmlify($image['handle']),
1790 '$public' => xmlify($public),
1791 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1795 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1796 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1798 diaspora_transmit($owner,$contact,$slap,$public_batch);
1803 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1806 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1807 $theiraddr = $contact['addr'];
1809 $p = q("select guid from item where parent = %d limit 1",
1813 $parent_guid = $p[0]['guid'];
1817 if($item['verb'] === ACTIVITY_LIKE) {
1818 $tpl = get_markup_template('diaspora_like.tpl');
1820 $target_type = 'Post';
1821 $positive = (($item['deleted']) ? 'false' : 'true');
1824 $tpl = get_markup_template('diaspora_comment.tpl');
1828 $text = html_entity_decode(bb2diaspora($item['body']));
1833 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1835 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1837 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1839 $msg = replace_macros($tpl,array(
1840 '$guid' => xmlify($item['guid']),
1841 '$parent_guid' => xmlify($parent_guid),
1842 '$target_type' =>xmlify($target_type),
1843 '$authorsig' => xmlify($authorsig),
1844 '$body' => xmlify($text),
1845 '$positive' => xmlify($positive),
1846 '$handle' => xmlify($myaddr)
1849 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1851 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1853 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1857 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1861 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1862 $theiraddr = $contact['addr'];
1865 $p = q("select guid from item where parent = %d limit 1",
1869 $parent_guid = $p[0]['guid'];
1873 if($item['verb'] === ACTIVITY_LIKE) {
1874 $tpl = get_markup_template('diaspora_like_relay.tpl');
1876 $target_type = 'Post';
1877 $positive = (($item['deleted']) ? 'false' : 'true');
1880 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1884 $body = $item['body'];
1886 $text = html_entity_decode(bb2diaspora($body));
1888 // fetch the original signature if somebody sent the post to us to relay
1889 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1890 // action. It wasn't needed. In that case create the original signature and the
1891 // owner (parent author) signature
1892 // comments from other networks will be relayed under our name, with a brief
1893 // preamble to describe what's happening and noting the real author
1895 $r = q("select * from sign where iid = %d limit 1",
1900 $signed_text = $orig_sign['signed_text'];
1901 $authorsig = $orig_sign['signature'];
1902 $handle = $orig_sign['signer'];
1906 $itemcontact = q("select * from contact where `id` = %d limit 1",
1907 intval($item['contact-id'])
1909 if(count($itemcontact)) {
1910 if(! $itemcontact[0]['self']) {
1911 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1912 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1913 network_to_name($itemcontact['network'])) . "\n";
1914 $body = $prefix . $body;
1920 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1922 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1924 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1926 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1927 intval($item['id']),
1928 dbesc($signed_text),
1929 dbesc(base64_encode($authorsig)),
1938 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1940 $msg = replace_macros($tpl,array(
1941 '$guid' => xmlify($item['guid']),
1942 '$parent_guid' => xmlify($parent_guid),
1943 '$target_type' =>xmlify($target_type),
1944 '$authorsig' => xmlify($orig_sign['signature']),
1945 '$parentsig' => xmlify($parentauthorsig),
1946 '$body' => xmlify($text),
1947 '$positive' => xmlify($positive),
1948 '$handle' => xmlify($handle)
1951 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1953 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1955 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1961 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1964 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1966 $signed_text = $item['guid'] . ';' . 'StatusMessage';
1968 $tpl = get_markup_template('diaspora_signed_retract.tpl');
1969 $msg = replace_macros($tpl, array(
1970 '$guid' => $item['guid'],
1971 '$type' => 'StatusMessage',
1972 '$handle' => $myaddr,
1973 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1976 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1978 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1983 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1986 $logid = random_string(4);
1987 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
1989 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
1993 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
1995 post_url($dest_url . '/', $slap);
1997 $return_code = $a->get_curl_code();
1998 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2000 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2001 logger('diaspora_transmit: queue message');
2003 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2004 intval($contact['id']),
2005 dbesc(NETWORK_DIASPORA),
2007 intval($public_batch)
2010 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2013 // queue message for redelivery
2014 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2019 return(($return_code) ? $return_code : (-1));