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) {
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 id = %d limit 1",intval($importer['uid']));
616 $ret = diaspora_share($u[0],$contact_record);
622 function diaspora_post($importer,$xml) {
625 $guid = notags(unxmlify($xml->guid));
626 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
628 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
632 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
633 logger('diaspora_post: Ignoring this author.');
637 $message_id = $diaspora_handle . ':' . $guid;
638 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
639 intval($importer['uid']),
644 logger('diaspora_post: message exists: ' . $guid);
648 // allocate a guid on our system - we aren't fixing any collisions.
649 // we're ignoring them
651 $g = q("select * from guid where guid = '%s' limit 1",
655 q("insert into guid ( guid ) values ( '%s' )",
660 $created = unxmlify($xml->created_at);
661 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
663 $body = diaspora2bb($xml->raw_message);
669 $tags = get_tags($body);
672 foreach($tags as $tag) {
673 if(strpos($tag,'#') === 0) {
674 if(strpos($tag,'[url='))
677 // don't link tags that are already embedded in links
679 if(preg_match('/\[(.*?)' . preg_quote($tag) . '(.*?)\]/',$body))
681 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag) . '(.*?)\)/',$body))
684 $basetag = str_replace('_',' ',substr($tag,1));
685 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
686 if(strlen($str_tags))
688 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
694 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
696 foreach($matches as $mtch) {
697 if(strlen($str_tags))
699 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
703 $datarray['uid'] = $importer['uid'];
704 $datarray['contact-id'] = $contact['id'];
705 $datarray['wall'] = 0;
706 $datarray['guid'] = $guid;
707 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
708 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
709 $datarray['private'] = $private;
710 $datarray['parent'] = 0;
711 $datarray['owner-name'] = $contact['name'];
712 $datarray['owner-link'] = $contact['url'];
713 $datarray['owner-avatar'] = $contact['thumb'];
714 $datarray['author-name'] = $contact['name'];
715 $datarray['author-link'] = $contact['url'];
716 $datarray['author-avatar'] = $contact['thumb'];
717 $datarray['body'] = $body;
718 $datarray['tag'] = $str_tags;
719 $datarray['app'] = 'Diaspora';
721 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
723 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
725 $message_id = item_store($datarray);
728 q("update item set plink = '%s' where id = %d limit 1",
729 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
738 function diaspora_reshare($importer,$xml) {
740 logger('diaspora_reshare: init: ' . print_r($xml,true));
743 $guid = notags(unxmlify($xml->guid));
744 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
747 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
751 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
752 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
756 $message_id = $diaspora_handle . ':' . $guid;
757 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
758 intval($importer['uid']),
763 logger('diaspora_reshare: message exists: ' . $guid);
767 $orig_author = notags(unxmlify($xml->root_diaspora_id));
768 $orig_guid = notags(unxmlify($xml->root_guid));
770 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
771 $x = fetch_url($source_url);
773 $x = fetch_url(str_replace('https://','http://',$source_url));
775 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
778 logger('diaspora_reshare: source: ' . $x);
780 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
781 $source_xml = parse_xml_string($x,false);
783 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
784 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
785 $body = scale_diaspora_images($body,false);
787 elseif($source_xml->post->asphoto->image_url) {
788 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
789 $body = scale_diaspora_images($body);
791 elseif($source_xml->post->status_message) {
792 $body = diaspora2bb($source_xml->post->status_message->raw_message);
793 $body = scale_diaspora_images($body);
797 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
801 logger('diaspora_reshare: empty body: source= ' . $x);
805 $person = find_diaspora_person_by_handle($orig_author);
807 if(is_array($person) && x($person,'name') && x($person,'url'))
808 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
810 $details = $orig_author;
812 $prefix = '♲ ' . $details . "\n";
815 // allocate a guid on our system - we aren't fixing any collisions.
816 // we're ignoring them
818 $g = q("select * from guid where guid = '%s' limit 1",
822 q("insert into guid ( guid ) values ( '%s' )",
827 $created = unxmlify($xml->created_at);
828 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
834 $tags = get_tags($body);
837 foreach($tags as $tag) {
838 if(strpos($tag,'#') === 0) {
839 if(strpos($tag,'[url='))
842 // don't link tags that are already embedded in links
844 if(preg_match('/\[(.*?)' . preg_quote($tag) . '(.*?)\]/',$body))
846 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag) . '(.*?)\)/',$body))
850 $basetag = str_replace('_',' ',substr($tag,1));
851 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
852 if(strlen($str_tags))
854 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
860 $datarray['uid'] = $importer['uid'];
861 $datarray['contact-id'] = $contact['id'];
862 $datarray['wall'] = 0;
863 $datarray['guid'] = $guid;
864 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
865 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
866 $datarray['private'] = $private;
867 $datarray['parent'] = 0;
868 $datarray['owner-name'] = $contact['name'];
869 $datarray['owner-link'] = $contact['url'];
870 $datarray['owner-avatar'] = $contact['thumb'];
871 $datarray['author-name'] = $contact['name'];
872 $datarray['author-link'] = $contact['url'];
873 $datarray['author-avatar'] = $contact['thumb'];
874 $datarray['body'] = $prefix . $body;
875 $datarray['tag'] = $str_tags;
876 $datarray['app'] = 'Diaspora';
878 $message_id = item_store($datarray);
881 q("update item set plink = '%s' where id = %d limit 1",
882 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
892 function diaspora_asphoto($importer,$xml) {
893 logger('diaspora_asphoto called');
896 $guid = notags(unxmlify($xml->guid));
897 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
899 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
903 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
904 logger('diaspora_asphoto: Ignoring this author.');
908 $message_id = $diaspora_handle . ':' . $guid;
909 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
910 intval($importer['uid']),
915 logger('diaspora_asphoto: message exists: ' . $guid);
919 // allocate a guid on our system - we aren't fixing any collisions.
920 // we're ignoring them
922 $g = q("select * from guid where guid = '%s' limit 1",
926 q("insert into guid ( guid ) values ( '%s' )",
931 $created = unxmlify($xml->created_at);
932 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
934 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
935 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
936 $body = scale_diaspora_images($body,false);
938 elseif($xml->image_url) {
939 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
940 $body = scale_diaspora_images($body);
943 logger('diaspora_asphoto: no photo url found.');
950 $datarray['uid'] = $importer['uid'];
951 $datarray['contact-id'] = $contact['id'];
952 $datarray['wall'] = 0;
953 $datarray['guid'] = $guid;
954 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
955 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
956 $datarray['private'] = $private;
957 $datarray['parent'] = 0;
958 $datarray['owner-name'] = $contact['name'];
959 $datarray['owner-link'] = $contact['url'];
960 $datarray['owner-avatar'] = $contact['thumb'];
961 $datarray['author-name'] = $contact['name'];
962 $datarray['author-link'] = $contact['url'];
963 $datarray['author-avatar'] = $contact['thumb'];
964 $datarray['body'] = $body;
966 $datarray['app'] = 'Diaspora/Cubbi.es';
968 $message_id = item_store($datarray);
971 q("update item set plink = '%s' where id = %d limit 1",
972 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
986 function diaspora_comment($importer,$xml,$msg) {
989 $guid = notags(unxmlify($xml->guid));
990 $parent_guid = notags(unxmlify($xml->parent_guid));
991 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
992 $target_type = notags(unxmlify($xml->target_type));
993 $text = unxmlify($xml->text);
994 $author_signature = notags(unxmlify($xml->author_signature));
996 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
998 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1000 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1004 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1005 logger('diaspora_comment: Ignoring this author.');
1009 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1010 intval($importer['uid']),
1014 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1018 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1019 intval($importer['uid']),
1023 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1026 $parent_item = $r[0];
1028 $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1030 $author_signature = base64_decode($author_signature);
1032 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1037 $person = find_diaspora_person_by_handle($diaspora_handle);
1039 if(is_array($person) && x($person,'pubkey'))
1040 $key = $person['pubkey'];
1042 logger('diaspora_comment: unable to find author details');
1047 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1048 logger('diaspora_comment: verification failed.');
1052 if($parent_author_signature) {
1053 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1055 $parent_author_signature = base64_decode($parent_author_signature);
1059 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1060 logger('diaspora_comment: owner verification failed.');
1065 // Phew! Everything checks out. Now create an item.
1067 $body = diaspora2bb($text);
1069 $message_id = $diaspora_handle . ':' . $guid;
1071 $datarray = array();
1075 $tags = get_tags($body);
1078 foreach($tags as $tag) {
1079 if(strpos($tag,'#') === 0) {
1080 if(strpos($tag,'[url='))
1083 // don't link tags that are already embedded in links
1085 if(preg_match('/\[(.*?)' . preg_quote($tag) . '(.*?)\]/',$body))
1087 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag) . '(.*?)\)/',$body))
1091 $basetag = str_replace('_',' ',substr($tag,1));
1092 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1093 if(strlen($str_tags))
1095 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1101 $datarray['uid'] = $importer['uid'];
1102 $datarray['contact-id'] = $contact['id'];
1103 $datarray['wall'] = $parent_item['wall'];
1104 $datarray['gravity'] = GRAVITY_COMMENT;
1105 $datarray['guid'] = $guid;
1106 $datarray['uri'] = $message_id;
1107 $datarray['parent-uri'] = $parent_item['uri'];
1109 // No timestamps for comments? OK, we'll the use current time.
1110 $datarray['created'] = $datarray['edited'] = datetime_convert();
1111 $datarray['private'] = $parent_item['private'];
1113 $datarray['owner-name'] = $parent_item['owner-name'];
1114 $datarray['owner-link'] = $parent_item['owner-link'];
1115 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1117 $datarray['author-name'] = $person['name'];
1118 $datarray['author-link'] = $person['url'];
1119 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1120 $datarray['body'] = $body;
1121 $datarray['tag'] = $str_tags;
1123 // We can't be certain what the original app is if the message is relayed.
1124 if(($parent_item['origin']) && (! $parent_author_signature))
1125 $datarray['app'] = 'Diaspora';
1127 $message_id = item_store($datarray);
1130 q("update item set plink = '%s' where id = %d limit 1",
1131 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1136 if(($parent_item['origin']) && (! $parent_author_signature)) {
1137 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1138 intval($message_id),
1139 dbesc($author_signed_data),
1140 dbesc(base64_encode($author_signature)),
1141 dbesc($diaspora_handle)
1144 // if the message isn't already being relayed, notify others
1145 // the existence of parent_author_signature means the parent_author or owner
1146 // is already relaying.
1148 proc_run('php','include/notifier.php','comment',$message_id);
1156 function diaspora_conversation($importer,$xml,$msg) {
1160 $guid = notags(unxmlify($xml->guid));
1161 $subject = notags(unxmlify($xml->subject));
1162 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1163 $participant_handles = notags(unxmlify($xml->participant_handles));
1164 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1166 $parent_uri = $diaspora_handle . ':' . $guid;
1168 $messages = $xml->message;
1170 if(! count($messages)) {
1171 logger('diaspora_conversation: empty conversation');
1175 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1177 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1181 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1182 logger('diaspora_conversation: Ignoring this author.');
1186 $conversation = null;
1188 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1189 intval($importer['uid']),
1193 $conversation = $c[0];
1195 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1196 intval($importer['uid']),
1198 dbesc($diaspora_handle),
1199 dbesc(datetime_convert('UTC','UTC',$created_at)),
1200 dbesc(datetime_convert()),
1202 dbesc($participant_handles)
1205 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1206 intval($importer['uid']),
1210 $conversation = $c[0];
1212 if(! $conversation) {
1213 logger('diaspora_conversation: unable to create conversation.');
1217 foreach($messages as $mesg) {
1221 $msg_guid = notags(unxmlify($mesg->guid));
1222 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1223 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1224 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1225 $msg_text = unxmlify($mesg->text);
1226 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1227 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1228 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1229 if($msg_conversation_guid != $guid) {
1230 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1234 $body = diaspora2bb($msg_text);
1235 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1237 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1239 $author_signature = base64_decode($msg_author_signature);
1241 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1246 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1248 if(is_array($person) && x($person,'pubkey'))
1249 $key = $person['pubkey'];
1251 logger('diaspora_conversation: unable to find author details');
1256 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1257 logger('diaspora_conversation: verification failed.');
1261 if($msg_parent_author_signature) {
1262 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1264 $parent_author_signature = base64_decode($msg_parent_author_signature);
1268 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1269 logger('diaspora_conversation: owner verification failed.');
1274 $r = q("select id from mail where `uri` = '%s' limit 1",
1278 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1282 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')",
1283 intval($importer['uid']),
1285 intval($conversation['id']),
1286 dbesc($person['name']),
1287 dbesc($person['photo']),
1288 dbesc($person['url']),
1289 intval($contact['id']),
1296 dbesc($msg_created_at)
1299 q("update conv set updated = '%s' where id = %d limit 1",
1300 dbesc(datetime_convert()),
1301 intval($conversation['id'])
1304 require_once('include/enotify.php');
1306 'type' => NOTIFY_MAIL,
1307 'notify_flags' => $importer['notify-flags'],
1308 'language' => $importer['language'],
1309 'to_name' => $importer['username'],
1310 'to_email' => $importer['email'],
1311 'item' => array('subject' => $subject, 'body' => $body),
1312 'source_name' => $person['name'],
1313 'source_link' => $person['url'],
1314 'source_photo' => $person['thumb'],
1315 'verb' => ACTIVITY_POST,
1323 function diaspora_message($importer,$xml,$msg) {
1327 $msg_guid = notags(unxmlify($xml->guid));
1328 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1329 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1330 $msg_author_signature = notags(unxmlify($xml->author_signature));
1331 $msg_text = unxmlify($xml->text);
1332 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1333 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1334 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1336 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1338 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1340 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1344 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1345 logger('diaspora_message: Ignoring this author.');
1349 $conversation = null;
1351 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1352 intval($importer['uid']),
1353 dbesc($msg_conversation_guid)
1356 $conversation = $c[0];
1358 logger('diaspora_message: conversation not available.');
1364 $body = diaspora2bb($msg_text);
1365 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1367 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1370 $author_signature = base64_decode($msg_author_signature);
1372 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1373 if(is_array($person) && x($person,'pubkey'))
1374 $key = $person['pubkey'];
1376 logger('diaspora_message: unable to find author details');
1380 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1381 logger('diaspora_message: verification failed.');
1385 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1387 intval($importer['uid'])
1390 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1394 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')",
1395 intval($importer['uid']),
1397 intval($conversation['id']),
1398 dbesc($person['name']),
1399 dbesc($person['photo']),
1400 dbesc($person['url']),
1401 intval($contact['id']),
1402 dbesc($conversation['subject']),
1408 dbesc($msg_created_at)
1411 q("update conv set updated = '%s' where id = %d limit 1",
1412 dbesc(datetime_convert()),
1413 intval($conversation['id'])
1420 function diaspora_photo($importer,$xml,$msg) {
1424 logger('diaspora_photo: init',LOGGER_DEBUG);
1426 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1428 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1430 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1432 $guid = notags(unxmlify($xml->guid));
1434 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1436 $public = notags(unxmlify($xml->public));
1438 $created_at = notags(unxmlify($xml_created_at));
1440 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1442 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1444 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1448 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1449 logger('diaspora_photo: Ignoring this author.');
1453 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1454 intval($importer['uid']),
1455 dbesc($status_message_guid)
1458 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1462 $parent_item = $r[0];
1464 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1466 $link_text = scale_diaspora_images($link_text);
1468 if(strpos($parent_item['body'],$link_text) === false) {
1469 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1470 dbesc($link_text . $parent_item['body']),
1471 intval($parent_item['id']),
1472 intval($parent_item['uid'])
1482 function diaspora_like($importer,$xml,$msg) {
1485 $guid = notags(unxmlify($xml->guid));
1486 $parent_guid = notags(unxmlify($xml->parent_guid));
1487 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1488 $target_type = notags(unxmlify($xml->target_type));
1489 $positive = notags(unxmlify($xml->positive));
1490 $author_signature = notags(unxmlify($xml->author_signature));
1492 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1494 // likes on comments not supported here and likes on photos not supported by Diaspora
1496 if($target_type !== 'Post')
1499 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1501 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1505 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1506 logger('diaspora_like: Ignoring this author.');
1510 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1511 intval($importer['uid']),
1515 logger('diaspora_like: parent item not found: ' . $guid);
1519 $parent_item = $r[0];
1521 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1522 intval($importer['uid']),
1526 if($positive === 'true') {
1527 logger('diaspora_like: duplicate like: ' . $guid);
1530 if($positive === 'false') {
1531 q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1532 intval($r[0]['id']),
1533 intval($importer['uid'])
1536 // send notification via proc_run()
1540 if($positive === 'false') {
1541 logger('diaspora_like: unlike received with no corresponding like');
1545 $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1547 $author_signature = base64_decode($author_signature);
1549 if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1554 $person = find_diaspora_person_by_handle($diaspora_handle);
1555 if(is_array($person) && x($person,'pubkey'))
1556 $key = $person['pubkey'];
1558 logger('diaspora_like: unable to find author details');
1563 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1564 logger('diaspora_like: verification failed.');
1568 if($parent_author_signature) {
1570 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1572 $parent_author_signature = base64_decode($parent_author_signature);
1576 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1577 logger('diaspora_like: owner verification failed.');
1582 // Phew! Everything checks out. Now create an item.
1584 $uri = $diaspora_handle . ':' . $guid;
1586 $activity = ACTIVITY_LIKE;
1587 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1588 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1589 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1590 $body = $parent_item['body'];
1595 <type>$objtype</type>
1597 <id>{$parent_item['uri']}</id>
1600 <content>$body</content>
1603 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1608 $arr['uid'] = $importer['uid'];
1609 $arr['guid'] = $guid;
1610 $arr['contact-id'] = $contact['id'];
1611 $arr['type'] = 'activity';
1612 $arr['wall'] = $parent_item['wall'];
1613 $arr['gravity'] = GRAVITY_LIKE;
1614 $arr['parent'] = $parent_item['id'];
1615 $arr['parent-uri'] = $parent_item['uri'];
1617 $arr['owner-name'] = $parent_item['name'];
1618 $arr['owner-link'] = $parent_item['url'];
1619 $arr['owner-avatar'] = $parent_item['thumb'];
1621 $arr['author-name'] = $person['name'];
1622 $arr['author-link'] = $person['url'];
1623 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1625 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1626 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1627 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1628 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1630 $arr['app'] = 'Diaspora';
1632 $arr['private'] = $parent_item['private'];
1633 $arr['verb'] = $activity;
1634 $arr['object-type'] = $objtype;
1635 $arr['object'] = $obj;
1636 $arr['visible'] = 1;
1638 $arr['last-child'] = 0;
1640 $message_id = item_store($arr);
1644 q("update item set plink = '%s' where id = %d limit 1",
1645 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1650 if(! $parent_author_signature) {
1651 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1652 intval($message_id),
1653 dbesc($author_signed_data),
1654 dbesc(base64_encode($author_signature)),
1655 dbesc($diaspora_handle)
1659 // if the message isn't already being relayed, notify others
1660 // the existence of parent_author_signature means the parent_author or owner
1661 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1663 if(($parent_item['origin']) && (! $parent_author_signature))
1664 proc_run('php','include/notifier.php','comment',$message_id);
1669 function diaspora_retraction($importer,$xml) {
1672 $guid = notags(unxmlify($xml->guid));
1673 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1674 $type = notags(unxmlify($xml->type));
1676 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1680 if($type === 'Person') {
1681 require_once('include/Contact.php');
1682 contact_remove($contact['id']);
1684 elseif($type === 'Post') {
1685 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1687 intval($importer['uid'])
1690 if(link_compare($r[0]['author-link'],$contact['url'])) {
1691 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1692 dbesc(datetime_convert()),
1703 function diaspora_signed_retraction($importer,$xml,$msg) {
1706 $guid = notags(unxmlify($xml->target_guid));
1707 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1708 $type = notags(unxmlify($xml->target_type));
1709 $sig = notags(unxmlify($xml->target_author_signature));
1711 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1713 logger('diaspora_signed_retraction: no contact');
1717 // this may not yet work for comments. Need to see how the relaying works
1718 // and figure out who signs it.
1721 $signed_data = $guid . ';' . $type ;
1723 $sig = base64_decode($sig);
1727 if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1728 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1732 if($type === 'StatusMessage') {
1733 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1735 intval($importer['uid'])
1738 if(link_compare($r[0]['author-link'],$contact['url'])) {
1739 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1740 dbesc(datetime_convert()),
1747 logger('diaspora_signed_retraction: unknown type: ' . $type);
1753 function diaspora_profile($importer,$xml) {
1756 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1758 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1762 if($contact['blocked']) {
1763 logger('diaspora_post: Ignoring this author.');
1767 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1768 $image_url = unxmlify($xml->image_url);
1769 $birthday = unxmlify($xml->birthday);
1771 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1772 intval($importer['uid']),
1773 intval($contact['id'])
1775 $oldphotos = ((count($r)) ? $r : null);
1777 require_once('include/Photo.php');
1779 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1781 // Generic birthday. We don't know the timezone. The year is irrelevant.
1783 $birthday = str_replace('1000','1901',$birthday);
1785 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1787 // this is to prevent multiple birthday notifications in a single year
1788 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1790 if(substr($birthday,5) === substr($contact['bd'],5))
1791 $birthday = $contact['bd'];
1793 $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",
1795 dbesc(datetime_convert()),
1799 dbesc(datetime_convert()),
1801 intval($contact['id']),
1802 intval($importer['uid'])
1807 foreach($oldphotos as $ph) {
1808 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1809 intval($importer['uid']),
1810 intval($contact['id']),
1811 dbesc($ph['resource-id'])
1821 function diaspora_share($me,$contact) {
1823 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1824 $theiraddr = $contact['addr'];
1826 $tpl = get_markup_template('diaspora_share.tpl');
1827 $msg = replace_macros($tpl, array(
1828 '$sender' => $myaddr,
1829 '$recipient' => $theiraddr
1832 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1834 return(diaspora_transmit($owner,$contact,$slap, false));
1837 function diaspora_unshare($me,$contact) {
1840 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1842 $tpl = get_markup_template('diaspora_retract.tpl');
1843 $msg = replace_macros($tpl, array(
1844 '$guid' => $me['guid'],
1845 '$type' => 'Person',
1846 '$handle' => $myaddr
1849 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1851 return(diaspora_transmit($owner,$contact,$slap, false));
1857 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1860 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1861 $theiraddr = $contact['addr'];
1865 $body = $item['body'];
1868 // We're trying to match Diaspora's split message/photo protocol but
1869 // all the photos are displayed on D* as links and not img's - even
1870 // though we're sending pretty much precisely what they send us when
1871 // doing the same operation.
1872 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1873 // which seems to get through intact.
1875 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1877 foreach($matches as $mtch) {
1879 $detail['str'] = $mtch[0];
1880 $detail['path'] = dirname($mtch[1]) . '/';
1881 $detail['file'] = basename($mtch[1]);
1882 $detail['guid'] = $item['guid'];
1883 $detail['handle'] = $myaddr;
1884 $images[] = $detail;
1885 $body = str_replace($detail['str'],$mtch[1],$body);
1890 $body = xmlify(html_entity_decode(bb2diaspora($body)));
1892 if($item['attach']) {
1893 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1895 $body .= "\n" . t('Attachments:') . "\n";
1896 foreach($matches as $mtch) {
1897 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1903 $public = (($item['private']) ? 'false' : 'true');
1905 require_once('include/datetime.php');
1906 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1908 $tpl = get_markup_template('diaspora_post.tpl');
1909 $msg = replace_macros($tpl, array(
1911 '$guid' => $item['guid'],
1912 '$handle' => xmlify($myaddr),
1913 '$public' => $public,
1914 '$created' => $created
1917 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1919 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1921 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1923 if(count($images)) {
1924 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1927 return $return_code;
1931 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1933 if(! count($images))
1935 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1937 $tpl = get_markup_template('diaspora_photo.tpl');
1938 foreach($images as $image) {
1939 if(! stristr($image['path'],$mysite))
1941 $resource = str_replace('.jpg','',$image['file']);
1942 $resource = substr($resource,0,strpos($resource,'-'));
1944 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1946 intval($owner['uid'])
1950 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1951 $msg = replace_macros($tpl,array(
1952 '$path' => xmlify($image['path']),
1953 '$filename' => xmlify($image['file']),
1954 '$msg_guid' => xmlify($image['guid']),
1955 '$guid' => xmlify($r[0]['guid']),
1956 '$handle' => xmlify($image['handle']),
1957 '$public' => xmlify($public),
1958 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1962 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1963 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1965 diaspora_transmit($owner,$contact,$slap,$public_batch);
1970 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1973 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1974 $theiraddr = $contact['addr'];
1976 $p = q("select guid from item where parent = %d limit 1",
1980 $parent_guid = $p[0]['guid'];
1984 if($item['verb'] === ACTIVITY_LIKE) {
1985 $tpl = get_markup_template('diaspora_like.tpl');
1987 $target_type = 'Post';
1988 $positive = (($item['deleted']) ? 'false' : 'true');
1991 $tpl = get_markup_template('diaspora_comment.tpl');
1995 $text = html_entity_decode(bb2diaspora($item['body']));
2000 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
2002 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
2004 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2006 $msg = replace_macros($tpl,array(
2007 '$guid' => xmlify($item['guid']),
2008 '$parent_guid' => xmlify($parent_guid),
2009 '$target_type' =>xmlify($target_type),
2010 '$authorsig' => xmlify($authorsig),
2011 '$body' => xmlify($text),
2012 '$positive' => xmlify($positive),
2013 '$handle' => xmlify($myaddr)
2016 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2018 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2020 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2024 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2028 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2029 $theiraddr = $contact['addr'];
2032 $p = q("select guid from item where parent = %d limit 1",
2036 $parent_guid = $p[0]['guid'];
2040 if($item['verb'] === ACTIVITY_LIKE) {
2041 $tpl = get_markup_template('diaspora_like_relay.tpl');
2043 $target_type = 'Post';
2044 $positive = (($item['deleted']) ? 'false' : 'true');
2047 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2051 $body = $item['body'];
2053 $text = html_entity_decode(bb2diaspora($body));
2055 // fetch the original signature if somebody sent the post to us to relay
2056 // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
2057 // action. It wasn't needed. In that case create the original signature and the
2058 // owner (parent author) signature
2059 // comments from other networks will be relayed under our name, with a brief
2060 // preamble to describe what's happening and noting the real author
2062 $r = q("select * from sign where iid = %d limit 1",
2067 $signed_text = $orig_sign['signed_text'];
2068 $authorsig = $orig_sign['signature'];
2069 $handle = $orig_sign['signer'];
2073 $itemcontact = q("select * from contact where `id` = %d limit 1",
2074 intval($item['contact-id'])
2076 if(count($itemcontact)) {
2077 if(! $itemcontact[0]['self']) {
2078 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
2079 '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',
2080 network_to_name($itemcontact['network'])) . "\n";
2081 $body = $prefix . $body;
2087 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
2089 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
2091 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2093 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2094 intval($item['id']),
2095 dbesc($signed_text),
2096 dbesc(base64_encode($authorsig)),
2105 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2107 $msg = replace_macros($tpl,array(
2108 '$guid' => xmlify($item['guid']),
2109 '$parent_guid' => xmlify($parent_guid),
2110 '$target_type' =>xmlify($target_type),
2111 '$authorsig' => xmlify($orig_sign['signature']),
2112 '$parentsig' => xmlify($parentauthorsig),
2113 '$body' => xmlify($text),
2114 '$positive' => xmlify($positive),
2115 '$handle' => xmlify($handle)
2118 logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
2120 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2122 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2128 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2131 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2133 $signed_text = $item['guid'] . ';' . 'StatusMessage';
2135 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2136 $msg = replace_macros($tpl, array(
2137 '$guid' => $item['guid'],
2138 '$type' => 'StatusMessage',
2139 '$handle' => $myaddr,
2140 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
2143 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2145 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2148 function diaspora_send_mail($item,$owner,$contact) {
2151 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2153 $r = q("select * from conv where id = %d and uid = %d limit 1",
2154 intval($item['convid']),
2155 intval($item['uid'])
2159 logger('diaspora_send_mail: conversation not found.');
2165 'guid' => xmlify($cnv['guid']),
2166 'subject' => xmlify($cnv['subject']),
2167 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2168 'diaspora_handle' => xmlify($cnv['creator']),
2169 'participant_handles' => xmlify($cnv['recips'])
2172 $body = bb2diaspora($item['body']);
2173 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2175 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2176 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2178 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2181 'guid' => xmlify($item['guid']),
2182 'parent_guid' => xmlify($cnv['guid']),
2183 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2184 'author_signature' => xmlify($sig),
2185 'text' => xmlify($body),
2186 'created_at' => xmlify($created),
2187 'diaspora_handle' => xmlify($myaddr),
2188 'conversation_guid' => xmlify($cnv['guid'])
2191 if($item['reply']) {
2192 $tpl = get_markup_template('diaspora_message.tpl');
2193 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2196 $conv['messages'] = array($msg);
2197 $tpl = get_markup_template('diaspora_conversation.tpl');
2198 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2201 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2203 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2205 return(diaspora_transmit($owner,$contact,$slap,false));
2210 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
2213 $logid = random_string(4);
2214 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2216 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2220 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2222 if(! intval(get_config('system','diaspora_test')))
2223 post_url($dest_url . '/', $slap);
2225 logger('diaspora_transmit: test_mode');
2229 $return_code = $a->get_curl_code();
2230 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2232 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2233 logger('diaspora_transmit: queue message');
2235 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2236 intval($contact['id']),
2237 dbesc(NETWORK_DIASPORA),
2239 intval($public_batch)
2242 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2245 // queue message for redelivery
2246 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2251 return(($return_code) ? $return_code : (-1));