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');
8 require_once('include/lock.php');
11 function diaspora_dispatch_public($msg) {
13 $enabled = intval(get_config('system','diaspora_enabled'));
15 logger('mod-diaspora: disabled');
19 $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 ",
20 dbesc(NETWORK_DIASPORA),
25 logger('diaspora_public: delivering to: ' . $rr['username']);
26 diaspora_dispatch($rr,$msg);
30 logger('diaspora_public: no subscribers');
35 function diaspora_dispatch($importer,$msg) {
39 $enabled = intval(get_config('system','diaspora_enabled'));
41 logger('mod-diaspora: disabled');
45 // php doesn't like dashes in variable names
47 $msg['message'] = str_replace(
48 array('<activity_streams-photo>','</activity_streams-photo>'),
49 array('<asphoto>','</asphoto>'),
53 $parsed_xml = parse_xml_string($msg['message'],false);
55 $xmlbase = $parsed_xml->post;
57 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
60 if($xmlbase->request) {
61 $ret = diaspora_request($importer,$xmlbase->request);
63 elseif($xmlbase->status_message) {
64 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
66 elseif($xmlbase->profile) {
67 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
69 elseif($xmlbase->comment) {
70 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
72 elseif($xmlbase->like) {
73 $ret = diaspora_like($importer,$xmlbase->like,$msg);
75 elseif($xmlbase->asphoto) {
76 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
78 elseif($xmlbase->reshare) {
79 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
81 elseif($xmlbase->retraction) {
82 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
84 elseif($xmlbase->signed_retraction) {
85 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
87 elseif($xmlbase->relayable_retraction) {
88 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
90 elseif($xmlbase->photo) {
91 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
93 elseif($xmlbase->conversation) {
94 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
96 elseif($xmlbase->message) {
97 $ret = diaspora_message($importer,$xmlbase->message,$msg);
100 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
105 function diaspora_get_contact_by_handle($uid,$handle) {
106 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
107 dbesc(NETWORK_DIASPORA),
116 function find_diaspora_person_by_handle($handle) {
126 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
127 dbesc(NETWORK_DIASPORA),
132 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
134 // update record occasionally so it doesn't get stale
135 $d = strtotime($person['updated'] . ' +00:00');
136 if($d < strtotime('now - 14 days'))
141 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
143 // If the person isn't in our 'fcontact' table, or if he/she is but
144 // his/her information hasn't been updated for more than 14 days, then
145 // we want to fetch the person's information from the remote server.
147 // Note that $person isn't changed by this block of code unless the
148 // person's information has been successfully fetched from the remote
149 // server. So if $person was 'false' to begin with (because he/she wasn't
150 // in the local cache), it'll stay false, and if $person held the local
151 // cache information to begin with, it'll keep that information. That way
152 // if there's a problem with the remote fetch, we can at least use our
153 // cached information--it's better than nothing.
155 if((! $person) || ($update)) {
156 // Lock the function to prevent race conditions if multiple items
157 // come in at the same time from a person who doesn't exist in
160 // Don't loop forever. On the last loop, try to create the contact
161 // whether the function is locked or not. Maybe the locking thread
162 // has died or something. At any rate, a duplicate in 'fcontact'
163 // is a much smaller problem than a deadlocked thread
164 $got_lock = lock_function('find_diaspora_person_by_handle', false);
165 if(($endlessloop + 1) >= $maxloops)
169 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
170 require_once('include/Scrape.php');
171 $r = probe_url($handle, PROBE_DIASPORA);
173 // Note that Friendica contacts can return a "Diaspora person"
174 // if Diaspora connectivity is enabled on their server
175 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
176 add_fcontact($r,$update);
180 unlock_function('find_diaspora_person_by_handle');
183 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
185 block_on_function_lock('find_diaspora_person_by_handle');
188 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
189 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
190 // The fact that the function was locked may mean that another process was creating the
191 // person's record. It could also mean another process was creating or updating an unrelated
194 // At any rate, we need to keep trying until we've either got the person or had a chance to
195 // try to fetch his/her remote information. But we don't want to block on locking the
196 // function, because if the other process is creating the record, then when we acquire the lock
197 // we'll dive right into creating another, duplicate record. We DO want to at least wait
198 // until the lock is released, so we don't flood the database with requests.
200 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
201 // we do have some information for the person
207 function get_diaspora_key($uri) {
208 logger('Fetching diaspora key for: ' . $uri);
210 $r = find_diaspora_person_by_handle($uri);
217 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
220 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
223 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
225 // $b64_data = base64_encode($msg);
226 // $b64url_data = base64url_encode($b64_data);
228 $b64url_data = base64url_encode($msg);
230 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
232 $type = 'application/xml';
233 $encoding = 'base64url';
236 $signable_data = $data . '.' . base64url_encode($type) . '.'
237 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
239 $signature = rsa_sign($signable_data,$prvkey);
240 $sig = base64url_encode($signature);
243 <?xml version='1.0' encoding='UTF-8'?>
244 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
246 <author_id>$handle</author_id>
249 <me:encoding>base64url</me:encoding>
250 <me:alg>RSA-SHA256</me:alg>
251 <me:data type="application/xml">$data</me:data>
252 <me:sig>$sig</me:sig>
257 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
265 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
269 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
271 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
273 // without a public key nothing will work
276 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
280 $inner_aes_key = random_string(32);
281 $b_inner_aes_key = base64_encode($inner_aes_key);
282 $inner_iv = random_string(16);
283 $b_inner_iv = base64_encode($inner_iv);
285 $outer_aes_key = random_string(32);
286 $b_outer_aes_key = base64_encode($outer_aes_key);
287 $outer_iv = random_string(16);
288 $b_outer_iv = base64_encode($outer_iv);
290 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
292 $padded_data = pkcs5_pad($msg,16);
293 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
295 $b64_data = base64_encode($inner_encrypted);
298 $b64url_data = base64url_encode($b64_data);
299 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
301 $type = 'application/xml';
302 $encoding = 'base64url';
305 $signable_data = $data . '.' . base64url_encode($type) . '.'
306 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
308 $signature = rsa_sign($signable_data,$prvkey);
309 $sig = base64url_encode($signature);
311 $decrypted_header = <<< EOT
314 <aes_key>$b_inner_aes_key</aes_key>
315 <author_id>$handle</author_id>
319 $decrypted_header = pkcs5_pad($decrypted_header,16);
321 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
323 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
325 $encrypted_outer_key_bundle = '';
326 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
328 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
330 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
332 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
333 'ciphertext' => base64_encode($ciphertext)));
334 $cipher_json = base64_encode($encrypted_header_json_object);
336 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
339 <?xml version='1.0' encoding='UTF-8'?>
340 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
343 <me:encoding>base64url</me:encoding>
344 <me:alg>RSA-SHA256</me:alg>
345 <me:data type="application/xml">$data</me:data>
346 <me:sig>$sig</me:sig>
351 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
358 * diaspora_decode($importer,$xml)
359 * array $importer -> from user table
360 * string $xml -> urldecoded Diaspora salmon
363 * 'message' -> decoded Diaspora XML message
364 * 'author' -> author diaspora handle
365 * 'key' -> author public key (converted to pkcs#8)
367 * Author and key are used elsewhere to save a lookup for verifying replies and likes
371 function diaspora_decode($importer,$xml) {
374 $basedom = parse_xml_string($xml);
376 $children = $basedom->children('https://joindiaspora.com/protocol');
378 if($children->header) {
380 $author_link = str_replace('acct:','',$children->header->author_id);
384 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
386 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
387 $ciphertext = base64_decode($encrypted_header->ciphertext);
389 $outer_key_bundle = '';
390 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
392 $j_outer_key_bundle = json_decode($outer_key_bundle);
394 $outer_iv = base64_decode($j_outer_key_bundle->iv);
395 $outer_key = base64_decode($j_outer_key_bundle->key);
397 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
400 $decrypted = pkcs5_unpad($decrypted);
403 * $decrypted now contains something like
406 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
407 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
412 * <name>Ryan Hughes</name>
413 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
418 * <author_id>galaxor@diaspora.priateship.org</author_id>
422 * </decrypted_header>
425 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
426 $idom = parse_xml_string($decrypted,false);
428 $inner_iv = base64_decode($idom->iv);
429 $inner_aes_key = base64_decode($idom->aes_key);
431 $author_link = str_replace('acct:','',$idom->author_id);
435 $dom = $basedom->children(NAMESPACE_SALMON_ME);
437 // figure out where in the DOM tree our data is hiding
439 if($dom->provenance->data)
440 $base = $dom->provenance;
441 elseif($dom->env->data)
447 logger('mod-diaspora: unable to locate salmon data in xml ');
448 http_status_exit(400);
452 // Stash the signature away for now. We have to find their key or it won't be good for anything.
453 $signature = base64url_decode($base->sig);
457 // strip whitespace so our data element will return to one big base64 blob
458 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
461 // stash away some other stuff for later
463 $type = $base->data[0]->attributes()->type[0];
464 $keyhash = $base->sig[0]->attributes()->keyhash[0];
465 $encoding = $base->encoding;
469 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
473 $data = base64url_decode($data);
477 $inner_decrypted = $data;
481 // Decode the encrypted blob
483 $inner_encrypted = base64_decode($data);
484 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
485 $inner_decrypted = pkcs5_unpad($inner_decrypted);
489 logger('mod-diaspora: Could not retrieve author URI.');
490 http_status_exit(400);
493 // Once we have the author URI, go to the web and try to find their public key
494 // (first this will look it up locally if it is in the fcontact cache)
495 // This will also convert diaspora public key from pkcs#1 to pkcs#8
497 logger('mod-diaspora: Fetching key for ' . $author_link );
498 $key = get_diaspora_key($author_link);
501 logger('mod-diaspora: Could not retrieve author key.');
502 http_status_exit(400);
505 $verify = rsa_verify($signed_data,$signature,$key);
508 logger('mod-diaspora: Message did not verify. Discarding.');
509 http_status_exit(400);
512 logger('mod-diaspora: Message verified.');
514 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
519 function diaspora_request($importer,$xml) {
523 $sender_handle = unxmlify($xml->sender_handle);
524 $recipient_handle = unxmlify($xml->recipient_handle);
526 if(! $sender_handle || ! $recipient_handle)
529 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
533 // perhaps we were already sharing with this person. Now they're sharing with us.
534 // That makes us friends.
536 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
537 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
538 intval(CONTACT_IS_FRIEND),
539 intval($contact['id']),
540 intval($importer['uid'])
545 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
546 intval($importer['uid'])
549 if((count($r)) && (! $r[0]['hide-friends']) && (! $contact['hidden'])) {
550 require_once('include/items.php');
552 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
553 intval($importer['uid'])
556 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
558 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
561 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
562 $arr['uid'] = $importer['uid'];
563 $arr['contact-id'] = $self[0]['id'];
565 $arr['type'] = 'wall';
568 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
569 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
570 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
571 $arr['verb'] = ACTIVITY_FRIEND;
572 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
574 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
575 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
576 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
577 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
579 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
580 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
581 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
582 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
583 $arr['object'] .= '</link></object>' . "\n";
584 $arr['last-child'] = 1;
586 $arr['allow_cid'] = $user[0]['allow_cid'];
587 $arr['allow_gid'] = $user[0]['allow_gid'];
588 $arr['deny_cid'] = $user[0]['deny_cid'];
589 $arr['deny_gid'] = $user[0]['deny_gid'];
591 $i = item_store($arr);
593 proc_run('php',"include/notifier.php","activity","$i");
602 $ret = find_diaspora_person_by_handle($sender_handle);
605 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
606 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
610 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
614 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
615 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
616 intval($importer['uid']),
617 dbesc($ret['network']),
621 dbesc(normalise_link($ret['url'])),
625 dbesc($ret['photo']),
626 dbesc($ret['pubkey']),
627 dbesc($ret['notify']),
633 // find the contact record we just created
635 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
637 if(! $contact_record) {
638 logger('diaspora_request: unable to locate newly created contact record.');
642 $g = q("select def_gid from user where uid = %d limit 1",
643 intval($importer['uid'])
645 if($g && intval($g[0]['def_gid'])) {
646 require_once('include/group.php');
647 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
650 if($importer['page-flags'] == PAGE_NORMAL) {
652 $hash = random_string() . (string) time(); // Generate a confirm_key
654 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
655 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
656 intval($importer['uid']),
657 intval($contact_record['id']),
660 dbesc( t('Sharing notification from Diaspora network')),
662 dbesc(datetime_convert())
667 // automatic friend approval
669 require_once('include/Photo.php');
671 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
673 // technically they are sharing with us (CONTACT_IS_SHARING),
674 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
675 // we are going to change the relationship and make them a follower.
677 if($importer['page-flags'] == PAGE_FREELOVE)
678 $new_relation = CONTACT_IS_FRIEND;
680 $new_relation = CONTACT_IS_FOLLOWER;
682 $r = q("UPDATE `contact` SET
689 `avatar-date` = '%s',
692 WHERE `id` = %d LIMIT 1
697 intval($new_relation),
698 dbesc(datetime_convert()),
699 dbesc(datetime_convert()),
700 dbesc(datetime_convert()),
701 intval($contact_record['id'])
704 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
706 $ret = diaspora_share($u[0],$contact_record);
712 function diaspora_post_allow($importer,$contact) {
713 if(($contact['blocked']) || ($contact['readonly']))
715 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
717 if($contact['rel'] == CONTACT_IS_FOLLOWER)
718 if($importer['page-flags'] == PAGE_COMMUNITY)
724 function diaspora_post($importer,$xml,$msg) {
727 $guid = notags(unxmlify($xml->guid));
728 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
730 if($diaspora_handle != $msg['author']) {
731 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
735 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
739 if(! diaspora_post_allow($importer,$contact)) {
740 logger('diaspora_post: Ignoring this author.');
744 $message_id = $diaspora_handle . ':' . $guid;
745 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
746 intval($importer['uid']),
751 logger('diaspora_post: message exists: ' . $guid);
755 // allocate a guid on our system - we aren't fixing any collisions.
756 // we're ignoring them
758 $g = q("select * from guid where guid = '%s' limit 1",
762 q("insert into guid ( guid ) values ( '%s' )",
767 $created = unxmlify($xml->created_at);
768 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
770 $body = diaspora2bb($xml->raw_message);
776 $tags = get_tags($body);
779 foreach($tags as $tag) {
780 if(strpos($tag,'#') === 0) {
781 if(strpos($tag,'[url='))
784 // don't link tags that are already embedded in links
786 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
788 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
791 $basetag = str_replace('_',' ',substr($tag,1));
792 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
793 if(strlen($str_tags))
795 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
801 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
803 foreach($matches as $mtch) {
804 if(strlen($str_tags))
806 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
810 $datarray['uid'] = $importer['uid'];
811 $datarray['contact-id'] = $contact['id'];
812 $datarray['wall'] = 0;
813 $datarray['guid'] = $guid;
814 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
815 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
816 $datarray['private'] = $private;
817 $datarray['parent'] = 0;
818 $datarray['owner-name'] = $contact['name'];
819 $datarray['owner-link'] = $contact['url'];
820 $datarray['owner-avatar'] = $contact['thumb'];
821 $datarray['author-name'] = $contact['name'];
822 $datarray['author-link'] = $contact['url'];
823 $datarray['author-avatar'] = $contact['thumb'];
824 $datarray['body'] = $body;
825 $datarray['tag'] = $str_tags;
826 $datarray['app'] = 'Diaspora';
828 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
830 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
832 $message_id = item_store($datarray);
835 q("update item set plink = '%s' where id = %d limit 1",
836 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
845 function diaspora_reshare($importer,$xml,$msg) {
847 logger('diaspora_reshare: init: ' . print_r($xml,true));
850 $guid = notags(unxmlify($xml->guid));
851 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
854 if($diaspora_handle != $msg['author']) {
855 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
859 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
863 if(! diaspora_post_allow($importer,$contact)) {
864 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
868 $message_id = $diaspora_handle . ':' . $guid;
869 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
870 intval($importer['uid']),
875 logger('diaspora_reshare: message exists: ' . $guid);
879 $orig_author = notags(unxmlify($xml->root_diaspora_id));
880 $orig_guid = notags(unxmlify($xml->root_guid));
882 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
883 $x = fetch_url($source_url);
885 $x = fetch_url(str_replace('https://','http://',$source_url));
887 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
890 logger('diaspora_reshare: source: ' . $x);
892 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
893 $source_xml = parse_xml_string($x,false);
895 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
896 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
897 $body = scale_external_images($body,false);
899 elseif($source_xml->post->asphoto->image_url) {
900 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
901 $body = scale_external_images($body);
903 elseif($source_xml->post->status_message) {
904 $body = diaspora2bb($source_xml->post->status_message->raw_message);
905 $body = scale_external_images($body);
909 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
913 logger('diaspora_reshare: empty body: source= ' . $x);
917 $person = find_diaspora_person_by_handle($orig_author);
919 if(is_array($person) && x($person,'name') && x($person,'url'))
920 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
922 $details = $orig_author;
924 $prefix = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . $details . "\n";
927 // allocate a guid on our system - we aren't fixing any collisions.
928 // we're ignoring them
930 $g = q("select * from guid where guid = '%s' limit 1",
934 q("insert into guid ( guid ) values ( '%s' )",
939 $created = unxmlify($xml->created_at);
940 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
946 $tags = get_tags($body);
949 foreach($tags as $tag) {
950 if(strpos($tag,'#') === 0) {
951 if(strpos($tag,'[url='))
954 // don't link tags that are already embedded in links
956 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
958 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
962 $basetag = str_replace('_',' ',substr($tag,1));
963 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
964 if(strlen($str_tags))
966 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
972 $datarray['uid'] = $importer['uid'];
973 $datarray['contact-id'] = $contact['id'];
974 $datarray['wall'] = 0;
975 $datarray['guid'] = $guid;
976 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
977 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
978 $datarray['private'] = $private;
979 $datarray['parent'] = 0;
980 $datarray['owner-name'] = $contact['name'];
981 $datarray['owner-link'] = $contact['url'];
982 $datarray['owner-avatar'] = $contact['thumb'];
983 $datarray['author-name'] = $contact['name'];
984 $datarray['author-link'] = $contact['url'];
985 $datarray['author-avatar'] = $contact['thumb'];
986 $datarray['body'] = $prefix . $body;
987 $datarray['tag'] = $str_tags;
988 $datarray['app'] = 'Diaspora';
990 $message_id = item_store($datarray);
993 q("update item set plink = '%s' where id = %d limit 1",
994 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1004 function diaspora_asphoto($importer,$xml,$msg) {
1005 logger('diaspora_asphoto called');
1008 $guid = notags(unxmlify($xml->guid));
1009 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1011 if($diaspora_handle != $msg['author']) {
1012 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1016 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1020 if(! diaspora_post_allow($importer,$contact)) {
1021 logger('diaspora_asphoto: Ignoring this author.');
1025 $message_id = $diaspora_handle . ':' . $guid;
1026 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1027 intval($importer['uid']),
1032 logger('diaspora_asphoto: message exists: ' . $guid);
1036 // allocate a guid on our system - we aren't fixing any collisions.
1037 // we're ignoring them
1039 $g = q("select * from guid where guid = '%s' limit 1",
1043 q("insert into guid ( guid ) values ( '%s' )",
1048 $created = unxmlify($xml->created_at);
1049 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1051 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1052 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1053 $body = scale_external_images($body,false);
1055 elseif($xml->image_url) {
1056 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1057 $body = scale_external_images($body);
1060 logger('diaspora_asphoto: no photo url found.');
1064 $datarray = array();
1067 $datarray['uid'] = $importer['uid'];
1068 $datarray['contact-id'] = $contact['id'];
1069 $datarray['wall'] = 0;
1070 $datarray['guid'] = $guid;
1071 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1072 $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1073 $datarray['private'] = $private;
1074 $datarray['parent'] = 0;
1075 $datarray['owner-name'] = $contact['name'];
1076 $datarray['owner-link'] = $contact['url'];
1077 $datarray['owner-avatar'] = $contact['thumb'];
1078 $datarray['author-name'] = $contact['name'];
1079 $datarray['author-link'] = $contact['url'];
1080 $datarray['author-avatar'] = $contact['thumb'];
1081 $datarray['body'] = $body;
1083 $datarray['app'] = 'Diaspora/Cubbi.es';
1085 $message_id = item_store($datarray);
1088 q("update item set plink = '%s' where id = %d limit 1",
1089 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1103 function diaspora_comment($importer,$xml,$msg) {
1106 $guid = notags(unxmlify($xml->guid));
1107 $parent_guid = notags(unxmlify($xml->parent_guid));
1108 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1109 $target_type = notags(unxmlify($xml->target_type));
1110 $text = unxmlify($xml->text);
1111 $author_signature = notags(unxmlify($xml->author_signature));
1113 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1115 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1117 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1121 if(! diaspora_post_allow($importer,$contact)) {
1122 logger('diaspora_comment: Ignoring this author.');
1126 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1127 intval($importer['uid']),
1131 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1135 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1136 intval($importer['uid']),
1140 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1143 $parent_item = $r[0];
1146 /* How Diaspora performs comment signature checking:
1148 - If an item has been sent by the comment author to the top-level post owner to relay on
1149 to the rest of the contacts on the top-level post, the top-level post owner should check
1150 the author_signature, then create a parent_author_signature before relaying the comment on
1151 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1152 check only the parent_author_signature. Basically, they trust that the top-level post
1153 owner has already verified the authenticity of anything he/she sends out
1154 - In either case, the signature that get checked is the signature created by the person
1158 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1161 if($parent_author_signature) {
1162 // If a parent_author_signature exists, then we've received the comment
1163 // relayed from the top-level post owner. There's no need to check the
1164 // author_signature if the parent_author_signature is valid
1166 $parent_author_signature = base64_decode($parent_author_signature);
1168 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1169 logger('diaspora_comment: top-level owner verification failed.');
1174 // If there's no parent_author_signature, then we've received the comment
1175 // from the comment creator. In that case, the person is commenting on
1176 // our post, so he/she must be a contact of ours and his/her public key
1177 // should be in $msg['key']
1179 $author_signature = base64_decode($author_signature);
1181 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1182 logger('diaspora_comment: comment author verification failed.');
1187 // Phew! Everything checks out. Now create an item.
1189 // Find the original comment author information.
1190 // We need this to make sure we display the comment author
1191 // information (name and avatar) correctly.
1192 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1195 $person = find_diaspora_person_by_handle($diaspora_handle);
1197 if(! is_array($person)) {
1198 logger('diaspora_comment: unable to find author details');
1203 $body = diaspora2bb($text);
1205 $message_id = $diaspora_handle . ':' . $guid;
1207 $datarray = array();
1211 $tags = get_tags($body);
1214 foreach($tags as $tag) {
1215 if(strpos($tag,'#') === 0) {
1216 if(strpos($tag,'[url='))
1219 // don't link tags that are already embedded in links
1221 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1223 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1227 $basetag = str_replace('_',' ',substr($tag,1));
1228 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1229 if(strlen($str_tags))
1231 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1237 $datarray['uid'] = $importer['uid'];
1238 $datarray['contact-id'] = $contact['id'];
1239 $datarray['type'] = 'remote-comment';
1240 $datarray['wall'] = $parent_item['wall'];
1241 $datarray['gravity'] = GRAVITY_COMMENT;
1242 $datarray['guid'] = $guid;
1243 $datarray['uri'] = $message_id;
1244 $datarray['parent-uri'] = $parent_item['uri'];
1246 // No timestamps for comments? OK, we'll the use current time.
1247 $datarray['created'] = $datarray['edited'] = datetime_convert();
1248 $datarray['private'] = $parent_item['private'];
1250 $datarray['owner-name'] = $parent_item['owner-name'];
1251 $datarray['owner-link'] = $parent_item['owner-link'];
1252 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1254 $datarray['author-name'] = $person['name'];
1255 $datarray['author-link'] = $person['url'];
1256 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1257 $datarray['body'] = $body;
1258 $datarray['tag'] = $str_tags;
1260 // We can't be certain what the original app is if the message is relayed.
1261 if(($parent_item['origin']) && (! $parent_author_signature))
1262 $datarray['app'] = 'Diaspora';
1264 $message_id = item_store($datarray);
1267 q("update item set plink = '%s' where id = %d limit 1",
1268 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1273 if(($parent_item['origin']) && (! $parent_author_signature)) {
1274 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1275 intval($message_id),
1276 dbesc($signed_data),
1277 dbesc(base64_encode($author_signature)),
1278 dbesc($diaspora_handle)
1281 // if the message isn't already being relayed, notify others
1282 // the existence of parent_author_signature means the parent_author or owner
1283 // is already relaying.
1285 proc_run('php','include/notifier.php','comment',$message_id);
1288 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1289 dbesc($parent_item['uri']),
1290 intval($importer['uid'])
1293 if(count($myconv)) {
1294 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1296 foreach($myconv as $conv) {
1298 // now if we find a match, it means we're in this conversation
1300 if(! link_compare($conv['author-link'],$importer_url))
1303 require_once('include/enotify.php');
1305 $conv_parent = $conv['parent'];
1308 'type' => NOTIFY_COMMENT,
1309 'notify_flags' => $importer['notify-flags'],
1310 'language' => $importer['language'],
1311 'to_name' => $importer['username'],
1312 'to_email' => $importer['email'],
1313 'uid' => $importer['uid'],
1314 'item' => $datarray,
1315 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id,
1316 'source_name' => $datarray['author-name'],
1317 'source_link' => $datarray['author-link'],
1318 'source_photo' => $datarray['author-avatar'],
1319 'verb' => ACTIVITY_POST,
1321 'parent' => $conv_parent,
1325 // only send one notification
1335 function diaspora_conversation($importer,$xml,$msg) {
1339 $guid = notags(unxmlify($xml->guid));
1340 $subject = notags(unxmlify($xml->subject));
1341 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1342 $participant_handles = notags(unxmlify($xml->participant_handles));
1343 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1345 $parent_uri = $diaspora_handle . ':' . $guid;
1347 $messages = $xml->message;
1349 if(! count($messages)) {
1350 logger('diaspora_conversation: empty conversation');
1354 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1356 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1360 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1361 logger('diaspora_conversation: Ignoring this author.');
1365 $conversation = null;
1367 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1368 intval($importer['uid']),
1372 $conversation = $c[0];
1374 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1375 intval($importer['uid']),
1377 dbesc($diaspora_handle),
1378 dbesc(datetime_convert('UTC','UTC',$created_at)),
1379 dbesc(datetime_convert()),
1381 dbesc($participant_handles)
1384 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1385 intval($importer['uid']),
1389 $conversation = $c[0];
1391 if(! $conversation) {
1392 logger('diaspora_conversation: unable to create conversation.');
1396 foreach($messages as $mesg) {
1400 $msg_guid = notags(unxmlify($mesg->guid));
1401 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1402 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1403 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1404 $msg_text = unxmlify($mesg->text);
1405 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1406 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1407 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1408 if($msg_conversation_guid != $guid) {
1409 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1413 $body = diaspora2bb($msg_text);
1414 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1416 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1418 $author_signature = base64_decode($msg_author_signature);
1420 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1425 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1427 if(is_array($person) && x($person,'pubkey'))
1428 $key = $person['pubkey'];
1430 logger('diaspora_conversation: unable to find author details');
1435 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1436 logger('diaspora_conversation: verification failed.');
1440 if($msg_parent_author_signature) {
1441 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1443 $parent_author_signature = base64_decode($msg_parent_author_signature);
1447 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1448 logger('diaspora_conversation: owner verification failed.');
1453 $r = q("select id from mail where `uri` = '%s' limit 1",
1457 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1461 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')",
1462 intval($importer['uid']),
1464 intval($conversation['id']),
1465 dbesc($person['name']),
1466 dbesc($person['photo']),
1467 dbesc($person['url']),
1468 intval($contact['id']),
1475 dbesc($msg_created_at)
1478 q("update conv set updated = '%s' where id = %d limit 1",
1479 dbesc(datetime_convert()),
1480 intval($conversation['id'])
1483 require_once('include/enotify.php');
1485 'type' => NOTIFY_MAIL,
1486 'notify_flags' => $importer['notify-flags'],
1487 'language' => $importer['language'],
1488 'to_name' => $importer['username'],
1489 'to_email' => $importer['email'],
1490 'uid' =>$importer['importer_uid'],
1491 'item' => array('subject' => $subject, 'body' => $body),
1492 'source_name' => $person['name'],
1493 'source_link' => $person['url'],
1494 'source_photo' => $person['thumb'],
1495 'verb' => ACTIVITY_POST,
1503 function diaspora_message($importer,$xml,$msg) {
1507 $msg_guid = notags(unxmlify($xml->guid));
1508 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1509 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1510 $msg_author_signature = notags(unxmlify($xml->author_signature));
1511 $msg_text = unxmlify($xml->text);
1512 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1513 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1514 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1516 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1518 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1520 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1524 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1525 logger('diaspora_message: Ignoring this author.');
1529 $conversation = null;
1531 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1532 intval($importer['uid']),
1533 dbesc($msg_conversation_guid)
1536 $conversation = $c[0];
1538 logger('diaspora_message: conversation not available.');
1544 $body = diaspora2bb($msg_text);
1545 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1547 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1550 $author_signature = base64_decode($msg_author_signature);
1552 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1553 if(is_array($person) && x($person,'pubkey'))
1554 $key = $person['pubkey'];
1556 logger('diaspora_message: unable to find author details');
1560 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1561 logger('diaspora_message: verification failed.');
1565 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1567 intval($importer['uid'])
1570 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1574 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')",
1575 intval($importer['uid']),
1577 intval($conversation['id']),
1578 dbesc($person['name']),
1579 dbesc($person['photo']),
1580 dbesc($person['url']),
1581 intval($contact['id']),
1582 dbesc($conversation['subject']),
1588 dbesc($msg_created_at)
1591 q("update conv set updated = '%s' where id = %d limit 1",
1592 dbesc(datetime_convert()),
1593 intval($conversation['id'])
1600 function diaspora_photo($importer,$xml,$msg) {
1604 logger('diaspora_photo: init',LOGGER_DEBUG);
1606 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1608 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1610 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1612 $guid = notags(unxmlify($xml->guid));
1614 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1616 $public = notags(unxmlify($xml->public));
1618 $created_at = notags(unxmlify($xml_created_at));
1620 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1622 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1624 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1628 if(! diaspora_post_allow($importer,$contact)) {
1629 logger('diaspora_photo: Ignoring this author.');
1633 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1634 intval($importer['uid']),
1635 dbesc($status_message_guid)
1638 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1642 $parent_item = $r[0];
1644 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1646 $link_text = scale_external_images($link_text, true,
1647 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1649 if(strpos($parent_item['body'],$link_text) === false) {
1650 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1651 dbesc($link_text . $parent_item['body']),
1652 intval($parent_item['id']),
1653 intval($parent_item['uid'])
1663 function diaspora_like($importer,$xml,$msg) {
1666 $guid = notags(unxmlify($xml->guid));
1667 $parent_guid = notags(unxmlify($xml->parent_guid));
1668 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1669 $target_type = notags(unxmlify($xml->target_type));
1670 $positive = notags(unxmlify($xml->positive));
1671 $author_signature = notags(unxmlify($xml->author_signature));
1673 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1675 // likes on comments not supported here and likes on photos not supported by Diaspora
1677 // if($target_type !== 'Post')
1680 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1682 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1686 if(! diaspora_post_allow($importer,$contact)) {
1687 logger('diaspora_like: Ignoring this author.');
1691 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1692 intval($importer['uid']),
1696 logger('diaspora_like: parent item not found: ' . $guid);
1700 $parent_item = $r[0];
1702 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1703 intval($importer['uid']),
1707 if($positive === 'true') {
1708 logger('diaspora_like: duplicate like: ' . $guid);
1711 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1712 // It looks like "RelayableRetractions" are used for "unlike" instead
1713 if($positive === 'false') {
1714 logger('diaspora_like: received a like with positive set to "false"...ignoring');
1715 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1716 intval($r[0]['id']),
1717 intval($importer['uid'])
1719 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1720 // send notification via proc_run()
1724 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1725 // It looks like "RelayableRetractions" are used for "unlike" instead
1726 if($positive === 'false') {
1727 logger('diaspora_like: received a like with positive set to "false"');
1728 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1733 /* How Diaspora performs "like" signature checking:
1735 - If an item has been sent by the like author to the top-level post owner to relay on
1736 to the rest of the contacts on the top-level post, the top-level post owner should check
1737 the author_signature, then create a parent_author_signature before relaying the like on
1738 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1739 check only the parent_author_signature. Basically, they trust that the top-level post
1740 owner has already verified the authenticity of anything he/she sends out
1741 - In either case, the signature that get checked is the signature created by the person
1745 $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1748 if($parent_author_signature) {
1749 // If a parent_author_signature exists, then we've received the like
1750 // relayed from the top-level post owner. There's no need to check the
1751 // author_signature if the parent_author_signature is valid
1753 $parent_author_signature = base64_decode($parent_author_signature);
1755 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1756 logger('diaspora_like: top-level owner verification failed.');
1761 // If there's no parent_author_signature, then we've received the like
1762 // from the like creator. In that case, the person is "like"ing
1763 // our post, so he/she must be a contact of ours and his/her public key
1764 // should be in $msg['key']
1766 $author_signature = base64_decode($author_signature);
1768 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1769 logger('diaspora_like: like creator verification failed.');
1774 // Phew! Everything checks out. Now create an item.
1776 // Find the original comment author information.
1777 // We need this to make sure we display the comment author
1778 // information (name and avatar) correctly.
1779 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1782 $person = find_diaspora_person_by_handle($diaspora_handle);
1784 if(! is_array($person)) {
1785 logger('diaspora_like: unable to find author details');
1790 $uri = $diaspora_handle . ':' . $guid;
1792 $activity = ACTIVITY_LIKE;
1793 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1794 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1795 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1796 $body = $parent_item['body'];
1801 <type>$objtype</type>
1803 <id>{$parent_item['uri']}</id>
1806 <content>$body</content>
1809 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1814 $arr['uid'] = $importer['uid'];
1815 $arr['guid'] = $guid;
1816 $arr['contact-id'] = $contact['id'];
1817 $arr['type'] = 'activity';
1818 $arr['wall'] = $parent_item['wall'];
1819 $arr['gravity'] = GRAVITY_LIKE;
1820 $arr['parent'] = $parent_item['id'];
1821 $arr['parent-uri'] = $parent_item['uri'];
1823 $arr['owner-name'] = $parent_item['name'];
1824 $arr['owner-link'] = $parent_item['url'];
1825 $arr['owner-avatar'] = $parent_item['thumb'];
1827 $arr['author-name'] = $person['name'];
1828 $arr['author-link'] = $person['url'];
1829 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1831 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1832 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1833 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1834 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1836 $arr['app'] = 'Diaspora';
1838 $arr['private'] = $parent_item['private'];
1839 $arr['verb'] = $activity;
1840 $arr['object-type'] = $objtype;
1841 $arr['object'] = $obj;
1842 $arr['visible'] = 1;
1844 $arr['last-child'] = 0;
1846 $message_id = item_store($arr);
1850 q("update item set plink = '%s' where id = %d limit 1",
1851 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1856 if(! $parent_author_signature) {
1857 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1858 intval($message_id),
1859 dbesc($signed_data),
1860 dbesc(base64_encode($author_signature)),
1861 dbesc($diaspora_handle)
1865 // if the message isn't already being relayed, notify others
1866 // the existence of parent_author_signature means the parent_author or owner
1867 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1869 if(($parent_item['origin']) && (! $parent_author_signature))
1870 proc_run('php','include/notifier.php','comment',$message_id);
1875 function diaspora_retraction($importer,$xml) {
1878 $guid = notags(unxmlify($xml->guid));
1879 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1880 $type = notags(unxmlify($xml->type));
1882 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1886 if($type === 'Person') {
1887 require_once('include/Contact.php');
1888 contact_remove($contact['id']);
1890 elseif($type === 'Post') {
1891 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1893 intval($importer['uid'])
1896 if(link_compare($r[0]['author-link'],$contact['url'])) {
1897 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1898 dbesc(datetime_convert()),
1909 function diaspora_signed_retraction($importer,$xml,$msg) {
1912 $guid = notags(unxmlify($xml->target_guid));
1913 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1914 $type = notags(unxmlify($xml->target_type));
1915 $sig = notags(unxmlify($xml->target_author_signature));
1917 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1919 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1921 logger('diaspora_signed_retraction: no contact');
1926 $signed_data = $guid . ';' . $type ;
1929 /* How Diaspora performs relayable_retraction signature checking:
1931 - If an item has been sent by the item author to the top-level post owner to relay on
1932 to the rest of the contacts on the top-level post, the top-level post owner checks
1933 the author_signature, then creates a parent_author_signature before relaying the item on
1934 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1935 check only the parent_author_signature. Basically, they trust that the top-level post
1936 owner has already verified the authenticity of anything he/she sends out
1937 - In either case, the signature that get checked is the signature created by the person
1941 if($parent_author_signature) {
1943 $parent_author_signature = base64_decode($parent_author_signature);
1945 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1946 logger('diaspora_signed_retraction: top-level post owner verification failed');
1953 $sig_decode = base64_decode($sig);
1955 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
1956 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
1961 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
1962 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1964 intval($importer['uid'])
1967 if(link_compare($r[0]['author-link'],$contact['url'])) {
1968 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d limit 1",
1969 dbesc(datetime_convert()),
1970 dbesc(datetime_convert()),
1974 // Now check if the retraction needs to be relayed by us
1976 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
1977 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
1978 // The only item with `parent` and `id` as the parent id is the parent item.
1979 $p = q("select origin from item where parent = %d and id = %d limit 1",
1984 if(($p[0]['origin']) && (! $parent_author_signature)) {
1985 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1987 dbesc($signed_data),
1989 dbesc($diaspora_handle)
1992 // the existence of parent_author_signature would have meant the parent_author or owner
1993 // is already relaying.
1994 logger('diaspora_signed_retraction: relaying relayable_retraction');
1996 proc_run('php','include/notifier.php','relayable_retraction',$r[0]['id']);
2003 logger('diaspora_signed_retraction: unknown type: ' . $type);
2009 function diaspora_profile($importer,$xml,$msg) {
2012 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2015 if($diaspora_handle != $msg['author']) {
2016 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2020 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2024 if($contact['blocked']) {
2025 logger('diaspora_post: Ignoring this author.');
2029 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2030 $image_url = unxmlify($xml->image_url);
2031 $birthday = unxmlify($xml->birthday);
2033 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2034 intval($importer['uid']),
2035 intval($contact['id'])
2037 $oldphotos = ((count($r)) ? $r : null);
2039 require_once('include/Photo.php');
2041 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2043 // Generic birthday. We don't know the timezone. The year is irrelevant.
2045 $birthday = str_replace('1000','1901',$birthday);
2047 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2049 // this is to prevent multiple birthday notifications in a single year
2050 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2052 if(substr($birthday,5) === substr($contact['bd'],5))
2053 $birthday = $contact['bd'];
2055 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2056 // Not doing this currently because D* protocol is scheduled for revision soon.
2058 $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",
2060 dbesc(datetime_convert()),
2064 dbesc(datetime_convert()),
2066 intval($contact['id']),
2067 intval($importer['uid'])
2072 foreach($oldphotos as $ph) {
2073 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2074 intval($importer['uid']),
2075 intval($contact['id']),
2076 dbesc($ph['resource-id'])
2086 function diaspora_share($me,$contact) {
2088 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2089 $theiraddr = $contact['addr'];
2091 $tpl = get_markup_template('diaspora_share.tpl');
2092 $msg = replace_macros($tpl, array(
2093 '$sender' => $myaddr,
2094 '$recipient' => $theiraddr
2097 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2098 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2100 return(diaspora_transmit($owner,$contact,$slap, false));
2103 function diaspora_unshare($me,$contact) {
2106 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2108 $tpl = get_markup_template('diaspora_retract.tpl');
2109 $msg = replace_macros($tpl, array(
2110 '$guid' => $me['guid'],
2111 '$type' => 'Person',
2112 '$handle' => $myaddr
2115 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2116 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2118 return(diaspora_transmit($owner,$contact,$slap, false));
2124 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2127 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2128 $theiraddr = $contact['addr'];
2132 $title = $item['title'];
2133 $body = $item['body'];
2136 // We're trying to match Diaspora's split message/photo protocol but
2137 // all the photos are displayed on D* as links and not img's - even
2138 // though we're sending pretty much precisely what they send us when
2139 // doing the same operation.
2140 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2141 // which seems to get through intact.
2143 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2145 foreach($matches as $mtch) {
2147 $detail['str'] = $mtch[0];
2148 $detail['path'] = dirname($mtch[1]) . '/';
2149 $detail['file'] = basename($mtch[1]);
2150 $detail['guid'] = $item['guid'];
2151 $detail['handle'] = $myaddr;
2152 $images[] = $detail;
2153 $body = str_replace($detail['str'],$mtch[1],$body);
2158 $body = preg_replace('/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $body);
2160 //if(strlen($title))
2161 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2163 // convert to markdown
2164 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2165 //$body = bb2diaspora($body);
2169 $body = "## ".html_entity_decode($title)."\n\n".$body;
2171 if($item['attach']) {
2172 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2174 $body .= "\n" . t('Attachments:') . "\n";
2175 foreach($matches as $mtch) {
2176 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2182 $public = (($item['private']) ? 'false' : 'true');
2184 require_once('include/datetime.php');
2185 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2187 $tpl = get_markup_template('diaspora_post.tpl');
2188 $msg = replace_macros($tpl, array(
2190 '$guid' => $item['guid'],
2191 '$handle' => xmlify($myaddr),
2192 '$public' => $public,
2193 '$created' => $created
2196 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
2198 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2199 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2201 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2203 if(count($images)) {
2204 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2207 return $return_code;
2211 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2213 if(! count($images))
2215 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2217 $tpl = get_markup_template('diaspora_photo.tpl');
2218 foreach($images as $image) {
2219 if(! stristr($image['path'],$mysite))
2221 $resource = str_replace('.jpg','',$image['file']);
2222 $resource = substr($resource,0,strpos($resource,'-'));
2224 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2226 intval($owner['uid'])
2230 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2231 $msg = replace_macros($tpl,array(
2232 '$path' => xmlify($image['path']),
2233 '$filename' => xmlify($image['file']),
2234 '$msg_guid' => xmlify($image['guid']),
2235 '$guid' => xmlify($r[0]['guid']),
2236 '$handle' => xmlify($image['handle']),
2237 '$public' => xmlify($public),
2238 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2242 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2243 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2244 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2246 diaspora_transmit($owner,$contact,$slap,$public_batch);
2251 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2254 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2255 // $theiraddr = $contact['addr'];
2257 if($item['thr-parent']) {
2258 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2259 dbesc($item['thr-parent'])
2263 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2264 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2265 // The only item with `parent` and `id` as the parent id is the parent item.
2266 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2267 intval($item['parent']),
2268 intval($item['parent'])
2276 if($item['verb'] === ACTIVITY_LIKE) {
2277 $tpl = get_markup_template('diaspora_like.tpl');
2279 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2280 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2281 // $positive = (($item['deleted']) ? 'false' : 'true');
2284 if(($item['deleted']))
2285 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2288 $tpl = get_markup_template('diaspora_comment.tpl');
2292 $text = html_entity_decode(bb2diaspora($item['body']));
2297 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2299 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2301 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2303 $msg = replace_macros($tpl,array(
2304 '$guid' => xmlify($item['guid']),
2305 '$parent_guid' => xmlify($parent['guid']),
2306 '$target_type' =>xmlify($target_type),
2307 '$authorsig' => xmlify($authorsig),
2308 '$body' => xmlify($text),
2309 '$positive' => xmlify($positive),
2310 '$handle' => xmlify($myaddr)
2313 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2315 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2316 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2318 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2322 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2326 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2327 // $theiraddr = $contact['addr'];
2329 $body = $item['body'];
2330 $text = html_entity_decode(bb2diaspora($body));
2333 if($item['thr-parent']) {
2334 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2335 dbesc($item['thr-parent'])
2339 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2340 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2341 // The only item with `parent` and `id` as the parent id is the parent item.
2342 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2343 intval($item['parent']),
2344 intval($item['parent'])
2353 $relay_retract = false;
2354 $sql_sign_id = 'iid';
2355 if( $item['deleted']) {
2356 $relay_retract = true;
2358 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2360 $sql_sign_id = 'retract_iid';
2361 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2363 elseif($item['verb'] === ACTIVITY_LIKE) {
2366 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2367 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2368 // $positive = (($item['deleted']) ? 'false' : 'true');
2371 $tpl = get_markup_template('diaspora_like_relay.tpl');
2373 else { // item is a comment
2374 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2378 // fetch the original signature if the relayable was created by a Diaspora
2379 // or DFRN user. Relayables for other networks are not supported.
2381 $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2386 $signed_text = $orig_sign['signed_text'];
2387 $authorsig = $orig_sign['signature'];
2388 $handle = $orig_sign['signer'];
2392 // Author signature information (for likes, comments, and retractions of likes or comments,
2393 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2394 // function is called
2395 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2400 $sender_signed_text = $item['guid'] . ';' . $target_type;
2402 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2404 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2406 // Sign the relayable with the top-level owner's signature
2408 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2409 // stored in the database, because that provides the best chance that Diaspora will
2410 // be able to reconstruct the signed text the same way we did. This is particularly a
2411 // concern for the comment, whose signed text includes the text of the comment. The
2412 // smallest change in the text of the comment, including removing whitespace, will
2413 // make the signature verification fail. Since we translate from BB code to Diaspora's
2414 // markup at the top of this function, which is AFTER we placed the original $signed_text
2415 // in the database, it's hazardous to trust the original $signed_text.
2417 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2419 $msg = replace_macros($tpl,array(
2420 '$guid' => xmlify($item['guid']),
2421 '$parent_guid' => xmlify($parent['guid']),
2422 '$target_type' =>xmlify($target_type),
2423 '$authorsig' => xmlify($authorsig),
2424 '$parentsig' => xmlify($parentauthorsig),
2425 '$body' => xmlify($text),
2426 '$positive' => xmlify($positive),
2427 '$handle' => xmlify($handle)
2430 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2433 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2434 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2436 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2442 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2445 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2447 // Check whether the retraction is for a top-level post or whether it's a relayable
2448 if( $item['uri'] !== $item['parent-uri'] ) {
2450 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2451 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2455 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2456 $target_type = 'StatusMessage';
2459 $signed_text = $item['guid'] . ';' . $target_type;
2461 $msg = replace_macros($tpl, array(
2462 '$guid' => xmlify($item['guid']),
2463 '$type' => xmlify($target_type),
2464 '$handle' => xmlify($myaddr),
2465 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2468 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2469 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2471 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2474 function diaspora_send_mail($item,$owner,$contact) {
2477 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2479 $r = q("select * from conv where id = %d and uid = %d limit 1",
2480 intval($item['convid']),
2481 intval($item['uid'])
2485 logger('diaspora_send_mail: conversation not found.');
2491 'guid' => xmlify($cnv['guid']),
2492 'subject' => xmlify($cnv['subject']),
2493 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2494 'diaspora_handle' => xmlify($cnv['creator']),
2495 'participant_handles' => xmlify($cnv['recips'])
2498 $body = bb2diaspora($item['body']);
2499 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2501 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2502 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2504 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2507 'guid' => xmlify($item['guid']),
2508 'parent_guid' => xmlify($cnv['guid']),
2509 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2510 'author_signature' => xmlify($sig),
2511 'text' => xmlify($body),
2512 'created_at' => xmlify($created),
2513 'diaspora_handle' => xmlify($myaddr),
2514 'conversation_guid' => xmlify($cnv['guid'])
2517 if($item['reply']) {
2518 $tpl = get_markup_template('diaspora_message.tpl');
2519 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2522 $conv['messages'] = array($msg);
2523 $tpl = get_markup_template('diaspora_conversation.tpl');
2524 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2527 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2529 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2530 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2532 return(diaspora_transmit($owner,$contact,$slap,false));
2537 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2539 $enabled = intval(get_config('system','diaspora_enabled'));
2545 $logid = random_string(4);
2546 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2548 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2552 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2554 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2558 if(! intval(get_config('system','diaspora_test'))) {
2559 post_url($dest_url . '/', $slap);
2560 $return_code = $a->get_curl_code();
2563 logger('diaspora_transmit: test_mode');
2568 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2570 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2571 logger('diaspora_transmit: queue message');
2573 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2574 intval($contact['id']),
2575 dbesc(NETWORK_DIASPORA),
2577 intval($public_batch)
2580 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2583 // queue message for redelivery
2584 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2589 return(($return_code) ? $return_code : (-1));