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->signed_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);
80 elseif($xmlbase->message) {
81 $ret = diaspora_message($importer,$xmlbase->message,$msg);
84 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
89 function diaspora_get_contact_by_handle($uid,$handle) {
90 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
91 dbesc(NETWORK_DIASPORA),
100 function find_diaspora_person_by_handle($handle) {
102 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
103 dbesc(NETWORK_DIASPORA),
107 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
108 // update record occasionally so it doesn't get stale
109 $d = strtotime($r[0]['updated'] . ' +00:00');
110 if($d > strtotime('now - 14 days'))
114 logger('find_diaspora_person_by_handle: refresh',LOGGER_DEBUG);
115 require_once('include/Scrape.php');
116 $r = probe_url($handle, PROBE_DIASPORA);
117 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
118 add_fcontact($r,$update);
125 function get_diaspora_key($uri) {
126 logger('Fetching diaspora key for: ' . $uri);
128 $r = find_diaspora_person_by_handle($uri);
135 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
138 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
141 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
143 // $b64_data = base64_encode($msg);
144 // $b64url_data = base64url_encode($b64_data);
146 $b64url_data = base64url_encode($msg);
148 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
150 $type = 'application/xml';
151 $encoding = 'base64url';
154 $signable_data = $data . '.' . base64url_encode($type) . '.'
155 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
157 $signature = rsa_sign($signable_data,$prvkey);
158 $sig = base64url_encode($signature);
161 <?xml version='1.0' encoding='UTF-8'?>
162 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
164 <author_id>$handle</author_id>
167 <me:encoding>base64url</me:encoding>
168 <me:alg>RSA-SHA256</me:alg>
169 <me:data type="application/xml">$data</me:data>
170 <me:sig>$sig</me:sig>
175 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
183 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
187 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
189 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
191 // without a public key nothing will work
194 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
198 $inner_aes_key = random_string(32);
199 $b_inner_aes_key = base64_encode($inner_aes_key);
200 $inner_iv = random_string(16);
201 $b_inner_iv = base64_encode($inner_iv);
203 $outer_aes_key = random_string(32);
204 $b_outer_aes_key = base64_encode($outer_aes_key);
205 $outer_iv = random_string(16);
206 $b_outer_iv = base64_encode($outer_iv);
208 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
210 $padded_data = pkcs5_pad($msg,16);
211 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
213 $b64_data = base64_encode($inner_encrypted);
216 $b64url_data = base64url_encode($b64_data);
217 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
219 $type = 'application/xml';
220 $encoding = 'base64url';
223 $signable_data = $data . '.' . base64url_encode($type) . '.'
224 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
226 $signature = rsa_sign($signable_data,$prvkey);
227 $sig = base64url_encode($signature);
229 $decrypted_header = <<< EOT
232 <aes_key>$b_inner_aes_key</aes_key>
233 <author_id>$handle</author_id>
237 $decrypted_header = pkcs5_pad($decrypted_header,16);
239 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
241 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
243 $encrypted_outer_key_bundle = '';
244 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
246 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
248 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
250 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
251 'ciphertext' => base64_encode($ciphertext)));
252 $cipher_json = base64_encode($encrypted_header_json_object);
254 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
257 <?xml version='1.0' encoding='UTF-8'?>
258 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
261 <me:encoding>base64url</me:encoding>
262 <me:alg>RSA-SHA256</me:alg>
263 <me:data type="application/xml">$data</me:data>
264 <me:sig>$sig</me:sig>
269 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
276 * diaspora_decode($importer,$xml)
277 * array $importer -> from user table
278 * string $xml -> urldecoded Diaspora salmon
281 * 'message' -> decoded Diaspora XML message
282 * 'author' -> author diaspora handle
283 * 'key' -> author public key (converted to pkcs#8)
285 * Author and key are used elsewhere to save a lookup for verifying replies and likes
289 function diaspora_decode($importer,$xml) {
292 $basedom = parse_xml_string($xml);
294 $children = $basedom->children('https://joindiaspora.com/protocol');
296 if($children->header) {
298 $author_link = str_replace('acct:','',$children->header->author_id);
302 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
304 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
305 $ciphertext = base64_decode($encrypted_header->ciphertext);
307 $outer_key_bundle = '';
308 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
310 $j_outer_key_bundle = json_decode($outer_key_bundle);
312 $outer_iv = base64_decode($j_outer_key_bundle->iv);
313 $outer_key = base64_decode($j_outer_key_bundle->key);
315 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
318 $decrypted = pkcs5_unpad($decrypted);
321 * $decrypted now contains something like
324 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
325 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
330 * <name>Ryan Hughes</name>
331 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
336 * <author_id>galaxor@diaspora.priateship.org</author_id>
340 * </decrypted_header>
343 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
344 $idom = parse_xml_string($decrypted,false);
346 $inner_iv = base64_decode($idom->iv);
347 $inner_aes_key = base64_decode($idom->aes_key);
349 $author_link = str_replace('acct:','',$idom->author_id);
353 $dom = $basedom->children(NAMESPACE_SALMON_ME);
355 // figure out where in the DOM tree our data is hiding
357 if($dom->provenance->data)
358 $base = $dom->provenance;
359 elseif($dom->env->data)
365 logger('mod-diaspora: unable to locate salmon data in xml ');
366 http_status_exit(400);
370 // Stash the signature away for now. We have to find their key or it won't be good for anything.
371 $signature = base64url_decode($base->sig);
375 // strip whitespace so our data element will return to one big base64 blob
376 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
379 // stash away some other stuff for later
381 $type = $base->data[0]->attributes()->type[0];
382 $keyhash = $base->sig[0]->attributes()->keyhash[0];
383 $encoding = $base->encoding;
387 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
391 $data = base64url_decode($data);
395 $inner_decrypted = $data;
399 // Decode the encrypted blob
401 $inner_encrypted = base64_decode($data);
402 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
403 $inner_decrypted = pkcs5_unpad($inner_decrypted);
407 logger('mod-diaspora: Could not retrieve author URI.');
408 http_status_exit(400);
411 // Once we have the author URI, go to the web and try to find their public key
412 // (first this will look it up locally if it is in the fcontact cache)
413 // This will also convert diaspora public key from pkcs#1 to pkcs#8
415 logger('mod-diaspora: Fetching key for ' . $author_link );
416 $key = get_diaspora_key($author_link);
419 logger('mod-diaspora: Could not retrieve author key.');
420 http_status_exit(400);
423 $verify = rsa_verify($signed_data,$signature,$key);
426 logger('mod-diaspora: Message did not verify. Discarding.');
427 http_status_exit(400);
430 logger('mod-diaspora: Message verified.');
432 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
437 function diaspora_request($importer,$xml) {
441 $sender_handle = unxmlify($xml->sender_handle);
442 $recipient_handle = unxmlify($xml->recipient_handle);
444 if(! $sender_handle || ! $recipient_handle)
447 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
451 // perhaps we were already sharing with this person. Now they're sharing with us.
452 // That makes us friends.
454 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
455 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
456 intval(CONTACT_IS_FRIEND),
457 intval($contact['id']),
458 intval($importer['uid'])
463 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
464 intval($importer['uid'])
467 if((count($r)) && (! $r[0]['hide-friends']) && (! $contact['hidden'])) {
468 require_once('include/items.php');
470 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
471 intval($importer['uid'])
474 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
476 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
479 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
480 $arr['uid'] = $importer['uid'];
481 $arr['contact-id'] = $self[0]['id'];
483 $arr['type'] = 'wall';
486 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
487 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
488 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
489 $arr['verb'] = ACTIVITY_FRIEND;
490 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
492 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
493 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
494 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
495 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
497 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
498 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
499 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
500 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
501 $arr['object'] .= '</link></object>' . "\n";
502 $arr['last-child'] = 1;
504 $arr['allow_cid'] = $user[0]['allow_cid'];
505 $arr['allow_gid'] = $user[0]['allow_gid'];
506 $arr['deny_cid'] = $user[0]['deny_cid'];
507 $arr['deny_gid'] = $user[0]['deny_gid'];
509 $i = item_store($arr);
511 proc_run('php',"include/notifier.php","activity","$i");
520 $ret = find_diaspora_person_by_handle($sender_handle);
523 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
524 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
528 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
532 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
533 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
534 intval($importer['uid']),
535 dbesc($ret['network']),
539 dbesc(normalise_link($ret['url'])),
543 dbesc($ret['photo']),
544 dbesc($ret['pubkey']),
545 dbesc($ret['notify']),
551 // find the contact record we just created
553 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
555 if(! $contact_record) {
556 logger('diaspora_request: unable to locate newly created contact record.');
560 if($importer['page-flags'] == PAGE_NORMAL) {
562 $hash = random_string() . (string) time(); // Generate a confirm_key
564 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
565 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
566 intval($importer['uid']),
567 intval($contact_record['id']),
570 dbesc( t('Sharing notification from Diaspora network')),
572 dbesc(datetime_convert())
577 // automatic friend approval
579 require_once('include/Photo.php');
581 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
583 // technically they are sharing with us (CONTACT_IS_SHARING),
584 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
585 // we are going to change the relationship and make them a follower.
587 if($importer['page-flags'] == PAGE_FREELOVE)
588 $new_relation = CONTACT_IS_FRIEND;
590 $new_relation = CONTACT_IS_FOLLOWER;
592 $r = q("UPDATE `contact` SET
599 `avatar-date` = '%s',
602 WHERE `id` = %d LIMIT 1
607 intval($new_relation),
608 dbesc(datetime_convert()),
609 dbesc(datetime_convert()),
610 dbesc(datetime_convert()),
611 intval($contact_record['id'])
614 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
616 $ret = diaspora_share($u[0],$contact_record);
622 function diaspora_post_allow($importer,$contact) {
623 if(($contact['blocked']) || ($contact['readonly']))
625 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
627 if($contact['rel'] == CONTACT_IS_FOLLOWER)
628 if($importer['page-flags'] == PAGE_COMMUNITY)
634 function diaspora_post($importer,$xml) {
637 $guid = notags(unxmlify($xml->guid));
638 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
640 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
644 if(! diaspora_post_allow($importer,$contact)) {
645 logger('diaspora_post: Ignoring this author.');
649 $message_id = $diaspora_handle . ':' . $guid;
650 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
651 intval($importer['uid']),
656 logger('diaspora_post: message exists: ' . $guid);
660 // allocate a guid on our system - we aren't fixing any collisions.
661 // we're ignoring them
663 $g = q("select * from guid where guid = '%s' limit 1",
667 q("insert into guid ( guid ) values ( '%s' )",
672 $created = unxmlify($xml->created_at);
673 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
675 $body = diaspora2bb($xml->raw_message);
681 $tags = get_tags($body);
684 foreach($tags as $tag) {
685 if(strpos($tag,'#') === 0) {
686 if(strpos($tag,'[url='))
689 // don't link tags that are already embedded in links
691 if(preg_match('/\[(.*?)' . preg_quote($tag) . '(.*?)\]/',$body))
693 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag) . '(.*?)\)/',$body))
696 $basetag = str_replace('_',' ',substr($tag,1));
697 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
698 if(strlen($str_tags))
700 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
706 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
708 foreach($matches as $mtch) {
709 if(strlen($str_tags))
711 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
715 $datarray['uid'] = $importer['uid'];
716 $datarray['contact-id'] = $contact['id'];
717 $datarray['wall'] = 0;
718 $datarray['guid'] = $guid;
719 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
720 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
721 $datarray['private'] = $private;
722 $datarray['parent'] = 0;
723 $datarray['owner-name'] = $contact['name'];
724 $datarray['owner-link'] = $contact['url'];
725 $datarray['owner-avatar'] = $contact['thumb'];
726 $datarray['author-name'] = $contact['name'];
727 $datarray['author-link'] = $contact['url'];
728 $datarray['author-avatar'] = $contact['thumb'];
729 $datarray['body'] = $body;
730 $datarray['tag'] = $str_tags;
731 $datarray['app'] = 'Diaspora';
733 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
735 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
737 $message_id = item_store($datarray);
740 q("update item set plink = '%s' where id = %d limit 1",
741 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
750 function diaspora_reshare($importer,$xml) {
752 logger('diaspora_reshare: init: ' . print_r($xml,true));
755 $guid = notags(unxmlify($xml->guid));
756 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
759 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
763 if(! diaspora_post_allow($importer,$contact)) {
764 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
768 $message_id = $diaspora_handle . ':' . $guid;
769 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
770 intval($importer['uid']),
775 logger('diaspora_reshare: message exists: ' . $guid);
779 $orig_author = notags(unxmlify($xml->root_diaspora_id));
780 $orig_guid = notags(unxmlify($xml->root_guid));
782 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
783 $x = fetch_url($source_url);
785 $x = fetch_url(str_replace('https://','http://',$source_url));
787 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
790 logger('diaspora_reshare: source: ' . $x);
792 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
793 $source_xml = parse_xml_string($x,false);
795 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
796 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
797 $body = scale_external_images($body,false);
799 elseif($source_xml->post->asphoto->image_url) {
800 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
801 $body = scale_external_images($body);
803 elseif($source_xml->post->status_message) {
804 $body = diaspora2bb($source_xml->post->status_message->raw_message);
805 $body = scale_external_images($body);
809 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
813 logger('diaspora_reshare: empty body: source= ' . $x);
817 $person = find_diaspora_person_by_handle($orig_author);
819 if(is_array($person) && x($person,'name') && x($person,'url'))
820 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
822 $details = $orig_author;
824 $prefix = '♲ ' . $details . "\n";
827 // allocate a guid on our system - we aren't fixing any collisions.
828 // we're ignoring them
830 $g = q("select * from guid where guid = '%s' limit 1",
834 q("insert into guid ( guid ) values ( '%s' )",
839 $created = unxmlify($xml->created_at);
840 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
846 $tags = get_tags($body);
849 foreach($tags as $tag) {
850 if(strpos($tag,'#') === 0) {
851 if(strpos($tag,'[url='))
854 // don't link tags that are already embedded in links
856 if(preg_match('/\[(.*?)' . preg_quote($tag) . '(.*?)\]/',$body))
858 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag) . '(.*?)\)/',$body))
862 $basetag = str_replace('_',' ',substr($tag,1));
863 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
864 if(strlen($str_tags))
866 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
872 $datarray['uid'] = $importer['uid'];
873 $datarray['contact-id'] = $contact['id'];
874 $datarray['wall'] = 0;
875 $datarray['guid'] = $guid;
876 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
877 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
878 $datarray['private'] = $private;
879 $datarray['parent'] = 0;
880 $datarray['owner-name'] = $contact['name'];
881 $datarray['owner-link'] = $contact['url'];
882 $datarray['owner-avatar'] = $contact['thumb'];
883 $datarray['author-name'] = $contact['name'];
884 $datarray['author-link'] = $contact['url'];
885 $datarray['author-avatar'] = $contact['thumb'];
886 $datarray['body'] = $prefix . $body;
887 $datarray['tag'] = $str_tags;
888 $datarray['app'] = 'Diaspora';
890 $message_id = item_store($datarray);
893 q("update item set plink = '%s' where id = %d limit 1",
894 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
904 function diaspora_asphoto($importer,$xml) {
905 logger('diaspora_asphoto called');
908 $guid = notags(unxmlify($xml->guid));
909 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
911 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
915 if(! diaspora_post_allow($importer,$contact)) {
916 logger('diaspora_asphoto: Ignoring this author.');
920 $message_id = $diaspora_handle . ':' . $guid;
921 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
922 intval($importer['uid']),
927 logger('diaspora_asphoto: message exists: ' . $guid);
931 // allocate a guid on our system - we aren't fixing any collisions.
932 // we're ignoring them
934 $g = q("select * from guid where guid = '%s' limit 1",
938 q("insert into guid ( guid ) values ( '%s' )",
943 $created = unxmlify($xml->created_at);
944 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
946 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
947 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
948 $body = scale_external_images($body,false);
950 elseif($xml->image_url) {
951 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
952 $body = scale_external_images($body);
955 logger('diaspora_asphoto: no photo url found.');
962 $datarray['uid'] = $importer['uid'];
963 $datarray['contact-id'] = $contact['id'];
964 $datarray['wall'] = 0;
965 $datarray['guid'] = $guid;
966 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
967 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
968 $datarray['private'] = $private;
969 $datarray['parent'] = 0;
970 $datarray['owner-name'] = $contact['name'];
971 $datarray['owner-link'] = $contact['url'];
972 $datarray['owner-avatar'] = $contact['thumb'];
973 $datarray['author-name'] = $contact['name'];
974 $datarray['author-link'] = $contact['url'];
975 $datarray['author-avatar'] = $contact['thumb'];
976 $datarray['body'] = $body;
978 $datarray['app'] = 'Diaspora/Cubbi.es';
980 $message_id = item_store($datarray);
983 q("update item set plink = '%s' where id = %d limit 1",
984 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
998 function diaspora_comment($importer,$xml,$msg) {
1001 $guid = notags(unxmlify($xml->guid));
1002 $parent_guid = notags(unxmlify($xml->parent_guid));
1003 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1004 $target_type = notags(unxmlify($xml->target_type));
1005 $text = unxmlify($xml->text);
1006 $author_signature = notags(unxmlify($xml->author_signature));
1008 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1010 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1012 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1016 if(! diaspora_post_allow($importer,$contact)) {
1017 logger('diaspora_comment: Ignoring this author.');
1021 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1022 intval($importer['uid']),
1026 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1030 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1031 intval($importer['uid']),
1035 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1038 $parent_item = $r[0];
1040 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1042 $author_signature = base64_decode($author_signature);
1044 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1049 $person = find_diaspora_person_by_handle($diaspora_handle);
1051 if(is_array($person) && x($person,'pubkey'))
1052 $key = $person['pubkey'];
1054 logger('diaspora_comment: unable to find author details');
1059 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1060 logger('diaspora_comment: verification failed.');
1064 if($parent_author_signature) {
1065 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1067 $parent_author_signature = base64_decode($parent_author_signature);
1071 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1072 logger('diaspora_comment: owner verification failed.');
1077 // Phew! Everything checks out. Now create an item.
1079 $body = diaspora2bb($text);
1081 $message_id = $diaspora_handle . ':' . $guid;
1083 $datarray = array();
1087 $tags = get_tags($body);
1090 foreach($tags as $tag) {
1091 if(strpos($tag,'#') === 0) {
1092 if(strpos($tag,'[url='))
1095 // don't link tags that are already embedded in links
1097 if(preg_match('/\[(.*?)' . preg_quote($tag) . '(.*?)\]/',$body))
1099 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag) . '(.*?)\)/',$body))
1103 $basetag = str_replace('_',' ',substr($tag,1));
1104 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1105 if(strlen($str_tags))
1107 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1113 $datarray['uid'] = $importer['uid'];
1114 $datarray['contact-id'] = $contact['id'];
1115 $datarray['wall'] = $parent_item['wall'];
1116 $datarray['gravity'] = GRAVITY_COMMENT;
1117 $datarray['guid'] = $guid;
1118 $datarray['uri'] = $message_id;
1119 $datarray['parent-uri'] = $parent_item['uri'];
1121 // No timestamps for comments? OK, we'll the use current time.
1122 $datarray['created'] = $datarray['edited'] = datetime_convert();
1123 $datarray['private'] = $parent_item['private'];
1125 $datarray['owner-name'] = $parent_item['owner-name'];
1126 $datarray['owner-link'] = $parent_item['owner-link'];
1127 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1129 $datarray['author-name'] = $person['name'];
1130 $datarray['author-link'] = $person['url'];
1131 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1132 $datarray['body'] = $body;
1133 $datarray['tag'] = $str_tags;
1135 // We can't be certain what the original app is if the message is relayed.
1136 if(($parent_item['origin']) && (! $parent_author_signature))
1137 $datarray['app'] = 'Diaspora';
1139 $message_id = item_store($datarray);
1142 q("update item set plink = '%s' where id = %d limit 1",
1143 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1148 if(($parent_item['origin']) && (! $parent_author_signature)) {
1149 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1150 intval($message_id),
1151 dbesc($author_signed_data),
1152 dbesc(base64_encode($author_signature)),
1153 dbesc($diaspora_handle)
1156 // if the message isn't already being relayed, notify others
1157 // the existence of parent_author_signature means the parent_author or owner
1158 // is already relaying.
1160 proc_run('php','include/notifier.php','comment',$message_id);
1168 function diaspora_conversation($importer,$xml,$msg) {
1172 $guid = notags(unxmlify($xml->guid));
1173 $subject = notags(unxmlify($xml->subject));
1174 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1175 $participant_handles = notags(unxmlify($xml->participant_handles));
1176 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1178 $parent_uri = $diaspora_handle . ':' . $guid;
1180 $messages = $xml->message;
1182 if(! count($messages)) {
1183 logger('diaspora_conversation: empty conversation');
1187 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1189 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1193 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1194 logger('diaspora_conversation: Ignoring this author.');
1198 $conversation = null;
1200 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1201 intval($importer['uid']),
1205 $conversation = $c[0];
1207 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1208 intval($importer['uid']),
1210 dbesc($diaspora_handle),
1211 dbesc(datetime_convert('UTC','UTC',$created_at)),
1212 dbesc(datetime_convert()),
1214 dbesc($participant_handles)
1217 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1218 intval($importer['uid']),
1222 $conversation = $c[0];
1224 if(! $conversation) {
1225 logger('diaspora_conversation: unable to create conversation.');
1229 foreach($messages as $mesg) {
1233 $msg_guid = notags(unxmlify($mesg->guid));
1234 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1235 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1236 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1237 $msg_text = unxmlify($mesg->text);
1238 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1239 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1240 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1241 if($msg_conversation_guid != $guid) {
1242 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1246 $body = diaspora2bb($msg_text);
1247 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1249 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1251 $author_signature = base64_decode($msg_author_signature);
1253 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1258 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1260 if(is_array($person) && x($person,'pubkey'))
1261 $key = $person['pubkey'];
1263 logger('diaspora_conversation: unable to find author details');
1268 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1269 logger('diaspora_conversation: verification failed.');
1273 if($msg_parent_author_signature) {
1274 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1276 $parent_author_signature = base64_decode($msg_parent_author_signature);
1280 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1281 logger('diaspora_conversation: owner verification failed.');
1286 $r = q("select id from mail where `uri` = '%s' limit 1",
1290 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1294 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1295 intval($importer['uid']),
1297 intval($conversation['id']),
1298 dbesc($person['name']),
1299 dbesc($person['photo']),
1300 dbesc($person['url']),
1301 intval($contact['id']),
1308 dbesc($msg_created_at)
1311 q("update conv set updated = '%s' where id = %d limit 1",
1312 dbesc(datetime_convert()),
1313 intval($conversation['id'])
1316 require_once('include/enotify.php');
1318 'type' => NOTIFY_MAIL,
1319 'notify_flags' => $importer['notify-flags'],
1320 'language' => $importer['language'],
1321 'to_name' => $importer['username'],
1322 'to_email' => $importer['email'],
1323 'uid' =>$importer['importer_uid'],
1324 'item' => array('subject' => $subject, 'body' => $body),
1325 'source_name' => $person['name'],
1326 'source_link' => $person['url'],
1327 'source_photo' => $person['thumb'],
1328 'verb' => ACTIVITY_POST,
1336 function diaspora_message($importer,$xml,$msg) {
1340 $msg_guid = notags(unxmlify($xml->guid));
1341 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1342 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1343 $msg_author_signature = notags(unxmlify($xml->author_signature));
1344 $msg_text = unxmlify($xml->text);
1345 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1346 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1347 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1349 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1351 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1353 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1357 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1358 logger('diaspora_message: Ignoring this author.');
1362 $conversation = null;
1364 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1365 intval($importer['uid']),
1366 dbesc($msg_conversation_guid)
1369 $conversation = $c[0];
1371 logger('diaspora_message: conversation not available.');
1377 $body = diaspora2bb($msg_text);
1378 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1380 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1383 $author_signature = base64_decode($msg_author_signature);
1385 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1386 if(is_array($person) && x($person,'pubkey'))
1387 $key = $person['pubkey'];
1389 logger('diaspora_message: unable to find author details');
1393 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1394 logger('diaspora_message: verification failed.');
1398 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1400 intval($importer['uid'])
1403 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1407 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1408 intval($importer['uid']),
1410 intval($conversation['id']),
1411 dbesc($person['name']),
1412 dbesc($person['photo']),
1413 dbesc($person['url']),
1414 intval($contact['id']),
1415 dbesc($conversation['subject']),
1421 dbesc($msg_created_at)
1424 q("update conv set updated = '%s' where id = %d limit 1",
1425 dbesc(datetime_convert()),
1426 intval($conversation['id'])
1433 function diaspora_photo($importer,$xml,$msg) {
1437 logger('diaspora_photo: init',LOGGER_DEBUG);
1439 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1441 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1443 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1445 $guid = notags(unxmlify($xml->guid));
1447 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1449 $public = notags(unxmlify($xml->public));
1451 $created_at = notags(unxmlify($xml_created_at));
1453 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1455 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1457 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1461 if(! diaspora_post_allow($importer,$contact)) {
1462 logger('diaspora_photo: Ignoring this author.');
1466 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1467 intval($importer['uid']),
1468 dbesc($status_message_guid)
1471 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1475 $parent_item = $r[0];
1477 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1479 $link_text = scale_external_images($link_text);
1481 if(strpos($parent_item['body'],$link_text) === false) {
1482 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1483 dbesc($link_text . $parent_item['body']),
1484 intval($parent_item['id']),
1485 intval($parent_item['uid'])
1495 function diaspora_like($importer,$xml,$msg) {
1498 $guid = notags(unxmlify($xml->guid));
1499 $parent_guid = notags(unxmlify($xml->parent_guid));
1500 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1501 $target_type = notags(unxmlify($xml->target_type));
1502 $positive = notags(unxmlify($xml->positive));
1503 $author_signature = notags(unxmlify($xml->author_signature));
1505 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1507 // likes on comments not supported here and likes on photos not supported by Diaspora
1509 if($target_type !== 'Post')
1512 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1514 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1518 if(! diaspora_post_allow($importer,$contact)) {
1519 logger('diaspora_like: Ignoring this author.');
1523 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1524 intval($importer['uid']),
1528 logger('diaspora_like: parent item not found: ' . $guid);
1532 $parent_item = $r[0];
1534 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1535 intval($importer['uid']),
1539 if($positive === 'true') {
1540 logger('diaspora_like: duplicate like: ' . $guid);
1543 if($positive === 'false') {
1544 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1545 intval($r[0]['id']),
1546 intval($importer['uid'])
1549 // send notification via proc_run()
1553 if($positive === 'false') {
1554 logger('diaspora_like: unlike received with no corresponding like');
1558 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1560 $author_signature = base64_decode($author_signature);
1562 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1567 $person = find_diaspora_person_by_handle($diaspora_handle);
1568 if(is_array($person) && x($person,'pubkey'))
1569 $key = $person['pubkey'];
1571 logger('diaspora_like: unable to find author details');
1576 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1577 logger('diaspora_like: verification failed.');
1581 if($parent_author_signature) {
1583 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1585 $parent_author_signature = base64_decode($parent_author_signature);
1589 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1590 logger('diaspora_like: owner verification failed.');
1595 // Phew! Everything checks out. Now create an item.
1597 $uri = $diaspora_handle . ':' . $guid;
1599 $activity = ACTIVITY_LIKE;
1600 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1601 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1602 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1603 $body = $parent_item['body'];
1608 <type>$objtype</type>
1610 <id>{$parent_item['uri']}</id>
1613 <content>$body</content>
1616 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1621 $arr['uid'] = $importer['uid'];
1622 $arr['guid'] = $guid;
1623 $arr['contact-id'] = $contact['id'];
1624 $arr['type'] = 'activity';
1625 $arr['wall'] = $parent_item['wall'];
1626 $arr['gravity'] = GRAVITY_LIKE;
1627 $arr['parent'] = $parent_item['id'];
1628 $arr['parent-uri'] = $parent_item['uri'];
1630 $arr['owner-name'] = $parent_item['name'];
1631 $arr['owner-link'] = $parent_item['url'];
1632 $arr['owner-avatar'] = $parent_item['thumb'];
1634 $arr['author-name'] = $person['name'];
1635 $arr['author-link'] = $person['url'];
1636 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1638 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1639 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1640 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1641 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1643 $arr['app'] = 'Diaspora';
1645 $arr['private'] = $parent_item['private'];
1646 $arr['verb'] = $activity;
1647 $arr['object-type'] = $objtype;
1648 $arr['object'] = $obj;
1649 $arr['visible'] = 1;
1651 $arr['last-child'] = 0;
1653 $message_id = item_store($arr);
1657 q("update item set plink = '%s' where id = %d limit 1",
1658 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1663 if(! $parent_author_signature) {
1664 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1665 intval($message_id),
1666 dbesc($author_signed_data),
1667 dbesc(base64_encode($author_signature)),
1668 dbesc($diaspora_handle)
1672 // if the message isn't already being relayed, notify others
1673 // the existence of parent_author_signature means the parent_author or owner
1674 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1676 if(($parent_item['origin']) && (! $parent_author_signature))
1677 proc_run('php','include/notifier.php','comment',$message_id);
1682 function diaspora_retraction($importer,$xml) {
1685 $guid = notags(unxmlify($xml->guid));
1686 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1687 $type = notags(unxmlify($xml->type));
1689 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1693 if($type === 'Person') {
1694 require_once('include/Contact.php');
1695 contact_remove($contact['id']);
1697 elseif($type === 'Post') {
1698 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1700 intval($importer['uid'])
1703 if(link_compare($r[0]['author-link'],$contact['url'])) {
1704 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1705 dbesc(datetime_convert()),
1716 function diaspora_signed_retraction($importer,$xml,$msg) {
1719 $guid = notags(unxmlify($xml->target_guid));
1720 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1721 $type = notags(unxmlify($xml->target_type));
1722 $sig = notags(unxmlify($xml->target_author_signature));
1724 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1726 logger('diaspora_signed_retraction: no contact');
1730 // this may not yet work for comments. Need to see how the relaying works
1731 // and figure out who signs it.
1734 $signed_data = $guid . ';' . $type ;
1736 $sig = base64_decode($sig);
1740 if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1741 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1745 if($type === 'StatusMessage') {
1746 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1748 intval($importer['uid'])
1751 if(link_compare($r[0]['author-link'],$contact['url'])) {
1752 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1753 dbesc(datetime_convert()),
1760 logger('diaspora_signed_retraction: unknown type: ' . $type);
1766 function diaspora_profile($importer,$xml) {
1769 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1771 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1775 if($contact['blocked']) {
1776 logger('diaspora_post: Ignoring this author.');
1780 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1781 $image_url = unxmlify($xml->image_url);
1782 $birthday = unxmlify($xml->birthday);
1784 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1785 intval($importer['uid']),
1786 intval($contact['id'])
1788 $oldphotos = ((count($r)) ? $r : null);
1790 require_once('include/Photo.php');
1792 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1794 // Generic birthday. We don't know the timezone. The year is irrelevant.
1796 $birthday = str_replace('1000','1901',$birthday);
1798 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1800 // this is to prevent multiple birthday notifications in a single year
1801 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1803 if(substr($birthday,5) === substr($contact['bd'],5))
1804 $birthday = $contact['bd'];
1806 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
1807 // Not doing this currently because D* protocol is scheduled for revision soon.
1809 $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",
1811 dbesc(datetime_convert()),
1815 dbesc(datetime_convert()),
1817 intval($contact['id']),
1818 intval($importer['uid'])
1823 foreach($oldphotos as $ph) {
1824 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1825 intval($importer['uid']),
1826 intval($contact['id']),
1827 dbesc($ph['resource-id'])
1837 function diaspora_share($me,$contact) {
1839 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1840 $theiraddr = $contact['addr'];
1842 $tpl = get_markup_template('diaspora_share.tpl');
1843 $msg = replace_macros($tpl, array(
1844 '$sender' => $myaddr,
1845 '$recipient' => $theiraddr
1848 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1850 return(diaspora_transmit($owner,$contact,$slap, false));
1853 function diaspora_unshare($me,$contact) {
1856 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1858 $tpl = get_markup_template('diaspora_retract.tpl');
1859 $msg = replace_macros($tpl, array(
1860 '$guid' => $me['guid'],
1861 '$type' => 'Person',
1862 '$handle' => $myaddr
1865 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1867 return(diaspora_transmit($owner,$contact,$slap, false));
1873 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1876 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1877 $theiraddr = $contact['addr'];
1881 $body = $item['body'];
1884 // We're trying to match Diaspora's split message/photo protocol but
1885 // all the photos are displayed on D* as links and not img's - even
1886 // though we're sending pretty much precisely what they send us when
1887 // doing the same operation.
1888 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1889 // which seems to get through intact.
1891 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1893 foreach($matches as $mtch) {
1895 $detail['str'] = $mtch[0];
1896 $detail['path'] = dirname($mtch[1]) . '/';
1897 $detail['file'] = basename($mtch[1]);
1898 $detail['guid'] = $item['guid'];
1899 $detail['handle'] = $myaddr;
1900 $images[] = $detail;
1901 $body = str_replace($detail['str'],$mtch[1],$body);
1906 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1908 if($item['attach']) {
1909 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1911 $body .= "\n" . t('Attachments:') . "\n";
1912 foreach($matches as $mtch) {
1913 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1919 $public = (($item['private']) ? 'false' : 'true');
1921 require_once('include/datetime.php');
1922 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1924 $tpl = get_markup_template('diaspora_post.tpl');
1925 $msg = replace_macros($tpl, array(
1927 '$guid' => $item['guid'],
1928 '$handle' => xmlify($myaddr),
1929 '$public' => $public,
1930 '$created' => $created
1933 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1935 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1937 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1939 if(count($images)) {
1940 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1943 return $return_code;
1947 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1949 if(! count($images))
1951 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1953 $tpl = get_markup_template('diaspora_photo.tpl');
1954 foreach($images as $image) {
1955 if(! stristr($image['path'],$mysite))
1957 $resource = str_replace('.jpg','',$image['file']);
1958 $resource = substr($resource,0,strpos($resource,'-'));
1960 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1962 intval($owner['uid'])
1966 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1967 $msg = replace_macros($tpl,array(
1968 '$path' => xmlify($image['path']),
1969 '$filename' => xmlify($image['file']),
1970 '$msg_guid' => xmlify($image['guid']),
1971 '$guid' => xmlify($r[0]['guid']),
1972 '$handle' => xmlify($image['handle']),
1973 '$public' => xmlify($public),
1974 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1978 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1979 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1981 diaspora_transmit($owner,$contact,$slap,$public_batch);
1986 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1989 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1990 $theiraddr = $contact['addr'];
1992 $p = q("select guid from item where parent = %d limit 1",
1996 $parent_guid = $p[0]['guid'];
2000 if($item['verb'] === ACTIVITY_LIKE) {
2001 $tpl = get_markup_template('diaspora_like.tpl');
2003 $target_type = 'Post';
2004 $positive = (($item['deleted']) ? 'false' : 'true');
2007 $tpl = get_markup_template('diaspora_comment.tpl');
2011 $text = html_entity_decode(bb2diaspora($item['body']));
2016 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
2018 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
2020 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2022 $msg = replace_macros($tpl,array(
2023 '$guid' => xmlify($item['guid']),
2024 '$parent_guid' => xmlify($parent_guid),
2025 '$target_type' =>xmlify($target_type),
2026 '$authorsig' => xmlify($authorsig),
2027 '$body' => xmlify($text),
2028 '$positive' => xmlify($positive),
2029 '$handle' => xmlify($myaddr)
2032 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2034 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2036 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2040 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2044 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2045 $theiraddr = $contact['addr'];
2048 $p = q("select guid from item where parent = %d limit 1",
2052 $parent_guid = $p[0]['guid'];
2056 if($item['verb'] === ACTIVITY_LIKE) {
2057 $tpl = get_markup_template('diaspora_like_relay.tpl');
2059 $target_type = 'Post';
2060 $positive = (($item['deleted']) ? 'false' : 'true');
2063 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2067 $body = $item['body'];
2069 $text = html_entity_decode(bb2diaspora($body));
2071 // fetch the original signature if somebody sent the post to us to relay
2072 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
2073 // action. It wasn't needed. In that case create the original signature and the
2074 // owner (parent author) signature
2075 // comments from other networks will be relayed under our name, with a brief
2076 // preamble to describe what's happening and noting the real author
2078 $r = q("select * from sign where iid = %d limit 1",
2083 $signed_text = $orig_sign['signed_text'];
2084 $authorsig = $orig_sign['signature'];
2085 $handle = $orig_sign['signer'];
2089 $itemcontact = q("select * from contact where `id` = %d limit 1",
2090 intval($item['contact-id'])
2092 if(count($itemcontact)) {
2093 if(! $itemcontact[0]['self']) {
2094 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
2095 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
2096 network_to_name($itemcontact['network'])) . "\n";
2097 $body = $prefix . $body;
2103 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
2105 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
2107 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2109 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2110 intval($item['id']),
2111 dbesc($signed_text),
2112 dbesc(base64_encode($authorsig)),
2121 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2123 $msg = replace_macros($tpl,array(
2124 '$guid' => xmlify($item['guid']),
2125 '$parent_guid' => xmlify($parent_guid),
2126 '$target_type' =>xmlify($target_type),
2127 '$authorsig' => xmlify($orig_sign['signature']),
2128 '$parentsig' => xmlify($parentauthorsig),
2129 '$body' => xmlify($text),
2130 '$positive' => xmlify($positive),
2131 '$handle' => xmlify($handle)
2134 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
2136 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2138 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2144 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2147 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2149 $signed_text = $item['guid'] . ';' . 'StatusMessage';
2151 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2152 $msg = replace_macros($tpl, array(
2153 '$guid' => $item['guid'],
2154 '$type' => 'StatusMessage',
2155 '$handle' => $myaddr,
2156 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
2159 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2161 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2164 function diaspora_send_mail($item,$owner,$contact) {
2167 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2169 $r = q("select * from conv where id = %d and uid = %d limit 1",
2170 intval($item['convid']),
2171 intval($item['uid'])
2175 logger('diaspora_send_mail: conversation not found.');
2181 'guid' => xmlify($cnv['guid']),
2182 'subject' => xmlify($cnv['subject']),
2183 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2184 'diaspora_handle' => xmlify($cnv['creator']),
2185 'participant_handles' => xmlify($cnv['recips'])
2188 $body = bb2diaspora($item['body']);
2189 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2191 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2192 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2194 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2197 'guid' => xmlify($item['guid']),
2198 'parent_guid' => xmlify($cnv['guid']),
2199 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2200 'author_signature' => xmlify($sig),
2201 'text' => xmlify($body),
2202 'created_at' => xmlify($created),
2203 'diaspora_handle' => xmlify($myaddr),
2204 'conversation_guid' => xmlify($cnv['guid'])
2207 if($item['reply']) {
2208 $tpl = get_markup_template('diaspora_message.tpl');
2209 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2212 $conv['messages'] = array($msg);
2213 $tpl = get_markup_template('diaspora_conversation.tpl');
2214 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2217 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2219 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2221 return(diaspora_transmit($owner,$contact,$slap,false));
2226 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
2229 $logid = random_string(4);
2230 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2232 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2236 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2238 if(! intval(get_config('system','diaspora_test')))
2239 post_url($dest_url . '/', $slap);
2241 logger('diaspora_transmit: test_mode');
2245 $return_code = $a->get_curl_code();
2246 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2248 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2249 logger('diaspora_transmit: queue message');
2251 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2252 intval($contact['id']),
2253 dbesc(NETWORK_DIASPORA),
2255 intval($public_batch)
2258 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2261 // queue message for redelivery
2262 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2267 return(($return_code) ? $return_code : (-1));