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['wall'] = $parent_item['wall'];
1240 $datarray['gravity'] = GRAVITY_COMMENT;
1241 $datarray['guid'] = $guid;
1242 $datarray['uri'] = $message_id;
1243 $datarray['parent-uri'] = $parent_item['uri'];
1245 // No timestamps for comments? OK, we'll the use current time.
1246 $datarray['created'] = $datarray['edited'] = datetime_convert();
1247 $datarray['private'] = $parent_item['private'];
1249 $datarray['owner-name'] = $parent_item['owner-name'];
1250 $datarray['owner-link'] = $parent_item['owner-link'];
1251 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1253 $datarray['author-name'] = $person['name'];
1254 $datarray['author-link'] = $person['url'];
1255 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1256 $datarray['body'] = $body;
1257 $datarray['tag'] = $str_tags;
1259 // We can't be certain what the original app is if the message is relayed.
1260 if(($parent_item['origin']) && (! $parent_author_signature))
1261 $datarray['app'] = 'Diaspora';
1263 $message_id = item_store($datarray);
1266 q("update item set plink = '%s' where id = %d limit 1",
1267 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1272 if(($parent_item['origin']) && (! $parent_author_signature)) {
1273 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1274 intval($message_id),
1275 dbesc($author_signed_data),
1276 dbesc(base64_encode($author_signature)),
1277 dbesc($diaspora_handle)
1280 // if the message isn't already being relayed, notify others
1281 // the existence of parent_author_signature means the parent_author or owner
1282 // is already relaying.
1284 proc_run('php','include/notifier.php','comment',$message_id);
1287 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1288 dbesc($parent_item['uri']),
1289 intval($importer['uid'])
1292 if(count($myconv)) {
1293 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1295 foreach($myconv as $conv) {
1297 // now if we find a match, it means we're in this conversation
1299 if(! link_compare($conv['author-link'],$importer_url))
1302 require_once('include/enotify.php');
1304 $conv_parent = $conv['parent'];
1307 'type' => NOTIFY_COMMENT,
1308 'notify_flags' => $importer['notify-flags'],
1309 'language' => $importer['language'],
1310 'to_name' => $importer['username'],
1311 'to_email' => $importer['email'],
1312 'uid' => $importer['uid'],
1313 'item' => $datarray,
1314 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id,
1315 'source_name' => $datarray['author-name'],
1316 'source_link' => $datarray['author-link'],
1317 'source_photo' => $datarray['author-avatar'],
1318 'verb' => ACTIVITY_POST,
1320 'parent' => $conv_parent,
1324 // only send one notification
1334 function diaspora_conversation($importer,$xml,$msg) {
1338 $guid = notags(unxmlify($xml->guid));
1339 $subject = notags(unxmlify($xml->subject));
1340 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1341 $participant_handles = notags(unxmlify($xml->participant_handles));
1342 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1344 $parent_uri = $diaspora_handle . ':' . $guid;
1346 $messages = $xml->message;
1348 if(! count($messages)) {
1349 logger('diaspora_conversation: empty conversation');
1353 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1355 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1359 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1360 logger('diaspora_conversation: Ignoring this author.');
1364 $conversation = null;
1366 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1367 intval($importer['uid']),
1371 $conversation = $c[0];
1373 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1374 intval($importer['uid']),
1376 dbesc($diaspora_handle),
1377 dbesc(datetime_convert('UTC','UTC',$created_at)),
1378 dbesc(datetime_convert()),
1380 dbesc($participant_handles)
1383 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1384 intval($importer['uid']),
1388 $conversation = $c[0];
1390 if(! $conversation) {
1391 logger('diaspora_conversation: unable to create conversation.');
1395 foreach($messages as $mesg) {
1399 $msg_guid = notags(unxmlify($mesg->guid));
1400 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1401 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1402 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1403 $msg_text = unxmlify($mesg->text);
1404 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1405 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1406 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1407 if($msg_conversation_guid != $guid) {
1408 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1412 $body = diaspora2bb($msg_text);
1413 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1415 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1417 $author_signature = base64_decode($msg_author_signature);
1419 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1424 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1426 if(is_array($person) && x($person,'pubkey'))
1427 $key = $person['pubkey'];
1429 logger('diaspora_conversation: unable to find author details');
1434 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1435 logger('diaspora_conversation: verification failed.');
1439 if($msg_parent_author_signature) {
1440 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1442 $parent_author_signature = base64_decode($msg_parent_author_signature);
1446 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1447 logger('diaspora_conversation: owner verification failed.');
1452 $r = q("select id from mail where `uri` = '%s' limit 1",
1456 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1460 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')",
1461 intval($importer['uid']),
1463 intval($conversation['id']),
1464 dbesc($person['name']),
1465 dbesc($person['photo']),
1466 dbesc($person['url']),
1467 intval($contact['id']),
1474 dbesc($msg_created_at)
1477 q("update conv set updated = '%s' where id = %d limit 1",
1478 dbesc(datetime_convert()),
1479 intval($conversation['id'])
1482 require_once('include/enotify.php');
1484 'type' => NOTIFY_MAIL,
1485 'notify_flags' => $importer['notify-flags'],
1486 'language' => $importer['language'],
1487 'to_name' => $importer['username'],
1488 'to_email' => $importer['email'],
1489 'uid' =>$importer['importer_uid'],
1490 'item' => array('subject' => $subject, 'body' => $body),
1491 'source_name' => $person['name'],
1492 'source_link' => $person['url'],
1493 'source_photo' => $person['thumb'],
1494 'verb' => ACTIVITY_POST,
1502 function diaspora_message($importer,$xml,$msg) {
1506 $msg_guid = notags(unxmlify($xml->guid));
1507 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1508 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1509 $msg_author_signature = notags(unxmlify($xml->author_signature));
1510 $msg_text = unxmlify($xml->text);
1511 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1512 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1513 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1515 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1517 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1519 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1523 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1524 logger('diaspora_message: Ignoring this author.');
1528 $conversation = null;
1530 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1531 intval($importer['uid']),
1532 dbesc($msg_conversation_guid)
1535 $conversation = $c[0];
1537 logger('diaspora_message: conversation not available.');
1543 $body = diaspora2bb($msg_text);
1544 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1546 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1549 $author_signature = base64_decode($msg_author_signature);
1551 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1552 if(is_array($person) && x($person,'pubkey'))
1553 $key = $person['pubkey'];
1555 logger('diaspora_message: unable to find author details');
1559 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1560 logger('diaspora_message: verification failed.');
1564 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1566 intval($importer['uid'])
1569 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1573 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')",
1574 intval($importer['uid']),
1576 intval($conversation['id']),
1577 dbesc($person['name']),
1578 dbesc($person['photo']),
1579 dbesc($person['url']),
1580 intval($contact['id']),
1581 dbesc($conversation['subject']),
1587 dbesc($msg_created_at)
1590 q("update conv set updated = '%s' where id = %d limit 1",
1591 dbesc(datetime_convert()),
1592 intval($conversation['id'])
1599 function diaspora_photo($importer,$xml,$msg) {
1603 logger('diaspora_photo: init',LOGGER_DEBUG);
1605 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1607 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1609 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1611 $guid = notags(unxmlify($xml->guid));
1613 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1615 $public = notags(unxmlify($xml->public));
1617 $created_at = notags(unxmlify($xml_created_at));
1619 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1621 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1623 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1627 if(! diaspora_post_allow($importer,$contact)) {
1628 logger('diaspora_photo: Ignoring this author.');
1632 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1633 intval($importer['uid']),
1634 dbesc($status_message_guid)
1637 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1641 $parent_item = $r[0];
1643 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1645 $link_text = scale_external_images($link_text, true,
1646 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1648 if(strpos($parent_item['body'],$link_text) === false) {
1649 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1650 dbesc($link_text . $parent_item['body']),
1651 intval($parent_item['id']),
1652 intval($parent_item['uid'])
1662 function diaspora_like($importer,$xml,$msg) {
1665 $guid = notags(unxmlify($xml->guid));
1666 $parent_guid = notags(unxmlify($xml->parent_guid));
1667 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1668 $target_type = notags(unxmlify($xml->target_type));
1669 $positive = notags(unxmlify($xml->positive));
1670 $author_signature = notags(unxmlify($xml->author_signature));
1672 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1674 // likes on comments not supported here and likes on photos not supported by Diaspora
1676 if($target_type !== 'Post')
1679 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1681 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1685 if(! diaspora_post_allow($importer,$contact)) {
1686 logger('diaspora_like: Ignoring this author.');
1690 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1691 intval($importer['uid']),
1695 logger('diaspora_like: parent item not found: ' . $guid);
1699 $parent_item = $r[0];
1701 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1702 intval($importer['uid']),
1706 if($positive === 'true') {
1707 logger('diaspora_like: duplicate like: ' . $guid);
1710 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1711 // It looks like "RelayableRetractions" are used for "unlike" instead
1712 if($positive === 'false') {
1713 logger('diaspora_like: received a like with positive set to "false"...ignoring');
1714 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1715 intval($r[0]['id']),
1716 intval($importer['uid'])
1718 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1719 // send notification via proc_run()
1723 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1724 // It looks like "RelayableRetractions" are used for "unlike" instead
1725 if($positive === 'false') {
1726 logger('diaspora_like: received a like with positive set to "false"');
1727 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1732 /* How Diaspora performs "like" signature checking:
1734 - If an item has been sent by the like author to the top-level post owner to relay on
1735 to the rest of the contacts on the top-level post, the top-level post owner should check
1736 the author_signature, then create a parent_author_signature before relaying the like on
1737 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1738 check only the parent_author_signature. Basically, they trust that the top-level post
1739 owner has already verified the authenticity of anything he/she sends out
1740 - In either case, the signature that get checked is the signature created by the person
1744 $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1747 if($parent_author_signature) {
1748 // If a parent_author_signature exists, then we've received the like
1749 // relayed from the top-level post owner. There's no need to check the
1750 // author_signature if the parent_author_signature is valid
1752 $parent_author_signature = base64_decode($parent_author_signature);
1754 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1755 logger('diaspora_like: top-level owner verification failed.');
1760 // If there's no parent_author_signature, then we've received the like
1761 // from the like creator. In that case, the person is "like"ing
1762 // our post, so he/she must be a contact of ours and his/her public key
1763 // should be in $msg['key']
1765 $author_signature = base64_decode($author_signature);
1767 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1768 logger('diaspora_like: like creator verification failed.');
1773 // Phew! Everything checks out. Now create an item.
1775 // Find the original comment author information.
1776 // We need this to make sure we display the comment author
1777 // information (name and avatar) correctly.
1778 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1781 $person = find_diaspora_person_by_handle($diaspora_handle);
1783 if(! is_array($person)) {
1784 logger('diaspora_like: unable to find author details');
1789 $uri = $diaspora_handle . ':' . $guid;
1791 $activity = ACTIVITY_LIKE;
1792 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1793 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1794 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1795 $body = $parent_item['body'];
1800 <type>$objtype</type>
1802 <id>{$parent_item['uri']}</id>
1805 <content>$body</content>
1808 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1813 $arr['uid'] = $importer['uid'];
1814 $arr['guid'] = $guid;
1815 $arr['contact-id'] = $contact['id'];
1816 $arr['type'] = 'activity';
1817 $arr['wall'] = $parent_item['wall'];
1818 $arr['gravity'] = GRAVITY_LIKE;
1819 $arr['parent'] = $parent_item['id'];
1820 $arr['parent-uri'] = $parent_item['uri'];
1822 $arr['owner-name'] = $parent_item['name'];
1823 $arr['owner-link'] = $parent_item['url'];
1824 $arr['owner-avatar'] = $parent_item['thumb'];
1826 $arr['author-name'] = $person['name'];
1827 $arr['author-link'] = $person['url'];
1828 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1830 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1831 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1832 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1833 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1835 $arr['app'] = 'Diaspora';
1837 $arr['private'] = $parent_item['private'];
1838 $arr['verb'] = $activity;
1839 $arr['object-type'] = $objtype;
1840 $arr['object'] = $obj;
1841 $arr['visible'] = 1;
1843 $arr['last-child'] = 0;
1845 $message_id = item_store($arr);
1849 q("update item set plink = '%s' where id = %d limit 1",
1850 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1855 if(! $parent_author_signature) {
1856 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1857 intval($message_id),
1858 dbesc($author_signed_data),
1859 dbesc(base64_encode($author_signature)),
1860 dbesc($diaspora_handle)
1864 // if the message isn't already being relayed, notify others
1865 // the existence of parent_author_signature means the parent_author or owner
1866 // is already relaying. The parent_item['origin'] indicates the message was created on our system
1868 if(($parent_item['origin']) && (! $parent_author_signature))
1869 proc_run('php','include/notifier.php','comment',$message_id);
1874 function diaspora_retraction($importer,$xml) {
1877 $guid = notags(unxmlify($xml->guid));
1878 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1879 $type = notags(unxmlify($xml->type));
1881 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1885 if($type === 'Person') {
1886 require_once('include/Contact.php');
1887 contact_remove($contact['id']);
1889 elseif($type === 'Post') {
1890 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1892 intval($importer['uid'])
1895 if(link_compare($r[0]['author-link'],$contact['url'])) {
1896 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1897 dbesc(datetime_convert()),
1908 function diaspora_signed_retraction($importer,$xml,$msg) {
1911 $guid = notags(unxmlify($xml->target_guid));
1912 $diaspora_handle = notags(unxmlify($xml->sender_handle));
1913 $type = notags(unxmlify($xml->target_type));
1914 $sig = notags(unxmlify($xml->target_author_signature));
1916 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1918 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1920 logger('diaspora_signed_retraction: no contact');
1925 $signed_data = $guid . ';' . $type ;
1928 /* How Diaspora performs relayable_retraction signature checking:
1930 - If an item has been sent by the item author to the top-level post owner to relay on
1931 to the rest of the contacts on the top-level post, the top-level post owner checks
1932 the author_signature, then creates a parent_author_signature before relaying the item on
1933 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1934 check only the parent_author_signature. Basically, they trust that the top-level post
1935 owner has already verified the authenticity of anything he/she sends out
1936 - In either case, the signature that get checked is the signature created by the person
1940 if($parent_author_signature) {
1942 $parent_author_signature = base64_decode($parent_author_signature);
1944 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1945 logger('diaspora_signed_retraction: top-level post owner verification failed');
1952 $sig_decode = base64_decode($sig);
1954 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
1955 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
1960 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
1961 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1963 intval($importer['uid'])
1966 if(link_compare($r[0]['author-link'],$contact['url'])) {
1967 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d limit 1",
1968 dbesc(datetime_convert()),
1969 dbesc(datetime_convert()),
1973 // Now check if the retraction needs to be relayed by us
1975 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
1976 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
1977 // The only item with `parent` and `id` as the parent id is the parent item.
1978 $p = q("select origin from item where parent = %d and id = %d limit 1",
1983 if(($p[0]['origin']) && (! $parent_author_signature)) {
1984 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1986 dbesc($signed_data),
1988 dbesc($diaspora_handle)
1991 // the existence of parent_author_signature would have meant the parent_author or owner
1992 // is already relaying.
1993 logger('diaspora_signed_retraction: relaying relayable_retraction');
1995 proc_run('php','include/notifier.php','relayable_retraction',$r[0]['id']);
2002 logger('diaspora_signed_retraction: unknown type: ' . $type);
2008 function diaspora_profile($importer,$xml,$msg) {
2011 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2014 if($diaspora_handle != $msg['author']) {
2015 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2019 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2023 if($contact['blocked']) {
2024 logger('diaspora_post: Ignoring this author.');
2028 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2029 $image_url = unxmlify($xml->image_url);
2030 $birthday = unxmlify($xml->birthday);
2032 $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2033 intval($importer['uid']),
2034 intval($contact['id'])
2036 $oldphotos = ((count($r)) ? $r : null);
2038 require_once('include/Photo.php');
2040 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2042 // Generic birthday. We don't know the timezone. The year is irrelevant.
2044 $birthday = str_replace('1000','1901',$birthday);
2046 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2048 // this is to prevent multiple birthday notifications in a single year
2049 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2051 if(substr($birthday,5) === substr($contact['bd'],5))
2052 $birthday = $contact['bd'];
2054 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2055 // Not doing this currently because D* protocol is scheduled for revision soon.
2057 $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",
2059 dbesc(datetime_convert()),
2063 dbesc(datetime_convert()),
2065 intval($contact['id']),
2066 intval($importer['uid'])
2071 foreach($oldphotos as $ph) {
2072 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2073 intval($importer['uid']),
2074 intval($contact['id']),
2075 dbesc($ph['resource-id'])
2085 function diaspora_share($me,$contact) {
2087 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2088 $theiraddr = $contact['addr'];
2090 $tpl = get_markup_template('diaspora_share.tpl');
2091 $msg = replace_macros($tpl, array(
2092 '$sender' => $myaddr,
2093 '$recipient' => $theiraddr
2096 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2097 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2099 return(diaspora_transmit($owner,$contact,$slap, false));
2102 function diaspora_unshare($me,$contact) {
2105 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2107 $tpl = get_markup_template('diaspora_retract.tpl');
2108 $msg = replace_macros($tpl, array(
2109 '$guid' => $me['guid'],
2110 '$type' => 'Person',
2111 '$handle' => $myaddr
2114 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2115 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2117 return(diaspora_transmit($owner,$contact,$slap, false));
2123 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2126 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2127 $theiraddr = $contact['addr'];
2131 $title = $item['title'];
2132 $body = $item['body'];
2135 // We're trying to match Diaspora's split message/photo protocol but
2136 // all the photos are displayed on D* as links and not img's - even
2137 // though we're sending pretty much precisely what they send us when
2138 // doing the same operation.
2139 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2140 // which seems to get through intact.
2142 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2144 foreach($matches as $mtch) {
2146 $detail['str'] = $mtch[0];
2147 $detail['path'] = dirname($mtch[1]) . '/';
2148 $detail['file'] = basename($mtch[1]);
2149 $detail['guid'] = $item['guid'];
2150 $detail['handle'] = $myaddr;
2151 $images[] = $detail;
2152 $body = str_replace($detail['str'],$mtch[1],$body);
2157 $body = preg_replace('/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $body);
2159 //if(strlen($title))
2160 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2162 // convert to markdown
2163 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2164 //$body = bb2diaspora($body);
2168 $body = "## ".html_entity_decode($title)."\n\n".$body;
2170 if($item['attach']) {
2171 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2173 $body .= "\n" . t('Attachments:') . "\n";
2174 foreach($matches as $mtch) {
2175 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2181 $public = (($item['private']) ? 'false' : 'true');
2183 require_once('include/datetime.php');
2184 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2186 $tpl = get_markup_template('diaspora_post.tpl');
2187 $msg = replace_macros($tpl, array(
2189 '$guid' => $item['guid'],
2190 '$handle' => xmlify($myaddr),
2191 '$public' => $public,
2192 '$created' => $created
2195 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
2197 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2198 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2200 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2202 if(count($images)) {
2203 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2206 return $return_code;
2210 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2212 if(! count($images))
2214 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2216 $tpl = get_markup_template('diaspora_photo.tpl');
2217 foreach($images as $image) {
2218 if(! stristr($image['path'],$mysite))
2220 $resource = str_replace('.jpg','',$image['file']);
2221 $resource = substr($resource,0,strpos($resource,'-'));
2223 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2225 intval($owner['uid'])
2229 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2230 $msg = replace_macros($tpl,array(
2231 '$path' => xmlify($image['path']),
2232 '$filename' => xmlify($image['file']),
2233 '$msg_guid' => xmlify($image['guid']),
2234 '$guid' => xmlify($r[0]['guid']),
2235 '$handle' => xmlify($image['handle']),
2236 '$public' => xmlify($public),
2237 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2241 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2242 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2243 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2245 diaspora_transmit($owner,$contact,$slap,$public_batch);
2250 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2253 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2254 // $theiraddr = $contact['addr'];
2256 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2257 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2258 // The only item with `parent` and `id` as the parent id is the parent item.
2259 $p = q("select guid from item where parent = %d and id = %d limit 1",
2260 intval($item['parent']),
2261 intval($item['parent'])
2264 $parent_guid = $p[0]['guid'];
2268 if($item['verb'] === ACTIVITY_LIKE) {
2269 $tpl = get_markup_template('diaspora_like.tpl');
2271 $target_type = 'Post';
2272 // $positive = (($item['deleted']) ? 'false' : 'true');
2275 if(($item['deleted']))
2276 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2279 $tpl = get_markup_template('diaspora_comment.tpl');
2283 $text = html_entity_decode(bb2diaspora($item['body']));
2288 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
2290 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
2292 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2294 $msg = replace_macros($tpl,array(
2295 '$guid' => xmlify($item['guid']),
2296 '$parent_guid' => xmlify($parent_guid),
2297 '$target_type' =>xmlify($target_type),
2298 '$authorsig' => xmlify($authorsig),
2299 '$body' => xmlify($text),
2300 '$positive' => xmlify($positive),
2301 '$handle' => xmlify($myaddr)
2304 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2306 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2307 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2309 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2313 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2317 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2318 // $theiraddr = $contact['addr'];
2320 $body = $item['body'];
2321 $text = html_entity_decode(bb2diaspora($body));
2324 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2325 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2326 // The only item with `parent` and `id` as the parent id is the parent item.
2327 $p = q("select guid from item where parent = %d and id = %d limit 1",
2328 intval($item['parent']),
2329 intval($item['parent'])
2332 $parent_guid = $p[0]['guid'];
2337 $relay_retract = false;
2338 $sql_sign_id = 'iid';
2339 if( $item['deleted']) {
2340 $relay_retract = true;
2342 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2344 $sql_sign_id = 'retract_iid';
2345 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2347 elseif($item['verb'] === ACTIVITY_LIKE) {
2350 $target_type = 'Post';
2351 // $positive = (($item['deleted']) ? 'false' : 'true');
2354 $tpl = get_markup_template('diaspora_like_relay.tpl');
2356 else { // item is a comment
2357 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2361 // fetch the original signature if the relayable was created by a Diaspora
2362 // or DFRN user. Relayables for other networks are not supported.
2364 $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2369 $signed_text = $orig_sign['signed_text'];
2370 $authorsig = $orig_sign['signature'];
2371 $handle = $orig_sign['signer'];
2375 // Author signature information (for likes, comments, and retractions of likes or comments,
2376 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2377 // function is called
2378 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2383 $sender_signed_text = $item['guid'] . ';' . $target_type;
2385 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $handle;
2387 $sender_signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $handle;
2389 // Sign the relayable with the top-level owner's signature
2391 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2392 // stored in the database, because that provides the best chance that Diaspora will
2393 // be able to reconstruct the signed text the same way we did. This is particularly a
2394 // concern for the comment, whose signed text includes the text of the comment. The
2395 // smallest change in the text of the comment, including removing whitespace, will
2396 // make the signature verification fail. Since we translate from BB code to Diaspora's
2397 // markup at the top of this function, which is AFTER we placed the original $signed_text
2398 // in the database, it's hazardous to trust the original $signed_text.
2400 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2402 $msg = replace_macros($tpl,array(
2403 '$guid' => xmlify($item['guid']),
2404 '$parent_guid' => xmlify($parent_guid),
2405 '$target_type' =>xmlify($target_type),
2406 '$authorsig' => xmlify($authorsig),
2407 '$parentsig' => xmlify($parentauthorsig),
2408 '$body' => xmlify($text),
2409 '$positive' => xmlify($positive),
2410 '$handle' => xmlify($handle)
2413 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2416 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2417 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2419 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2425 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2428 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2430 // Check whether the retraction is for a top-level post or whether it's a relayable
2431 if( $item['uri'] !== $item['parent-uri'] ) {
2433 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2434 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2438 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2439 $target_type = 'StatusMessage';
2442 $signed_text = $item['guid'] . ';' . $target_type;
2444 $msg = replace_macros($tpl, array(
2445 '$guid' => xmlify($item['guid']),
2446 '$type' => xmlify($target_type),
2447 '$handle' => xmlify($myaddr),
2448 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2451 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2452 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2454 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2457 function diaspora_send_mail($item,$owner,$contact) {
2460 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2462 $r = q("select * from conv where id = %d and uid = %d limit 1",
2463 intval($item['convid']),
2464 intval($item['uid'])
2468 logger('diaspora_send_mail: conversation not found.');
2474 'guid' => xmlify($cnv['guid']),
2475 'subject' => xmlify($cnv['subject']),
2476 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2477 'diaspora_handle' => xmlify($cnv['creator']),
2478 'participant_handles' => xmlify($cnv['recips'])
2481 $body = bb2diaspora($item['body']);
2482 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2484 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2485 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2487 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2490 'guid' => xmlify($item['guid']),
2491 'parent_guid' => xmlify($cnv['guid']),
2492 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2493 'author_signature' => xmlify($sig),
2494 'text' => xmlify($body),
2495 'created_at' => xmlify($created),
2496 'diaspora_handle' => xmlify($myaddr),
2497 'conversation_guid' => xmlify($cnv['guid'])
2500 if($item['reply']) {
2501 $tpl = get_markup_template('diaspora_message.tpl');
2502 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2505 $conv['messages'] = array($msg);
2506 $tpl = get_markup_template('diaspora_conversation.tpl');
2507 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2510 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2512 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2513 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2515 return(diaspora_transmit($owner,$contact,$slap,false));
2520 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2522 $enabled = intval(get_config('system','diaspora_enabled'));
2528 $logid = random_string(4);
2529 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2531 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2535 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2537 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2541 if(! intval(get_config('system','diaspora_test'))) {
2542 post_url($dest_url . '/', $slap);
2543 $return_code = $a->get_curl_code();
2546 logger('diaspora_transmit: test_mode');
2551 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2553 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2554 logger('diaspora_transmit: queue message');
2556 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2557 intval($contact['id']),
2558 dbesc(NETWORK_DIASPORA),
2560 intval($public_batch)
2563 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2566 // queue message for redelivery
2567 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2572 return(($return_code) ? $return_code : (-1));