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,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1100 intval($importer['uid']),
1102 dbesc($diaspora_handle),
1103 dbesc(datetime_convert('UTC','UTC',$created_at)),
1104 dbesc(datetime_convert()),
1106 dbesc($participant_handles)
1109 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1110 intval($importer['uid']),
1114 $conversation = $c[0];
1116 if(! $conversation) {
1117 logger('diaspora_conversation: unable to create conversation.');
1122 foreach($messages as $mesg) {
1126 $msg_guid = notags(unxmlify($mesg->guid));
1127 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1128 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1129 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1130 $msg_text = unxmlify($mesg->text);
1131 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1132 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1133 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1134 if($msg_conversation_guid != $guid) {
1135 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1141 if($msg_parent_guid != $guid)
1144 $body = diaspora2bb($msg_text);
1145 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1147 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1148 // $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . $msg_diaspora_handle;
1150 $author_signature = base64_decode($msg_author_signature);
1152 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1157 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1159 if(is_array($person) && x($person,'pubkey'))
1160 $key = $person['pubkey'];
1162 logger('diaspora_conversation: unable to find author details');
1167 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1168 logger('diaspora_conversation: verification failed.');
1172 if($msg_parent_author_signature) {
1173 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1175 $parent_author_signature = base64_decode($msg_parent_author_signature);
1179 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1180 logger('diaspora_conversation: owner verification failed.');
1185 $r = q("select id from mail where `uri` = '%s' limit 1",
1189 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1193 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')",
1194 intval($importer['uid']),
1196 intval($conversation['id']),
1197 dbesc($person['name']),
1198 dbesc($person['photo']),
1199 dbesc($person['url']),
1200 intval($contact['id']),
1207 dbesc($msg_created_at)
1210 q("updated conv set updated = '%s' where id = %d limit 1",
1211 dbesc(datetime_convert()),
1212 intval($conversation['id'])
1224 function diaspora_photo($importer,$xml,$msg) {
1227 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1229 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1231 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1233 $guid = notags(unxmlify($xml->guid));
1235 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1237 $public = notags(unxmlify($xml->public));
1239 $created_at = notags(unxmlify($xml_created_at));
1242 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1246 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1247 logger('diaspora_photo: Ignoring this author.');
1251 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1252 intval($importer['uid']),
1253 dbesc($status_message_guid)
1256 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1259 $parent_item = $r[0];
1261 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1263 $link_text = scale_diaspora_images($link_text);
1265 if(strpos($parent_item['body'],$link_text) === false) {
1266 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1267 dbesc($link_text . $parent_item['body']),
1268 intval($parent_item['id']),
1269 intval($parent_item['uid'])
1279 function diaspora_like($importer,$xml,$msg) {
1282 $guid = notags(unxmlify($xml->guid));
1283 $parent_guid = notags(unxmlify($xml->parent_guid));
1284 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1285 $target_type = notags(unxmlify($xml->target_type));
1286 $positive = notags(unxmlify($xml->positive));
1287 $author_signature = notags(unxmlify($xml->author_signature));
1289 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1291 // likes on comments not supported here and likes on photos not supported by Diaspora
1293 if($target_type !== 'Post')
1296 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1298 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1302 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1303 logger('diaspora_like: Ignoring this author.');
1307 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1308 intval($importer['uid']),
1312 logger('diaspora_like: parent item not found: ' . $guid);
1316 $parent_item = $r[0];
1318 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1319 intval($importer['uid']),
1323 if($positive === 'true') {
1324 logger('diaspora_like: duplicate like: ' . $guid);
1327 if($positive === 'false') {
1328 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1329 intval($r[0]['id']),
1330 intval($importer['uid'])
1333 // send notification via proc_run()
1337 if($positive === 'false') {
1338 logger('diaspora_like: unlike received with no corresponding like');
1342 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1344 $author_signature = base64_decode($author_signature);
1346 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1351 $person = find_diaspora_person_by_handle($diaspora_handle);
1352 if(is_array($person) && x($person,'pubkey'))
1353 $key = $person['pubkey'];
1355 logger('diaspora_like: unable to find author details');
1360 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1361 logger('diaspora_like: verification failed.');
1365 if($parent_author_signature) {
1367 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1369 $parent_author_signature = base64_decode($parent_author_signature);
1373 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1374 logger('diaspora_like: owner verification failed.');
1379 // Phew! Everything checks out. Now create an item.
1381 $uri = $diaspora_handle . ':' . $guid;
1383 $activity = ACTIVITY_LIKE;
1384 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1385 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1386 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1387 $body = $parent_item['body'];
1392 <type>$objtype</type>
1394 <id>{$parent_item['uri']}</id>
1397 <content>$body</content>
1400 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1405 $arr['uid'] = $importer['uid'];
1406 $arr['guid'] = $guid;
1407 $arr['contact-id'] = $contact['id'];
1408 $arr['type'] = 'activity';
1409 $arr['wall'] = $parent_item['wall'];
1410 $arr['gravity'] = GRAVITY_LIKE;
1411 $arr['parent'] = $parent_item['id'];
1412 $arr['parent-uri'] = $parent_item['uri'];
1414 $arr['owner-name'] = $parent_item['name'];
1415 $arr['owner-link'] = $parent_item['url'];
1416 $arr['owner-avatar'] = $parent_item['thumb'];
1418 $arr['author-name'] = $person['name'];
1419 $arr['author-link'] = $person['url'];
1420 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1422 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1423 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1424 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1425 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1427 $arr['app'] = 'Diaspora';
1429 $arr['private'] = $parent_item['private'];
1430 $arr['verb'] = $activity;
1431 $arr['object-type'] = $objtype;
1432 $arr['object'] = $obj;
1433 $arr['visible'] = 1;
1435 $arr['last-child'] = 0;
1437 $message_id = item_store($arr);
1441 q("update item set plink = '%s' where id = %d limit 1",
1442 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1447 if(! $parent_author_signature) {
1448 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1449 intval($message_id),
1450 dbesc($author_signed_data),
1451 dbesc(base64_encode($author_signature)),
1452 dbesc($diaspora_handle)
1456 // if the message isn't already being relayed, notify others
1457 // the existence of parent_author_signature means the parent_author or owner
1458 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1460 if(($parent_item['origin']) && (! $parent_author_signature))
1461 proc_run('php','include/notifier.php','comment',$message_id);
1466 function diaspora_retraction($importer,$xml) {
1468 $guid = notags(unxmlify($xml->guid));
1469 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1470 $type = notags(unxmlify($xml->type));
1472 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1476 if($type === 'Person') {
1477 require_once('include/Contact.php');
1478 contact_remove($contact['id']);
1480 elseif($type === 'Post') {
1481 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1483 intval($importer['uid'])
1486 if(link_compare($r[0]['author-link'],$contact['url'])) {
1487 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1488 dbesc(datetime_convert()),
1499 function diaspora_signed_retraction($importer,$xml) {
1501 $guid = notags(unxmlify($xml->target_guid));
1502 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1503 $type = notags(unxmlify($xml->target_type));
1504 $sig = notags(unxmlify($xml->target_author_signature));
1506 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1510 // this may not yet work for comments. Need to see how the relaying works
1511 // and figure out who signs it.
1514 $signed_data = $guid . ';' . $type ;
1516 $sig = base64_decode($sig);
1520 if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1521 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1525 if($type === 'StatusMessage') {
1526 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1528 intval($importer['uid'])
1531 if(link_compare($r[0]['author-link'],$contact['url'])) {
1532 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1533 dbesc(datetime_convert()),
1544 function diaspora_profile($importer,$xml) {
1547 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1549 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1553 if($contact['blocked']) {
1554 logger('diaspora_post: Ignoring this author.');
1558 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1559 $image_url = unxmlify($xml->image_url);
1560 $birthday = unxmlify($xml->birthday);
1562 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1563 intval($importer['uid']),
1564 intval($contact['id'])
1566 $oldphotos = ((count($r)) ? $r : null);
1568 require_once('include/Photo.php');
1570 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1572 // Generic birthday. We don't know the timezone. The year is irrelevant.
1574 $birthday = str_replace('1000','1901',$birthday);
1576 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1578 $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",
1580 dbesc(datetime_convert()),
1584 dbesc(datetime_convert()),
1586 intval($contact['id']),
1587 intval($importer['uid'])
1592 foreach($oldphotos as $ph) {
1593 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1594 intval($importer['uid']),
1595 intval($contact['id']),
1596 dbesc($ph['resource-id'])
1627 function diaspora_share($me,$contact) {
1629 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1630 $theiraddr = $contact['addr'];
1632 $tpl = get_markup_template('diaspora_share.tpl');
1633 $msg = replace_macros($tpl, array(
1634 '$sender' => $myaddr,
1635 '$recipient' => $theiraddr
1638 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1640 return(diaspora_transmit($owner,$contact,$slap, false));
1643 function diaspora_unshare($me,$contact) {
1646 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1648 $tpl = get_markup_template('diaspora_retract.tpl');
1649 $msg = replace_macros($tpl, array(
1650 '$guid' => $me['guid'],
1651 '$type' => 'Person',
1652 '$handle' => $myaddr
1655 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1657 return(diaspora_transmit($owner,$contact,$slap, false));
1663 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1666 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1667 $theiraddr = $contact['addr'];
1671 $body = $item['body'];
1674 // We're trying to match Diaspora's split message/photo protocol but
1675 // all the photos are displayed on D* as links and not img's - even
1676 // though we're sending pretty much precisely what they send us when
1677 // doing the same operation.
1678 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1679 // which seems to get through intact.
1681 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1683 foreach($matches as $mtch) {
1685 $detail['str'] = $mtch[0];
1686 $detail['path'] = dirname($mtch[1]) . '/';
1687 $detail['file'] = basename($mtch[1]);
1688 $detail['guid'] = $item['guid'];
1689 $detail['handle'] = $myaddr;
1690 $images[] = $detail;
1691 $body = str_replace($detail['str'],$mtch[1],$body);
1696 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1698 if($item['attach']) {
1699 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1701 $body .= "\n" . t('Attachments:') . "\n";
1702 foreach($matches as $mtch) {
1703 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1709 $public = (($item['private']) ? 'false' : 'true');
1711 require_once('include/datetime.php');
1712 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1714 $tpl = get_markup_template('diaspora_post.tpl');
1715 $msg = replace_macros($tpl, array(
1717 '$guid' => $item['guid'],
1718 '$handle' => xmlify($myaddr),
1719 '$public' => $public,
1720 '$created' => $created
1723 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1725 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1727 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1729 if(count($images)) {
1730 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1733 return $return_code;
1737 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1739 if(! count($images))
1741 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1743 $tpl = get_markup_template('diaspora_photo.tpl');
1744 foreach($images as $image) {
1745 if(! stristr($image['path'],$mysite))
1747 $resource = str_replace('.jpg','',$image['file']);
1748 $resource = substr($resource,0,strpos($resource,'-'));
1750 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1752 intval($owner['uid'])
1756 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1757 $msg = replace_macros($tpl,array(
1758 '$path' => xmlify($image['path']),
1759 '$filename' => xmlify($image['file']),
1760 '$msg_guid' => xmlify($image['guid']),
1761 '$guid' => xmlify($r[0]['guid']),
1762 '$handle' => xmlify($image['handle']),
1763 '$public' => xmlify($public),
1764 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1768 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1769 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1771 diaspora_transmit($owner,$contact,$slap,$public_batch);
1776 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1779 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1780 $theiraddr = $contact['addr'];
1782 $p = q("select guid from item where parent = %d limit 1",
1786 $parent_guid = $p[0]['guid'];
1790 if($item['verb'] === ACTIVITY_LIKE) {
1791 $tpl = get_markup_template('diaspora_like.tpl');
1793 $target_type = 'Post';
1794 $positive = (($item['deleted']) ? 'false' : 'true');
1797 $tpl = get_markup_template('diaspora_comment.tpl');
1801 $text = html_entity_decode(bb2diaspora($item['body']));
1806 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1808 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1810 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1812 $msg = replace_macros($tpl,array(
1813 '$guid' => xmlify($item['guid']),
1814 '$parent_guid' => xmlify($parent_guid),
1815 '$target_type' =>xmlify($target_type),
1816 '$authorsig' => xmlify($authorsig),
1817 '$body' => xmlify($text),
1818 '$positive' => xmlify($positive),
1819 '$handle' => xmlify($myaddr)
1822 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1824 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1826 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1830 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1834 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1835 $theiraddr = $contact['addr'];
1838 $p = q("select guid from item where parent = %d limit 1",
1842 $parent_guid = $p[0]['guid'];
1846 if($item['verb'] === ACTIVITY_LIKE) {
1847 $tpl = get_markup_template('diaspora_like_relay.tpl');
1849 $target_type = 'Post';
1850 $positive = (($item['deleted']) ? 'false' : 'true');
1853 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1857 $body = $item['body'];
1859 $text = html_entity_decode(bb2diaspora($body));
1861 // fetch the original signature if somebody sent the post to us to relay
1862 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1863 // action. It wasn't needed. In that case create the original signature and the
1864 // owner (parent author) signature
1865 // comments from other networks will be relayed under our name, with a brief
1866 // preamble to describe what's happening and noting the real author
1868 $r = q("select * from sign where iid = %d limit 1",
1873 $signed_text = $orig_sign['signed_text'];
1874 $authorsig = $orig_sign['signature'];
1875 $handle = $orig_sign['signer'];
1879 $itemcontact = q("select * from contact where `id` = %d limit 1",
1880 intval($item['contact-id'])
1882 if(count($itemcontact)) {
1883 if(! $itemcontact[0]['self']) {
1884 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1885 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
1886 network_to_name($itemcontact['network'])) . "\n";
1887 $body = $prefix . $body;
1893 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1895 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1897 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1899 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1900 intval($item['id']),
1901 dbesc($signed_text),
1902 dbesc(base64_encode($authorsig)),
1911 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1913 $msg = replace_macros($tpl,array(
1914 '$guid' => xmlify($item['guid']),
1915 '$parent_guid' => xmlify($parent_guid),
1916 '$target_type' =>xmlify($target_type),
1917 '$authorsig' => xmlify($orig_sign['signature']),
1918 '$parentsig' => xmlify($parentauthorsig),
1919 '$body' => xmlify($text),
1920 '$positive' => xmlify($positive),
1921 '$handle' => xmlify($handle)
1924 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1926 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1928 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1934 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1937 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1939 $signed_text = $item['guid'] . ';' . 'StatusMessage';
1941 $tpl = get_markup_template('diaspora_signed_retract.tpl');
1942 $msg = replace_macros($tpl, array(
1943 '$guid' => $item['guid'],
1944 '$type' => 'StatusMessage',
1945 '$handle' => $myaddr,
1946 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1949 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1951 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1954 function diaspora_send_mail($item,$owner,$contact) {
1957 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1959 $r = q("select * from conv where id = %d and uid = %d limit 1",
1960 intval($item['convid']),
1961 intval($item['uid'])
1965 logger('diaspora_send_mail: conversation not found.');
1972 if($item['parent-uri'] != $item['uri']) {
1973 $r = q("select * from mail where uri = '%s' and uid = %d limit 1",
1974 dbesc($item['parent-uri']),
1975 intval($item['uid'])
1981 'guid' => xmlify($cnv['guid']),
1982 'subject' => xmlify($cnv['subject']),
1983 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
1984 'diaspora_handle' => xmlify($cnv['creator']),
1985 'participant_handles' => xmlify($cnv['recips'])
1988 $body = bb2diaspora($item['body']);
1989 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1990 $parent_guid = (($item['parent-uri'] == $item['uri']) ? $cnv['guid'] : $parent['guid']);
1992 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $body . ';'
1993 . $created . ';' . $myaddr . ';' . $cnv['guid'];
1995 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1998 'guid' => xmlify($item['guid']),
1999 'parent_guid' => (($item['parent-uri'] == $item['uri']) ? xmlify($cnv['guid']) : xmlify($parent['guid'])),
2000 'parent_author_signature' => (($item['parent-uri'] == $item['uri']) ? xmlify($sig) : null),
2001 'author_signature' => xmlify($sig),
2002 'text' => xmlify($body),
2003 'created_at' => xmlify($created),
2004 'diaspora_handle' => xmlify($myaddr),
2005 'conversation_guid' => xmlify($cnv['guid'])
2008 $conv['messages'] = array($msg);
2010 $tpl = get_markup_template('diaspora_conversation.tpl');
2011 $msg = replace_macros($tpl, array('$conv' => $conv));
2013 logger('diaspora_conversation: ' . print_r($msg,true));
2015 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2017 return(diaspora_transmit($owner,$contact,$slap,false));
2022 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
2025 $logid = random_string(4);
2026 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2028 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2032 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2034 post_url($dest_url . '/', $slap);
2036 $return_code = $a->get_curl_code();
2037 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2039 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2040 logger('diaspora_transmit: queue message');
2042 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2043 intval($contact['id']),
2044 dbesc(NETWORK_DIASPORA),
2046 intval($public_batch)
2049 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2052 // queue message for redelivery
2053 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2058 return(($return_code) ? $return_code : (-1));