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 $enabled = intval(get_config('system','diaspora_enabled'));
14 logger('mod-diaspora: disabled');
18 $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 ",
19 dbesc(NETWORK_DIASPORA),
24 logger('diaspora_public: delivering to: ' . $rr['username']);
25 diaspora_dispatch($rr,$msg);
29 logger('diaspora_public: no subscribers');
34 function diaspora_dispatch($importer,$msg) {
38 $enabled = intval(get_config('system','diaspora_enabled'));
40 logger('mod-diaspora: disabled');
44 // php doesn't like dashes in variable names
46 $msg['message'] = str_replace(
47 array('<activity_streams-photo>','</activity_streams-photo>'),
48 array('<asphoto>','</asphoto>'),
52 $parsed_xml = parse_xml_string($msg['message'],false);
54 $xmlbase = $parsed_xml->post;
56 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
59 if($xmlbase->request) {
60 $ret = diaspora_request($importer,$xmlbase->request);
62 elseif($xmlbase->status_message) {
63 $ret = diaspora_post($importer,$xmlbase->status_message);
65 elseif($xmlbase->profile) {
66 $ret = diaspora_profile($importer,$xmlbase->profile);
68 elseif($xmlbase->comment) {
69 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
71 elseif($xmlbase->like) {
72 $ret = diaspora_like($importer,$xmlbase->like,$msg);
74 elseif($xmlbase->asphoto) {
75 $ret = diaspora_asphoto($importer,$xmlbase->asphoto);
77 elseif($xmlbase->reshare) {
78 $ret = diaspora_reshare($importer,$xmlbase->reshare);
80 elseif($xmlbase->retraction) {
81 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
83 elseif($xmlbase->signed_retraction) {
84 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
86 elseif($xmlbase->relayable_retraction) {
87 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
89 elseif($xmlbase->photo) {
90 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
92 elseif($xmlbase->conversation) {
93 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
95 elseif($xmlbase->message) {
96 $ret = diaspora_message($importer,$xmlbase->message,$msg);
99 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
104 function diaspora_get_contact_by_handle($uid,$handle) {
105 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
106 dbesc(NETWORK_DIASPORA),
115 function find_diaspora_person_by_handle($handle) {
117 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
118 dbesc(NETWORK_DIASPORA),
122 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
123 // update record occasionally so it doesn't get stale
124 $d = strtotime($r[0]['updated'] . ' +00:00');
125 if($d > strtotime('now - 14 days'))
129 logger('find_diaspora_person_by_handle: refresh',LOGGER_DEBUG);
130 require_once('include/Scrape.php');
131 $r = probe_url($handle, PROBE_DIASPORA);
132 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
133 add_fcontact($r,$update);
140 function get_diaspora_key($uri) {
141 logger('Fetching diaspora key for: ' . $uri);
143 $r = find_diaspora_person_by_handle($uri);
150 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
153 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
156 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
158 // $b64_data = base64_encode($msg);
159 // $b64url_data = base64url_encode($b64_data);
161 $b64url_data = base64url_encode($msg);
163 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
165 $type = 'application/xml';
166 $encoding = 'base64url';
169 $signable_data = $data . '.' . base64url_encode($type) . '.'
170 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
172 $signature = rsa_sign($signable_data,$prvkey);
173 $sig = base64url_encode($signature);
176 <?xml version='1.0' encoding='UTF-8'?>
177 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
179 <author_id>$handle</author_id>
182 <me:encoding>base64url</me:encoding>
183 <me:alg>RSA-SHA256</me:alg>
184 <me:data type="application/xml">$data</me:data>
185 <me:sig>$sig</me:sig>
190 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
198 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
202 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
204 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
206 // without a public key nothing will work
209 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
213 $inner_aes_key = random_string(32);
214 $b_inner_aes_key = base64_encode($inner_aes_key);
215 $inner_iv = random_string(16);
216 $b_inner_iv = base64_encode($inner_iv);
218 $outer_aes_key = random_string(32);
219 $b_outer_aes_key = base64_encode($outer_aes_key);
220 $outer_iv = random_string(16);
221 $b_outer_iv = base64_encode($outer_iv);
223 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
225 $padded_data = pkcs5_pad($msg,16);
226 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
228 $b64_data = base64_encode($inner_encrypted);
231 $b64url_data = base64url_encode($b64_data);
232 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
234 $type = 'application/xml';
235 $encoding = 'base64url';
238 $signable_data = $data . '.' . base64url_encode($type) . '.'
239 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
241 $signature = rsa_sign($signable_data,$prvkey);
242 $sig = base64url_encode($signature);
244 $decrypted_header = <<< EOT
247 <aes_key>$b_inner_aes_key</aes_key>
248 <author_id>$handle</author_id>
252 $decrypted_header = pkcs5_pad($decrypted_header,16);
254 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
256 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
258 $encrypted_outer_key_bundle = '';
259 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
261 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
263 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
265 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
266 'ciphertext' => base64_encode($ciphertext)));
267 $cipher_json = base64_encode($encrypted_header_json_object);
269 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
272 <?xml version='1.0' encoding='UTF-8'?>
273 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
276 <me:encoding>base64url</me:encoding>
277 <me:alg>RSA-SHA256</me:alg>
278 <me:data type="application/xml">$data</me:data>
279 <me:sig>$sig</me:sig>
284 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
291 * diaspora_decode($importer,$xml)
292 * array $importer -> from user table
293 * string $xml -> urldecoded Diaspora salmon
296 * 'message' -> decoded Diaspora XML message
297 * 'author' -> author diaspora handle
298 * 'key' -> author public key (converted to pkcs#8)
300 * Author and key are used elsewhere to save a lookup for verifying replies and likes
304 function diaspora_decode($importer,$xml) {
307 $basedom = parse_xml_string($xml);
309 $children = $basedom->children('https://joindiaspora.com/protocol');
311 if($children->header) {
313 $author_link = str_replace('acct:','',$children->header->author_id);
317 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
319 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
320 $ciphertext = base64_decode($encrypted_header->ciphertext);
322 $outer_key_bundle = '';
323 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
325 $j_outer_key_bundle = json_decode($outer_key_bundle);
327 $outer_iv = base64_decode($j_outer_key_bundle->iv);
328 $outer_key = base64_decode($j_outer_key_bundle->key);
330 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
333 $decrypted = pkcs5_unpad($decrypted);
336 * $decrypted now contains something like
339 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
340 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
345 * <name>Ryan Hughes</name>
346 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
351 * <author_id>galaxor@diaspora.priateship.org</author_id>
355 * </decrypted_header>
358 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
359 $idom = parse_xml_string($decrypted,false);
361 $inner_iv = base64_decode($idom->iv);
362 $inner_aes_key = base64_decode($idom->aes_key);
364 $author_link = str_replace('acct:','',$idom->author_id);
368 $dom = $basedom->children(NAMESPACE_SALMON_ME);
370 // figure out where in the DOM tree our data is hiding
372 if($dom->provenance->data)
373 $base = $dom->provenance;
374 elseif($dom->env->data)
380 logger('mod-diaspora: unable to locate salmon data in xml ');
381 http_status_exit(400);
385 // Stash the signature away for now. We have to find their key or it won't be good for anything.
386 $signature = base64url_decode($base->sig);
390 // strip whitespace so our data element will return to one big base64 blob
391 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
394 // stash away some other stuff for later
396 $type = $base->data[0]->attributes()->type[0];
397 $keyhash = $base->sig[0]->attributes()->keyhash[0];
398 $encoding = $base->encoding;
402 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
406 $data = base64url_decode($data);
410 $inner_decrypted = $data;
414 // Decode the encrypted blob
416 $inner_encrypted = base64_decode($data);
417 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
418 $inner_decrypted = pkcs5_unpad($inner_decrypted);
422 logger('mod-diaspora: Could not retrieve author URI.');
423 http_status_exit(400);
426 // Once we have the author URI, go to the web and try to find their public key
427 // (first this will look it up locally if it is in the fcontact cache)
428 // This will also convert diaspora public key from pkcs#1 to pkcs#8
430 logger('mod-diaspora: Fetching key for ' . $author_link );
431 $key = get_diaspora_key($author_link);
434 logger('mod-diaspora: Could not retrieve author key.');
435 http_status_exit(400);
438 $verify = rsa_verify($signed_data,$signature,$key);
441 logger('mod-diaspora: Message did not verify. Discarding.');
442 http_status_exit(400);
445 logger('mod-diaspora: Message verified.');
447 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
452 function diaspora_request($importer,$xml) {
456 $sender_handle = unxmlify($xml->sender_handle);
457 $recipient_handle = unxmlify($xml->recipient_handle);
459 if(! $sender_handle || ! $recipient_handle)
462 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
466 // perhaps we were already sharing with this person. Now they're sharing with us.
467 // That makes us friends.
469 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
470 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
471 intval(CONTACT_IS_FRIEND),
472 intval($contact['id']),
473 intval($importer['uid'])
478 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
479 intval($importer['uid'])
482 if((count($r)) && (! $r[0]['hide-friends']) && (! $contact['hidden'])) {
483 require_once('include/items.php');
485 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
486 intval($importer['uid'])
489 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
491 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
494 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
495 $arr['uid'] = $importer['uid'];
496 $arr['contact-id'] = $self[0]['id'];
498 $arr['type'] = 'wall';
501 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
502 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
503 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
504 $arr['verb'] = ACTIVITY_FRIEND;
505 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
507 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
508 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
509 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
510 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
512 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
513 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
514 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
515 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
516 $arr['object'] .= '</link></object>' . "\n";
517 $arr['last-child'] = 1;
519 $arr['allow_cid'] = $user[0]['allow_cid'];
520 $arr['allow_gid'] = $user[0]['allow_gid'];
521 $arr['deny_cid'] = $user[0]['deny_cid'];
522 $arr['deny_gid'] = $user[0]['deny_gid'];
524 $i = item_store($arr);
526 proc_run('php',"include/notifier.php","activity","$i");
535 $ret = find_diaspora_person_by_handle($sender_handle);
538 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
539 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
543 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
547 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
548 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
549 intval($importer['uid']),
550 dbesc($ret['network']),
554 dbesc(normalise_link($ret['url'])),
558 dbesc($ret['photo']),
559 dbesc($ret['pubkey']),
560 dbesc($ret['notify']),
566 // find the contact record we just created
568 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
570 if(! $contact_record) {
571 logger('diaspora_request: unable to locate newly created contact record.');
575 $g = q("select def_gid from user where uid = %d limit 1",
576 intval($importer['uid'])
578 if($g && intval($g[0]['def_gid'])) {
579 require_once('include/group.php');
580 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
583 if($importer['page-flags'] == PAGE_NORMAL) {
585 $hash = random_string() . (string) time(); // Generate a confirm_key
587 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
588 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
589 intval($importer['uid']),
590 intval($contact_record['id']),
593 dbesc( t('Sharing notification from Diaspora network')),
595 dbesc(datetime_convert())
600 // automatic friend approval
602 require_once('include/Photo.php');
604 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
606 // technically they are sharing with us (CONTACT_IS_SHARING),
607 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
608 // we are going to change the relationship and make them a follower.
610 if($importer['page-flags'] == PAGE_FREELOVE)
611 $new_relation = CONTACT_IS_FRIEND;
613 $new_relation = CONTACT_IS_FOLLOWER;
615 $r = q("UPDATE `contact` SET
622 `avatar-date` = '%s',
625 WHERE `id` = %d LIMIT 1
630 intval($new_relation),
631 dbesc(datetime_convert()),
632 dbesc(datetime_convert()),
633 dbesc(datetime_convert()),
634 intval($contact_record['id'])
637 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
639 $ret = diaspora_share($u[0],$contact_record);
645 function diaspora_post_allow($importer,$contact) {
646 if(($contact['blocked']) || ($contact['readonly']))
648 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
650 if($contact['rel'] == CONTACT_IS_FOLLOWER)
651 if($importer['page-flags'] == PAGE_COMMUNITY)
657 function diaspora_post($importer,$xml) {
660 $guid = notags(unxmlify($xml->guid));
661 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
663 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
667 if(! diaspora_post_allow($importer,$contact)) {
668 logger('diaspora_post: Ignoring this author.');
672 $message_id = $diaspora_handle . ':' . $guid;
673 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
674 intval($importer['uid']),
679 logger('diaspora_post: message exists: ' . $guid);
683 // allocate a guid on our system - we aren't fixing any collisions.
684 // we're ignoring them
686 $g = q("select * from guid where guid = '%s' limit 1",
690 q("insert into guid ( guid ) values ( '%s' )",
695 $created = unxmlify($xml->created_at);
696 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
698 $body = diaspora2bb($xml->raw_message);
704 $tags = get_tags($body);
707 foreach($tags as $tag) {
708 if(strpos($tag,'#') === 0) {
709 if(strpos($tag,'[url='))
712 // don't link tags that are already embedded in links
714 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
716 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
719 $basetag = str_replace('_',' ',substr($tag,1));
720 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
721 if(strlen($str_tags))
723 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
729 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
731 foreach($matches as $mtch) {
732 if(strlen($str_tags))
734 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
738 $datarray['uid'] = $importer['uid'];
739 $datarray['contact-id'] = $contact['id'];
740 $datarray['wall'] = 0;
741 $datarray['guid'] = $guid;
742 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
743 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
744 $datarray['private'] = $private;
745 $datarray['parent'] = 0;
746 $datarray['owner-name'] = $contact['name'];
747 $datarray['owner-link'] = $contact['url'];
748 $datarray['owner-avatar'] = $contact['thumb'];
749 $datarray['author-name'] = $contact['name'];
750 $datarray['author-link'] = $contact['url'];
751 $datarray['author-avatar'] = $contact['thumb'];
752 $datarray['body'] = $body;
753 $datarray['tag'] = $str_tags;
754 $datarray['app'] = 'Diaspora';
756 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
758 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
760 $message_id = item_store($datarray);
763 q("update item set plink = '%s' where id = %d limit 1",
764 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
773 function diaspora_reshare($importer,$xml) {
775 logger('diaspora_reshare: init: ' . print_r($xml,true));
778 $guid = notags(unxmlify($xml->guid));
779 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
782 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
786 if(! diaspora_post_allow($importer,$contact)) {
787 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
791 $message_id = $diaspora_handle . ':' . $guid;
792 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
793 intval($importer['uid']),
798 logger('diaspora_reshare: message exists: ' . $guid);
802 $orig_author = notags(unxmlify($xml->root_diaspora_id));
803 $orig_guid = notags(unxmlify($xml->root_guid));
805 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
806 $x = fetch_url($source_url);
808 $x = fetch_url(str_replace('https://','http://',$source_url));
810 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
813 logger('diaspora_reshare: source: ' . $x);
815 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
816 $source_xml = parse_xml_string($x,false);
818 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
819 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
820 $body = scale_external_images($body,false);
822 elseif($source_xml->post->asphoto->image_url) {
823 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
824 $body = scale_external_images($body);
826 elseif($source_xml->post->status_message) {
827 $body = diaspora2bb($source_xml->post->status_message->raw_message);
828 $body = scale_external_images($body);
832 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
836 logger('diaspora_reshare: empty body: source= ' . $x);
840 $person = find_diaspora_person_by_handle($orig_author);
842 if(is_array($person) && x($person,'name') && x($person,'url'))
843 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
845 $details = $orig_author;
847 $prefix = '♲ ' . $details . "\n";
850 // allocate a guid on our system - we aren't fixing any collisions.
851 // we're ignoring them
853 $g = q("select * from guid where guid = '%s' limit 1",
857 q("insert into guid ( guid ) values ( '%s' )",
862 $created = unxmlify($xml->created_at);
863 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
869 $tags = get_tags($body);
872 foreach($tags as $tag) {
873 if(strpos($tag,'#') === 0) {
874 if(strpos($tag,'[url='))
877 // don't link tags that are already embedded in links
879 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
881 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
885 $basetag = str_replace('_',' ',substr($tag,1));
886 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
887 if(strlen($str_tags))
889 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
895 $datarray['uid'] = $importer['uid'];
896 $datarray['contact-id'] = $contact['id'];
897 $datarray['wall'] = 0;
898 $datarray['guid'] = $guid;
899 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
900 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
901 $datarray['private'] = $private;
902 $datarray['parent'] = 0;
903 $datarray['owner-name'] = $contact['name'];
904 $datarray['owner-link'] = $contact['url'];
905 $datarray['owner-avatar'] = $contact['thumb'];
906 $datarray['author-name'] = $contact['name'];
907 $datarray['author-link'] = $contact['url'];
908 $datarray['author-avatar'] = $contact['thumb'];
909 $datarray['body'] = $prefix . $body;
910 $datarray['tag'] = $str_tags;
911 $datarray['app'] = 'Diaspora';
913 $message_id = item_store($datarray);
916 q("update item set plink = '%s' where id = %d limit 1",
917 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
927 function diaspora_asphoto($importer,$xml) {
928 logger('diaspora_asphoto called');
931 $guid = notags(unxmlify($xml->guid));
932 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
934 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
938 if(! diaspora_post_allow($importer,$contact)) {
939 logger('diaspora_asphoto: Ignoring this author.');
943 $message_id = $diaspora_handle . ':' . $guid;
944 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
945 intval($importer['uid']),
950 logger('diaspora_asphoto: message exists: ' . $guid);
954 // allocate a guid on our system - we aren't fixing any collisions.
955 // we're ignoring them
957 $g = q("select * from guid where guid = '%s' limit 1",
961 q("insert into guid ( guid ) values ( '%s' )",
966 $created = unxmlify($xml->created_at);
967 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
969 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
970 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
971 $body = scale_external_images($body,false);
973 elseif($xml->image_url) {
974 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
975 $body = scale_external_images($body);
978 logger('diaspora_asphoto: no photo url found.');
985 $datarray['uid'] = $importer['uid'];
986 $datarray['contact-id'] = $contact['id'];
987 $datarray['wall'] = 0;
988 $datarray['guid'] = $guid;
989 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
990 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
991 $datarray['private'] = $private;
992 $datarray['parent'] = 0;
993 $datarray['owner-name'] = $contact['name'];
994 $datarray['owner-link'] = $contact['url'];
995 $datarray['owner-avatar'] = $contact['thumb'];
996 $datarray['author-name'] = $contact['name'];
997 $datarray['author-link'] = $contact['url'];
998 $datarray['author-avatar'] = $contact['thumb'];
999 $datarray['body'] = $body;
1001 $datarray['app'] = 'Diaspora/Cubbi.es';
1003 $message_id = item_store($datarray);
1006 q("update item set plink = '%s' where id = %d limit 1",
1007 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1021 function diaspora_comment($importer,$xml,$msg) {
1024 $guid = notags(unxmlify($xml->guid));
1025 $parent_guid = notags(unxmlify($xml->parent_guid));
1026 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1027 $target_type = notags(unxmlify($xml->target_type));
1028 $text = unxmlify($xml->text);
1029 $author_signature = notags(unxmlify($xml->author_signature));
1031 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1033 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1035 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1039 if(! diaspora_post_allow($importer,$contact)) {
1040 logger('diaspora_comment: Ignoring this author.');
1044 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1045 intval($importer['uid']),
1049 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1053 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1054 intval($importer['uid']),
1058 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1061 $parent_item = $r[0];
1064 /* How Diaspora performs comment signature checking:
1066 - If an item has been sent by the comment author to the top-level post owner to relay on
1067 to the rest of the contacts on the top-level post, the top-level post owner should check
1068 the author_signature, then create a parent_author_signature before relaying the comment on
1069 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1070 check only the parent_author_signature. Basically, they trust that the top-level post
1071 owner has already verified the authenticity of anything he/she sends out
1072 - In either case, the signature that get checked is the signature created by the person
1076 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1079 if($parent_author_signature) {
1080 // If a parent_author_signature exists, then we've received the comment
1081 // relayed from the top-level post owner. There's no need to check the
1082 // author_signature if the parent_author_signature is valid
1084 $parent_author_signature = base64_decode($parent_author_signature);
1086 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1087 logger('diaspora_comment: top-level owner verification failed.');
1092 // If there's no parent_author_signature, then we've received the comment
1093 // from the comment creator. In that case, the person is commenting on
1094 // our post, so he/she must be a contact of ours and his/her public key
1095 // should be in $msg['key']
1097 /* if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1102 $person = find_diaspora_person_by_handle($diaspora_handle);
1104 if(is_array($person) && x($person,'pubkey'))
1105 $key = $person['pubkey'];
1107 logger('diaspora_comment: unable to find author details');
1112 $author_signature = base64_decode($author_signature);
1114 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1115 logger('diaspora_comment: comment author verification failed.');
1120 // Phew! Everything checks out. Now create an item.
1122 // Find the original comment author information
1123 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1126 $person = find_diaspora_person_by_handle($diaspora_handle);
1128 if(! is_array($person)) {
1129 logger('diaspora_comment: unable to find author details');
1134 $body = diaspora2bb($text);
1136 $message_id = $diaspora_handle . ':' . $guid;
1138 $datarray = array();
1142 $tags = get_tags($body);
1145 foreach($tags as $tag) {
1146 if(strpos($tag,'#') === 0) {
1147 if(strpos($tag,'[url='))
1150 // don't link tags that are already embedded in links
1152 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1154 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1158 $basetag = str_replace('_',' ',substr($tag,1));
1159 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1160 if(strlen($str_tags))
1162 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1168 $datarray['uid'] = $importer['uid'];
1169 $datarray['contact-id'] = $contact['id'];
1170 $datarray['wall'] = $parent_item['wall'];
1171 $datarray['gravity'] = GRAVITY_COMMENT;
1172 $datarray['guid'] = $guid;
1173 $datarray['uri'] = $message_id;
1174 $datarray['parent-uri'] = $parent_item['uri'];
1176 // No timestamps for comments? OK, we'll the use current time.
1177 $datarray['created'] = $datarray['edited'] = datetime_convert();
1178 $datarray['private'] = $parent_item['private'];
1180 $datarray['owner-name'] = $parent_item['owner-name'];
1181 $datarray['owner-link'] = $parent_item['owner-link'];
1182 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1184 $datarray['author-name'] = $person['name'];
1185 $datarray['author-link'] = $person['url'];
1186 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1187 $datarray['body'] = $body;
1188 $datarray['tag'] = $str_tags;
1190 // We can't be certain what the original app is if the message is relayed.
1191 if(($parent_item['origin']) && (! $parent_author_signature))
1192 $datarray['app'] = 'Diaspora';
1194 $message_id = item_store($datarray);
1197 q("update item set plink = '%s' where id = %d limit 1",
1198 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1203 if(($parent_item['origin']) && (! $parent_author_signature)) {
1204 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1205 intval($message_id),
1206 dbesc($author_signed_data),
1207 dbesc(base64_encode($author_signature)),
1208 dbesc($diaspora_handle)
1211 // if the message isn't already being relayed, notify others
1212 // the existence of parent_author_signature means the parent_author or owner
1213 // is already relaying.
1215 proc_run('php','include/notifier.php','comment',$message_id);
1218 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1219 dbesc($parent_item['uri']),
1220 intval($importer['uid'])
1223 if(count($myconv)) {
1224 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1226 foreach($myconv as $conv) {
1228 // now if we find a match, it means we're in this conversation
1230 if(! link_compare($conv['author-link'],$importer_url))
1233 require_once('include/enotify.php');
1235 $conv_parent = $conv['parent'];
1238 'type' => NOTIFY_COMMENT,
1239 'notify_flags' => $importer['notify-flags'],
1240 'language' => $importer['language'],
1241 'to_name' => $importer['username'],
1242 'to_email' => $importer['email'],
1243 'uid' => $importer['uid'],
1244 'item' => $datarray,
1245 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id,
1246 'source_name' => $datarray['author-name'],
1247 'source_link' => $datarray['author-link'],
1248 'source_photo' => $datarray['author-avatar'],
1249 'verb' => ACTIVITY_POST,
1251 'parent' => $conv_parent,
1255 // only send one notification
1265 function diaspora_conversation($importer,$xml,$msg) {
1269 $guid = notags(unxmlify($xml->guid));
1270 $subject = notags(unxmlify($xml->subject));
1271 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1272 $participant_handles = notags(unxmlify($xml->participant_handles));
1273 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1275 $parent_uri = $diaspora_handle . ':' . $guid;
1277 $messages = $xml->message;
1279 if(! count($messages)) {
1280 logger('diaspora_conversation: empty conversation');
1284 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1286 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1290 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1291 logger('diaspora_conversation: Ignoring this author.');
1295 $conversation = null;
1297 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1298 intval($importer['uid']),
1302 $conversation = $c[0];
1304 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1305 intval($importer['uid']),
1307 dbesc($diaspora_handle),
1308 dbesc(datetime_convert('UTC','UTC',$created_at)),
1309 dbesc(datetime_convert()),
1311 dbesc($participant_handles)
1314 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1315 intval($importer['uid']),
1319 $conversation = $c[0];
1321 if(! $conversation) {
1322 logger('diaspora_conversation: unable to create conversation.');
1326 foreach($messages as $mesg) {
1330 $msg_guid = notags(unxmlify($mesg->guid));
1331 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1332 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1333 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1334 $msg_text = unxmlify($mesg->text);
1335 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1336 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1337 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1338 if($msg_conversation_guid != $guid) {
1339 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1343 $body = diaspora2bb($msg_text);
1344 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1346 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1348 $author_signature = base64_decode($msg_author_signature);
1350 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1355 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1357 if(is_array($person) && x($person,'pubkey'))
1358 $key = $person['pubkey'];
1360 logger('diaspora_conversation: unable to find author details');
1365 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1366 logger('diaspora_conversation: verification failed.');
1370 if($msg_parent_author_signature) {
1371 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1373 $parent_author_signature = base64_decode($msg_parent_author_signature);
1377 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1378 logger('diaspora_conversation: owner verification failed.');
1383 $r = q("select id from mail where `uri` = '%s' limit 1",
1387 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1391 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')",
1392 intval($importer['uid']),
1394 intval($conversation['id']),
1395 dbesc($person['name']),
1396 dbesc($person['photo']),
1397 dbesc($person['url']),
1398 intval($contact['id']),
1405 dbesc($msg_created_at)
1408 q("update conv set updated = '%s' where id = %d limit 1",
1409 dbesc(datetime_convert()),
1410 intval($conversation['id'])
1413 require_once('include/enotify.php');
1415 'type' => NOTIFY_MAIL,
1416 'notify_flags' => $importer['notify-flags'],
1417 'language' => $importer['language'],
1418 'to_name' => $importer['username'],
1419 'to_email' => $importer['email'],
1420 'uid' =>$importer['importer_uid'],
1421 'item' => array('subject' => $subject, 'body' => $body),
1422 'source_name' => $person['name'],
1423 'source_link' => $person['url'],
1424 'source_photo' => $person['thumb'],
1425 'verb' => ACTIVITY_POST,
1433 function diaspora_message($importer,$xml,$msg) {
1437 $msg_guid = notags(unxmlify($xml->guid));
1438 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1439 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1440 $msg_author_signature = notags(unxmlify($xml->author_signature));
1441 $msg_text = unxmlify($xml->text);
1442 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1443 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1444 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1446 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1448 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1450 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1454 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1455 logger('diaspora_message: Ignoring this author.');
1459 $conversation = null;
1461 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1462 intval($importer['uid']),
1463 dbesc($msg_conversation_guid)
1466 $conversation = $c[0];
1468 logger('diaspora_message: conversation not available.');
1474 $body = diaspora2bb($msg_text);
1475 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1477 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1480 $author_signature = base64_decode($msg_author_signature);
1482 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1483 if(is_array($person) && x($person,'pubkey'))
1484 $key = $person['pubkey'];
1486 logger('diaspora_message: unable to find author details');
1490 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1491 logger('diaspora_message: verification failed.');
1495 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1497 intval($importer['uid'])
1500 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1504 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')",
1505 intval($importer['uid']),
1507 intval($conversation['id']),
1508 dbesc($person['name']),
1509 dbesc($person['photo']),
1510 dbesc($person['url']),
1511 intval($contact['id']),
1512 dbesc($conversation['subject']),
1518 dbesc($msg_created_at)
1521 q("update conv set updated = '%s' where id = %d limit 1",
1522 dbesc(datetime_convert()),
1523 intval($conversation['id'])
1530 function diaspora_photo($importer,$xml,$msg) {
1534 logger('diaspora_photo: init',LOGGER_DEBUG);
1536 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1538 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1540 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1542 $guid = notags(unxmlify($xml->guid));
1544 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1546 $public = notags(unxmlify($xml->public));
1548 $created_at = notags(unxmlify($xml_created_at));
1550 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1552 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1554 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1558 if(! diaspora_post_allow($importer,$contact)) {
1559 logger('diaspora_photo: Ignoring this author.');
1563 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1564 intval($importer['uid']),
1565 dbesc($status_message_guid)
1568 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1572 $parent_item = $r[0];
1574 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1576 $link_text = scale_external_images($link_text);
1578 if(strpos($parent_item['body'],$link_text) === false) {
1579 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1580 dbesc($link_text . $parent_item['body']),
1581 intval($parent_item['id']),
1582 intval($parent_item['uid'])
1592 function diaspora_like($importer,$xml,$msg) {
1595 $guid = notags(unxmlify($xml->guid));
1596 $parent_guid = notags(unxmlify($xml->parent_guid));
1597 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1598 $target_type = notags(unxmlify($xml->target_type));
1599 $positive = notags(unxmlify($xml->positive));
1600 $author_signature = notags(unxmlify($xml->author_signature));
1602 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1604 // likes on comments not supported here and likes on photos not supported by Diaspora
1606 if($target_type !== 'Post')
1609 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1611 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1615 if(! diaspora_post_allow($importer,$contact)) {
1616 logger('diaspora_like: Ignoring this author.');
1620 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1621 intval($importer['uid']),
1625 logger('diaspora_like: parent item not found: ' . $guid);
1629 $parent_item = $r[0];
1631 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1632 intval($importer['uid']),
1636 if($positive === 'true') {
1637 logger('diaspora_like: duplicate like: ' . $guid);
1640 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1641 // It looks like "RelayableRetractions" are used for "unlike" instead
1642 if($positive === 'false') {
1643 logger('diaspora_like: received a like with positive set to "false"...ignoring');
1644 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1645 intval($r[0]['id']),
1646 intval($importer['uid'])
1648 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1649 // send notification via proc_run()
1653 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1654 // It looks like "RelayableRetractions" are used for "unlike" instead
1655 if($positive === 'false') {
1656 logger('diaspora_like: received a like with positive set to "false"');
1657 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1662 /* How Diaspora performs "like" signature checking:
1664 - If an item has been sent by the like author to the top-level post owner to relay on
1665 to the rest of the contacts on the top-level post, the top-level post owner should check
1666 the author_signature, then create a parent_author_signature before relaying the like on
1667 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1668 check only the parent_author_signature. Basically, they trust that the top-level post
1669 owner has already verified the authenticity of anything he/she sends out
1670 - In either case, the signature that get checked is the signature created by the person
1674 $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1677 if($parent_author_signature) {
1678 // If a parent_author_signature exists, then we've received the like
1679 // relayed from the top-level post owner. There's no need to check the
1680 // author_signature if the parent_author_signature is valid
1682 $parent_author_signature = base64_decode($parent_author_signature);
1684 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1685 logger('diaspora_like: top-level owner verification failed.');
1690 // If there's no parent_author_signature, then we've received the like
1691 // from the like creator. In that case, the person is "like"ing
1692 // our post, so he/she must be a contact of ours and his/her public key
1693 // should be in $msg['key']
1695 /* if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1700 $person = find_diaspora_person_by_handle($diaspora_handle);
1701 if(is_array($person) && x($person,'pubkey'))
1702 $key = $person['pubkey'];
1704 logger('diaspora_like: unable to find author details');
1709 $author_signature = base64_decode($author_signature);
1711 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1712 logger('diaspora_like: like creator verification failed.');
1717 // Phew! Everything checks out. Now create an item.
1719 // Find the original like author information
1720 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1723 $person = find_diaspora_person_by_handle($diaspora_handle);
1725 if(! is_array($person)) {
1726 logger('diaspora_like: unable to find author details');
1731 $uri = $diaspora_handle . ':' . $guid;
1733 $activity = ACTIVITY_LIKE;
1734 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1735 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1736 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1737 $body = $parent_item['body'];
1742 <type>$objtype</type>
1744 <id>{$parent_item['uri']}</id>
1747 <content>$body</content>
1750 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1755 $arr['uid'] = $importer['uid'];
1756 $arr['guid'] = $guid;
1757 $arr['contact-id'] = $contact['id'];
1758 $arr['type'] = 'activity';
1759 $arr['wall'] = $parent_item['wall'];
1760 $arr['gravity'] = GRAVITY_LIKE;
1761 $arr['parent'] = $parent_item['id'];
1762 $arr['parent-uri'] = $parent_item['uri'];
1764 $arr['owner-name'] = $parent_item['name'];
1765 $arr['owner-link'] = $parent_item['url'];
1766 $arr['owner-avatar'] = $parent_item['thumb'];
1768 $arr['author-name'] = $person['name'];
1769 $arr['author-link'] = $person['url'];
1770 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1772 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1773 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1774 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1775 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1777 $arr['app'] = 'Diaspora';
1779 $arr['private'] = $parent_item['private'];
1780 $arr['verb'] = $activity;
1781 $arr['object-type'] = $objtype;
1782 $arr['object'] = $obj;
1783 $arr['visible'] = 1;
1785 $arr['last-child'] = 0;
1787 $message_id = item_store($arr);
1791 q("update item set plink = '%s' where id = %d limit 1",
1792 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1797 if(! $parent_author_signature) {
1798 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1799 intval($message_id),
1800 dbesc($author_signed_data),
1801 dbesc(base64_encode($author_signature)),
1802 dbesc($diaspora_handle)
1806 // if the message isn't already being relayed, notify others
1807 // the existence of parent_author_signature means the parent_author or owner
1808 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1810 if(($parent_item['origin']) && (! $parent_author_signature))
1811 proc_run('php','include/notifier.php','comment',$message_id);
1816 function diaspora_retraction($importer,$xml) {
1819 $guid = notags(unxmlify($xml->guid));
1820 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1821 $type = notags(unxmlify($xml->type));
1823 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1827 if($type === 'Person') {
1828 require_once('include/Contact.php');
1829 contact_remove($contact['id']);
1831 elseif($type === 'Post') {
1832 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1834 intval($importer['uid'])
1837 if(link_compare($r[0]['author-link'],$contact['url'])) {
1838 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1839 dbesc(datetime_convert()),
1850 function diaspora_signed_retraction($importer,$xml,$msg) {
1853 $guid = notags(unxmlify($xml->target_guid));
1854 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1855 $type = notags(unxmlify($xml->target_type));
1856 $sig = notags(unxmlify($xml->target_author_signature));
1858 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1860 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1862 logger('diaspora_signed_retraction: no contact');
1867 $signed_data = $guid . ';' . $type ;
1870 /* How Diaspora performs relayable_retraction signature checking:
1872 - If an item has been sent by the item author to the top-level post owner to relay on
1873 to the rest of the contacts on the top-level post, the top-level post owner checks
1874 the author_signature, then creates a parent_author_signature before relaying the item on
1875 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1876 check only the parent_author_signature. Basically, they trust that the top-level post
1877 owner has already verified the authenticity of anything he/she sends out
1878 - In either case, the signature that get checked is the signature created by the person
1882 if($parent_author_signature) {
1884 $parent_author_signature = base64_decode($parent_author_signature);
1886 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1887 logger('diaspora_signed_retraction: top-level post owner verification failed');
1894 /* if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1899 $person = find_diaspora_person_by_handle($diaspora_handle);
1901 if(is_array($person) && x($person,'pubkey'))
1902 $key = $person['pubkey'];
1904 logger('diaspora_signed_retraction: unable to find author details');
1909 $sig_decode = base64_decode($sig);
1911 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
1912 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
1917 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
1918 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1920 intval($importer['uid'])
1923 if(link_compare($r[0]['author-link'],$contact['url'])) {
1924 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d limit 1",
1925 dbesc(datetime_convert()),
1926 dbesc(datetime_convert()),
1930 // Now check if the retraction needs to be relayed by us
1932 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
1933 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
1934 // The only item with `parent` and `id` as the parent id is the parent item.
1935 $p = q("select origin from item where parent = %d and id = %d limit 1",
1940 if(($p[0]['origin']) && (! $parent_author_signature)) {
1941 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1943 dbesc($signed_data),
1945 dbesc($diaspora_handle)
1948 // the existence of parent_author_signature would have meant the parent_author or owner
1949 // is already relaying.
1950 logger('diaspora_signed_retraction: relaying relayable_retraction');
1952 proc_run('php','include/notifier.php','relayable_retraction',$r[0]['id']);
1959 logger('diaspora_signed_retraction: unknown type: ' . $type);
1965 function diaspora_profile($importer,$xml) {
1968 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1970 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1974 if($contact['blocked']) {
1975 logger('diaspora_post: Ignoring this author.');
1979 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1980 $image_url = unxmlify($xml->image_url);
1981 $birthday = unxmlify($xml->birthday);
1983 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1984 intval($importer['uid']),
1985 intval($contact['id'])
1987 $oldphotos = ((count($r)) ? $r : null);
1989 require_once('include/Photo.php');
1991 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1993 // Generic birthday. We don't know the timezone. The year is irrelevant.
1995 $birthday = str_replace('1000','1901',$birthday);
1997 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1999 // this is to prevent multiple birthday notifications in a single year
2000 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2002 if(substr($birthday,5) === substr($contact['bd'],5))
2003 $birthday = $contact['bd'];
2005 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2006 // Not doing this currently because D* protocol is scheduled for revision soon.
2008 $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",
2010 dbesc(datetime_convert()),
2014 dbesc(datetime_convert()),
2016 intval($contact['id']),
2017 intval($importer['uid'])
2022 foreach($oldphotos as $ph) {
2023 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2024 intval($importer['uid']),
2025 intval($contact['id']),
2026 dbesc($ph['resource-id'])
2036 function diaspora_share($me,$contact) {
2038 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2039 $theiraddr = $contact['addr'];
2041 $tpl = get_markup_template('diaspora_share.tpl');
2042 $msg = replace_macros($tpl, array(
2043 '$sender' => $myaddr,
2044 '$recipient' => $theiraddr
2047 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2049 return(diaspora_transmit($owner,$contact,$slap, false));
2052 function diaspora_unshare($me,$contact) {
2055 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2057 $tpl = get_markup_template('diaspora_retract.tpl');
2058 $msg = replace_macros($tpl, array(
2059 '$guid' => $me['guid'],
2060 '$type' => 'Person',
2061 '$handle' => $myaddr
2064 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2066 return(diaspora_transmit($owner,$contact,$slap, false));
2072 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2075 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2076 $theiraddr = $contact['addr'];
2080 $title = $item['title'];
2081 $body = $item['body'];
2084 // We're trying to match Diaspora's split message/photo protocol but
2085 // all the photos are displayed on D* as links and not img's - even
2086 // though we're sending pretty much precisely what they send us when
2087 // doing the same operation.
2088 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2089 // which seems to get through intact.
2091 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2093 foreach($matches as $mtch) {
2095 $detail['str'] = $mtch[0];
2096 $detail['path'] = dirname($mtch[1]) . '/';
2097 $detail['file'] = basename($mtch[1]);
2098 $detail['guid'] = $item['guid'];
2099 $detail['handle'] = $myaddr;
2100 $images[] = $detail;
2101 $body = str_replace($detail['str'],$mtch[1],$body);
2105 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2108 $body = xmlify('**' . html_entity_decode($title) . '**' . "\n") . $body;
2111 if($item['attach']) {
2112 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2114 $body .= "\n" . t('Attachments:') . "\n";
2115 foreach($matches as $mtch) {
2116 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2122 $public = (($item['private']) ? 'false' : 'true');
2124 require_once('include/datetime.php');
2125 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2127 $tpl = get_markup_template('diaspora_post.tpl');
2128 $msg = replace_macros($tpl, array(
2130 '$guid' => $item['guid'],
2131 '$handle' => xmlify($myaddr),
2132 '$public' => $public,
2133 '$created' => $created
2136 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
2138 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2140 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2142 if(count($images)) {
2143 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2146 return $return_code;
2150 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2152 if(! count($images))
2154 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2156 $tpl = get_markup_template('diaspora_photo.tpl');
2157 foreach($images as $image) {
2158 if(! stristr($image['path'],$mysite))
2160 $resource = str_replace('.jpg','',$image['file']);
2161 $resource = substr($resource,0,strpos($resource,'-'));
2163 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2165 intval($owner['uid'])
2169 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2170 $msg = replace_macros($tpl,array(
2171 '$path' => xmlify($image['path']),
2172 '$filename' => xmlify($image['file']),
2173 '$msg_guid' => xmlify($image['guid']),
2174 '$guid' => xmlify($r[0]['guid']),
2175 '$handle' => xmlify($image['handle']),
2176 '$public' => xmlify($public),
2177 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2181 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2182 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2184 diaspora_transmit($owner,$contact,$slap,$public_batch);
2189 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2192 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2193 $theiraddr = $contact['addr'];
2195 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2196 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2197 // The only item with `parent` and `id` as the parent id is the parent item.
2198 $p = q("select guid from item where parent = %d and id = %d limit 1",
2199 intval($item['parent']),
2200 intval($item['parent'])
2203 $parent_guid = $p[0]['guid'];
2207 if($item['verb'] === ACTIVITY_LIKE) {
2208 $tpl = get_markup_template('diaspora_like.tpl');
2210 $target_type = 'Post';
2211 // $positive = (($item['deleted']) ? 'false' : 'true');
2214 if(($item['deleted']))
2215 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2218 $tpl = get_markup_template('diaspora_comment.tpl');
2222 $text = html_entity_decode(bb2diaspora($item['body']));
2227 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
2229 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
2231 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2233 $msg = replace_macros($tpl,array(
2234 '$guid' => xmlify($item['guid']),
2235 '$parent_guid' => xmlify($parent_guid),
2236 '$target_type' =>xmlify($target_type),
2237 '$authorsig' => xmlify($authorsig),
2238 '$body' => xmlify($text),
2239 '$positive' => xmlify($positive),
2240 '$handle' => xmlify($myaddr)
2243 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2245 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2247 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2251 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2255 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2256 $theiraddr = $contact['addr'];
2259 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2260 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2261 // The only item with `parent` and `id` as the parent id is the parent item.
2262 $p = q("select guid from item where parent = %d and id = %d limit 1",
2263 intval($item['parent']),
2264 intval($item['parent'])
2267 $parent_guid = $p[0]['guid'];
2272 $relay_retract = false;
2273 $sql_sign_id = 'iid';
2274 if( $item['deleted']) {
2275 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2276 $relay_retract = true;
2277 $sql_sign_id = 'retract_iid';
2278 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2280 elseif($item['verb'] === ACTIVITY_LIKE) {
2281 $tpl = get_markup_template('diaspora_like_relay.tpl');
2283 $target_type = 'Post';
2284 // $positive = (($item['deleted']) ? 'false' : 'true');
2288 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2291 $body = $item['body'];
2293 $text = html_entity_decode(bb2diaspora($body));
2296 // fetch the original signature if the relayable was created by a Diaspora
2297 // or DFRN user. Relayables for other networks are not supported.
2299 $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2304 $signed_text = $orig_sign['signed_text'];
2305 $authorsig = $orig_sign['signature'];
2306 $handle = $orig_sign['signer'];
2310 // Author signature information (for likes, comments, and retractions of likes or comments,
2311 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2312 // function is called
2313 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2316 $itemcontact = q("select * from contact where `id` = %d limit 1",
2317 intval($item['contact-id'])
2319 if(count($itemcontact)) {
2320 if(! $itemcontact[0]['self']) {
2321 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
2322 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
2323 network_to_name($itemcontact['network'])) . "\n";
2324 // "$body" was assigned to "$text" above. It isn't used after that, so I don't think
2325 // the following change will do anything
2326 $body = $prefix . $body;
2328 // I think this comment will fail upon reaching Diaspora, because "$signed_text" is not defined
2332 // I'm confused about this "else." Since it sets "$handle = $myaddr," it seems like it should be for the case
2333 // where the top-level post owner commented on his own post, i.e. "$itemcontact[0]['self']" is true. But it's
2334 // positioned to be for the case where "count($itemcontact)" is 0.
2339 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $handle;
2340 elseif($relay_retract)
2341 $signed_text = $item['guid'] . ';' . $target_type;
2343 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $handle;
2345 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2347 q("insert into sign (`" . $sql_sign_id . "`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2348 intval($item['id']),
2349 dbesc($signed_text),
2357 // sign it with the top-level owner's signature
2359 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2361 $msg = replace_macros($tpl,array(
2362 '$guid' => xmlify($item['guid']),
2363 '$parent_guid' => xmlify($parent_guid),
2364 '$target_type' =>xmlify($target_type),
2365 '$authorsig' => xmlify($authorsig),
2366 '$parentsig' => xmlify($parentauthorsig),
2367 '$body' => xmlify($text),
2368 '$positive' => xmlify($positive),
2369 '$handle' => xmlify($handle)
2372 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2375 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2377 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2383 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2386 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2388 // Check whether the retraction is for a top-level post or whether it's a relayable
2389 if( $item['uri'] !== $item['parent-uri'] ) {
2391 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2392 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2396 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2397 $target_type = 'StatusMessage';
2400 $signed_text = $item['guid'] . ';' . $target_type;
2402 $msg = replace_macros($tpl, array(
2403 '$guid' => xmlify($item['guid']),
2404 '$type' => xmlify($target_type),
2405 '$handle' => xmlify($myaddr),
2406 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2409 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2411 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2414 function diaspora_send_mail($item,$owner,$contact) {
2417 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2419 $r = q("select * from conv where id = %d and uid = %d limit 1",
2420 intval($item['convid']),
2421 intval($item['uid'])
2425 logger('diaspora_send_mail: conversation not found.');
2431 'guid' => xmlify($cnv['guid']),
2432 'subject' => xmlify($cnv['subject']),
2433 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2434 'diaspora_handle' => xmlify($cnv['creator']),
2435 'participant_handles' => xmlify($cnv['recips'])
2438 $body = bb2diaspora($item['body']);
2439 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2441 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2442 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2444 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2447 'guid' => xmlify($item['guid']),
2448 'parent_guid' => xmlify($cnv['guid']),
2449 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2450 'author_signature' => xmlify($sig),
2451 'text' => xmlify($body),
2452 'created_at' => xmlify($created),
2453 'diaspora_handle' => xmlify($myaddr),
2454 'conversation_guid' => xmlify($cnv['guid'])
2457 if($item['reply']) {
2458 $tpl = get_markup_template('diaspora_message.tpl');
2459 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2462 $conv['messages'] = array($msg);
2463 $tpl = get_markup_template('diaspora_conversation.tpl');
2464 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2467 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2469 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2471 return(diaspora_transmit($owner,$contact,$slap,false));
2476 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
2478 $enabled = intval(get_config('system','diaspora_enabled'));
2484 $logid = random_string(4);
2485 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2487 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2491 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2493 if(was_recently_delayed($contact['id'])) {
2497 if(! intval(get_config('system','diaspora_test'))) {
2498 post_url($dest_url . '/', $slap);
2499 $return_code = $a->get_curl_code();
2502 logger('diaspora_transmit: test_mode');
2507 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2509 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2510 logger('diaspora_transmit: queue message');
2512 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2513 intval($contact['id']),
2514 dbesc(NETWORK_DIASPORA),
2516 intval($public_batch)
2519 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2522 // queue message for redelivery
2523 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2528 return(($return_code) ? $return_code : (-1));