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');
10 function diaspora_add_page_info($url) {
11 require_once("mod/parse_url.php");
12 $data = parseurl_getsiteinfo($url, true);
14 logger('diaspora_add_page_info: fetch page info for '.$url.' '.print_r($data, true), LOGGER_DATA);
16 if (($data["type"] != "link") OR ($data["title"] == $url))
19 if (is_string($data["title"]))
20 $text .= "[bookmark=".$url."]".trim($data["title"])."[/bookmark]";
22 if (sizeof($data["images"]) > 0) {
23 $imagedata = $data["images"][0];
24 $text .= '[img]'.$imagedata["src"].'[/img]';
27 if (is_string($data["text"]))
28 $text .= "[quote]".$data["text"]."[/quote]";
30 return("\n[class=type-".$data["type"]."]".$text."[/class]");
33 function diaspora_add_page_info_to_body($body) {
35 logger('diaspora_add_page_info_to_body: fetch page info for body '.$body, LOGGER_DATA);
37 $URLSearchString = "^\[\]";
39 // Adding these spaces is a quick hack due to my problems with regular expressions :)
40 preg_match("/[^@#]\[url\]([$URLSearchString]*)\[\/url\]/ism", " ".$body, $matches);
43 preg_match("/[^@#]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " ".$body, $matches);
46 $body .= diaspora_add_page_info($matches[1]);
51 function diaspora_dispatch_public($msg) {
53 $enabled = intval(get_config('system','diaspora_enabled'));
55 logger('mod-diaspora: disabled');
59 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
60 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
61 AND `account_expired` = 0 AND `account_removed` = 0 ",
62 dbesc(NETWORK_DIASPORA),
67 logger('diaspora_public: delivering to: ' . $rr['username']);
68 diaspora_dispatch($rr,$msg);
72 logger('diaspora_public: no subscribers');
77 function diaspora_dispatch($importer,$msg,$attempt=1) {
81 $enabled = intval(get_config('system','diaspora_enabled'));
83 logger('mod-diaspora: disabled');
87 // php doesn't like dashes in variable names
89 $msg['message'] = str_replace(
90 array('<activity_streams-photo>','</activity_streams-photo>'),
91 array('<asphoto>','</asphoto>'),
95 $parsed_xml = parse_xml_string($msg['message'],false);
97 $xmlbase = $parsed_xml->post;
99 logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
102 if($xmlbase->request) {
103 $ret = diaspora_request($importer,$xmlbase->request);
105 elseif($xmlbase->status_message) {
106 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
108 elseif($xmlbase->profile) {
109 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
111 elseif($xmlbase->comment) {
112 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
114 elseif($xmlbase->like) {
115 $ret = diaspora_like($importer,$xmlbase->like,$msg);
117 elseif($xmlbase->asphoto) {
118 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
120 elseif($xmlbase->reshare) {
121 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
123 elseif($xmlbase->retraction) {
124 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
126 elseif($xmlbase->signed_retraction) {
127 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
129 elseif($xmlbase->relayable_retraction) {
130 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
132 elseif($xmlbase->photo) {
133 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
135 elseif($xmlbase->conversation) {
136 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
138 elseif($xmlbase->message) {
139 $ret = diaspora_message($importer,$xmlbase->message,$msg);
142 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
147 function diaspora_handle_from_contact($contact_id) {
150 logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
152 $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
158 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
160 if($contact['network'] === NETWORK_DIASPORA) {
161 $handle = $contact['addr'];
163 // logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
165 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
166 $baseurl_start = strpos($contact['url'],'://') + 3;
167 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
168 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
169 $handle = $contact['nick'] . '@' . $baseurl;
171 // logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
178 function diaspora_get_contact_by_handle($uid,$handle) {
179 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
180 dbesc(NETWORK_DIASPORA),
187 $handle_parts = explode("@", $handle);
188 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
189 $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
200 function find_diaspora_person_by_handle($handle) {
210 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
211 dbesc(NETWORK_DIASPORA),
216 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
218 // update record occasionally so it doesn't get stale
219 $d = strtotime($person['updated'] . ' +00:00');
220 if($d < strtotime('now - 14 days'))
225 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
227 // If the person isn't in our 'fcontact' table, or if he/she is but
228 // his/her information hasn't been updated for more than 14 days, then
229 // we want to fetch the person's information from the remote server.
231 // Note that $person isn't changed by this block of code unless the
232 // person's information has been successfully fetched from the remote
233 // server. So if $person was 'false' to begin with (because he/she wasn't
234 // in the local cache), it'll stay false, and if $person held the local
235 // cache information to begin with, it'll keep that information. That way
236 // if there's a problem with the remote fetch, we can at least use our
237 // cached information--it's better than nothing.
239 if((! $person) || ($update)) {
240 // Lock the function to prevent race conditions if multiple items
241 // come in at the same time from a person who doesn't exist in
244 // Don't loop forever. On the last loop, try to create the contact
245 // whether the function is locked or not. Maybe the locking thread
246 // has died or something. At any rate, a duplicate in 'fcontact'
247 // is a much smaller problem than a deadlocked thread
248 $got_lock = lock_function('find_diaspora_person_by_handle', false);
249 if(($endlessloop + 1) >= $maxloops)
253 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
254 require_once('include/Scrape.php');
255 $r = probe_url($handle, PROBE_DIASPORA);
257 // Note that Friendica contacts can return a "Diaspora person"
258 // if Diaspora connectivity is enabled on their server
259 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
260 add_fcontact($r,$update);
264 unlock_function('find_diaspora_person_by_handle');
267 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
269 block_on_function_lock('find_diaspora_person_by_handle');
272 } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
273 // We need to try again if the person wasn't in 'fcontact' but the function was locked.
274 // The fact that the function was locked may mean that another process was creating the
275 // person's record. It could also mean another process was creating or updating an unrelated
278 // At any rate, we need to keep trying until we've either got the person or had a chance to
279 // try to fetch his/her remote information. But we don't want to block on locking the
280 // function, because if the other process is creating the record, then when we acquire the lock
281 // we'll dive right into creating another, duplicate record. We DO want to at least wait
282 // until the lock is released, so we don't flood the database with requests.
284 // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
285 // we do have some information for the person
291 function get_diaspora_key($uri) {
292 logger('Fetching diaspora key for: ' . $uri);
294 $r = find_diaspora_person_by_handle($uri);
301 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
304 logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
307 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
309 // $b64_data = base64_encode($msg);
310 // $b64url_data = base64url_encode($b64_data);
312 $b64url_data = base64url_encode($msg);
314 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
316 $type = 'application/xml';
317 $encoding = 'base64url';
320 $signable_data = $data . '.' . base64url_encode($type) . '.'
321 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
323 $signature = rsa_sign($signable_data,$prvkey);
324 $sig = base64url_encode($signature);
327 <?xml version='1.0' encoding='UTF-8'?>
328 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
330 <author_id>$handle</author_id>
333 <me:encoding>base64url</me:encoding>
334 <me:alg>RSA-SHA256</me:alg>
335 <me:data type="application/xml">$data</me:data>
336 <me:sig>$sig</me:sig>
341 logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
349 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
353 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
355 logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
357 // without a public key nothing will work
360 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
364 $inner_aes_key = random_string(32);
365 $b_inner_aes_key = base64_encode($inner_aes_key);
366 $inner_iv = random_string(16);
367 $b_inner_iv = base64_encode($inner_iv);
369 $outer_aes_key = random_string(32);
370 $b_outer_aes_key = base64_encode($outer_aes_key);
371 $outer_iv = random_string(16);
372 $b_outer_iv = base64_encode($outer_iv);
374 $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
376 $padded_data = pkcs5_pad($msg,16);
377 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
379 $b64_data = base64_encode($inner_encrypted);
382 $b64url_data = base64url_encode($b64_data);
383 $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
385 $type = 'application/xml';
386 $encoding = 'base64url';
389 $signable_data = $data . '.' . base64url_encode($type) . '.'
390 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
392 $signature = rsa_sign($signable_data,$prvkey);
393 $sig = base64url_encode($signature);
395 $decrypted_header = <<< EOT
398 <aes_key>$b_inner_aes_key</aes_key>
399 <author_id>$handle</author_id>
403 $decrypted_header = pkcs5_pad($decrypted_header,16);
405 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
407 $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
409 $encrypted_outer_key_bundle = '';
410 openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
412 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
414 logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
416 $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle),
417 'ciphertext' => base64_encode($ciphertext)));
418 $cipher_json = base64_encode($encrypted_header_json_object);
420 $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
423 <?xml version='1.0' encoding='UTF-8'?>
424 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
427 <me:encoding>base64url</me:encoding>
428 <me:alg>RSA-SHA256</me:alg>
429 <me:data type="application/xml">$data</me:data>
430 <me:sig>$sig</me:sig>
435 logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
442 * diaspora_decode($importer,$xml)
443 * array $importer -> from user table
444 * string $xml -> urldecoded Diaspora salmon
447 * 'message' -> decoded Diaspora XML message
448 * 'author' -> author diaspora handle
449 * 'key' -> author public key (converted to pkcs#8)
451 * Author and key are used elsewhere to save a lookup for verifying replies and likes
455 function diaspora_decode($importer,$xml) {
458 $basedom = parse_xml_string($xml);
460 $children = $basedom->children('https://joindiaspora.com/protocol');
462 if($children->header) {
464 $author_link = str_replace('acct:','',$children->header->author_id);
468 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
470 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
471 $ciphertext = base64_decode($encrypted_header->ciphertext);
473 $outer_key_bundle = '';
474 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
476 $j_outer_key_bundle = json_decode($outer_key_bundle);
478 $outer_iv = base64_decode($j_outer_key_bundle->iv);
479 $outer_key = base64_decode($j_outer_key_bundle->key);
481 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
484 $decrypted = pkcs5_unpad($decrypted);
487 * $decrypted now contains something like
490 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
491 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
496 * <name>Ryan Hughes</name>
497 * <uri>acct:galaxor@diaspora.pirateship.org</uri>
502 * <author_id>galaxor@diaspora.priateship.org</author_id>
506 * </decrypted_header>
509 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
510 $idom = parse_xml_string($decrypted,false);
512 $inner_iv = base64_decode($idom->iv);
513 $inner_aes_key = base64_decode($idom->aes_key);
515 $author_link = str_replace('acct:','',$idom->author_id);
519 $dom = $basedom->children(NAMESPACE_SALMON_ME);
521 // figure out where in the DOM tree our data is hiding
523 if($dom->provenance->data)
524 $base = $dom->provenance;
525 elseif($dom->env->data)
531 logger('mod-diaspora: unable to locate salmon data in xml ');
532 http_status_exit(400);
536 // Stash the signature away for now. We have to find their key or it won't be good for anything.
537 $signature = base64url_decode($base->sig);
541 // strip whitespace so our data element will return to one big base64 blob
542 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
545 // stash away some other stuff for later
547 $type = $base->data[0]->attributes()->type[0];
548 $keyhash = $base->sig[0]->attributes()->keyhash[0];
549 $encoding = $base->encoding;
553 $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
557 $data = base64url_decode($data);
561 $inner_decrypted = $data;
565 // Decode the encrypted blob
567 $inner_encrypted = base64_decode($data);
568 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
569 $inner_decrypted = pkcs5_unpad($inner_decrypted);
573 logger('mod-diaspora: Could not retrieve author URI.');
574 http_status_exit(400);
577 // Once we have the author URI, go to the web and try to find their public key
578 // (first this will look it up locally if it is in the fcontact cache)
579 // This will also convert diaspora public key from pkcs#1 to pkcs#8
581 logger('mod-diaspora: Fetching key for ' . $author_link );
582 $key = get_diaspora_key($author_link);
585 logger('mod-diaspora: Could not retrieve author key.');
586 http_status_exit(400);
589 $verify = rsa_verify($signed_data,$signature,$key);
592 logger('mod-diaspora: Message did not verify. Discarding.');
593 http_status_exit(400);
596 logger('mod-diaspora: Message verified.');
598 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
603 function diaspora_request($importer,$xml) {
607 $sender_handle = unxmlify($xml->sender_handle);
608 $recipient_handle = unxmlify($xml->recipient_handle);
610 if(! $sender_handle || ! $recipient_handle)
613 $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
617 // perhaps we were already sharing with this person. Now they're sharing with us.
618 // That makes us friends.
620 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
621 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
622 intval(CONTACT_IS_FRIEND),
623 intval($contact['id']),
624 intval($importer['uid'])
629 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
630 intval($importer['uid'])
633 if((count($r)) && (! $r[0]['hide-friends']) && (! $contact['hidden'])) {
634 require_once('include/items.php');
636 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
637 intval($importer['uid'])
640 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
642 if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
645 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
646 $arr['uid'] = $importer['uid'];
647 $arr['contact-id'] = $self[0]['id'];
649 $arr['type'] = 'wall';
652 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
653 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
654 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
655 $arr['verb'] = ACTIVITY_FRIEND;
656 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
658 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
659 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
660 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
661 $arr['body'] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
663 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
664 . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
665 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
666 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
667 $arr['object'] .= '</link></object>' . "\n";
668 $arr['last-child'] = 1;
670 $arr['allow_cid'] = $user[0]['allow_cid'];
671 $arr['allow_gid'] = $user[0]['allow_gid'];
672 $arr['deny_cid'] = $user[0]['deny_cid'];
673 $arr['deny_gid'] = $user[0]['deny_gid'];
675 $i = item_store($arr);
677 proc_run('php',"include/notifier.php","activity","$i");
686 $ret = find_diaspora_person_by_handle($sender_handle);
689 if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
690 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
694 $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
698 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
699 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
700 intval($importer['uid']),
701 dbesc($ret['network']),
705 dbesc(normalise_link($ret['url'])),
709 dbesc($ret['photo']),
710 dbesc($ret['pubkey']),
711 dbesc($ret['notify']),
717 // find the contact record we just created
719 $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
721 if(! $contact_record) {
722 logger('diaspora_request: unable to locate newly created contact record.');
726 $g = q("select def_gid from user where uid = %d limit 1",
727 intval($importer['uid'])
729 if($g && intval($g[0]['def_gid'])) {
730 require_once('include/group.php');
731 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
734 if($importer['page-flags'] == PAGE_NORMAL) {
736 $hash = random_string() . (string) time(); // Generate a confirm_key
738 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
739 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
740 intval($importer['uid']),
741 intval($contact_record['id']),
744 dbesc( t('Sharing notification from Diaspora network')),
746 dbesc(datetime_convert())
751 // automatic friend approval
753 require_once('include/Photo.php');
755 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
757 // technically they are sharing with us (CONTACT_IS_SHARING),
758 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
759 // we are going to change the relationship and make them a follower.
761 if($importer['page-flags'] == PAGE_FREELOVE)
762 $new_relation = CONTACT_IS_FRIEND;
764 $new_relation = CONTACT_IS_FOLLOWER;
766 $r = q("UPDATE `contact` SET
773 `avatar-date` = '%s',
781 intval($new_relation),
782 dbesc(datetime_convert()),
783 dbesc(datetime_convert()),
784 dbesc(datetime_convert()),
785 intval($contact_record['id'])
788 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
790 $ret = diaspora_share($u[0],$contact_record);
796 function diaspora_post_allow($importer,$contact) {
798 // perhaps we were already sharing with this person. Now they're sharing with us.
799 // That makes us friends.
800 // Normally this should have handled by getting a request - but this could get lost
801 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
802 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
803 intval(CONTACT_IS_FRIEND),
804 intval($contact['id']),
805 intval($importer['uid'])
807 $contact['rel'] = CONTACT_IS_FRIEND;
808 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
811 if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
813 if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
815 if($contact['rel'] == CONTACT_IS_FOLLOWER)
816 if($importer['page-flags'] == PAGE_COMMUNITY)
822 function diaspora_post($importer,$xml,$msg) {
825 $guid = notags(unxmlify($xml->guid));
826 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
828 if($diaspora_handle != $msg['author']) {
829 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
833 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
837 if(! diaspora_post_allow($importer,$contact)) {
838 logger('diaspora_post: Ignoring this author.');
842 $message_id = $diaspora_handle . ':' . $guid;
843 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
844 intval($importer['uid']),
849 logger('diaspora_post: message exists: ' . $guid);
853 // allocate a guid on our system - we aren't fixing any collisions.
854 // we're ignoring them
856 $g = q("select * from guid where guid = '%s' limit 1",
860 q("insert into guid ( guid ) values ( '%s' )",
865 $created = unxmlify($xml->created_at);
866 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
868 $body = diaspora2bb($xml->raw_message);
870 // Add OEmbed and other information to the body
871 $body = diaspora_add_page_info_to_body($body);
877 $tags = get_tags($body);
880 foreach($tags as $tag) {
881 if(strpos($tag,'#') === 0) {
882 if(strpos($tag,'[url='))
885 // don't link tags that are already embedded in links
887 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
889 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
892 $basetag = str_replace('_',' ',substr($tag,1));
893 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
894 if(strlen($str_tags))
896 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
902 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
904 foreach($matches as $mtch) {
905 if(strlen($str_tags))
907 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
911 $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
913 $datarray['uid'] = $importer['uid'];
914 $datarray['contact-id'] = $contact['id'];
915 $datarray['wall'] = 0;
916 $datarray['network'] = NETWORK_DIASPORA;
917 $datarray['guid'] = $guid;
918 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
919 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
920 $datarray['private'] = $private;
921 $datarray['parent'] = 0;
922 $datarray['plink'] = $plink;
923 $datarray['owner-name'] = $contact['name'];
924 $datarray['owner-link'] = $contact['url'];
925 //$datarray['owner-avatar'] = $contact['thumb'];
926 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
927 $datarray['author-name'] = $contact['name'];
928 $datarray['author-link'] = $contact['url'];
929 $datarray['author-avatar'] = $contact['thumb'];
930 $datarray['body'] = $body;
931 $datarray['tag'] = $str_tags;
932 $datarray['app'] = 'Diaspora';
934 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
936 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
938 $message_id = item_store($datarray);
941 // q("update item set plink = '%s' where id = %d",
942 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
943 // intval($message_id)
951 function diaspora_reshare($importer,$xml,$msg) {
953 logger('diaspora_reshare: init: ' . print_r($xml,true));
956 $guid = notags(unxmlify($xml->guid));
957 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
960 if($diaspora_handle != $msg['author']) {
961 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
965 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
969 if(! diaspora_post_allow($importer,$contact)) {
970 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
974 $message_id = $diaspora_handle . ':' . $guid;
975 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
976 intval($importer['uid']),
981 logger('diaspora_reshare: message exists: ' . $guid);
985 $orig_author = notags(unxmlify($xml->root_diaspora_id));
986 $orig_guid = notags(unxmlify($xml->root_guid));
988 $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
989 $orig_url = 'https://'.substr($orig_author,strpos($orig_author,'@')+1).'/posts/'.$orig_guid;
990 $x = fetch_url($source_url);
992 $x = fetch_url(str_replace('https://','http://',$source_url));
994 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
997 logger('diaspora_reshare: source: ' . $x);
999 $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1000 $source_xml = parse_xml_string($x,false);
1002 if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1003 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1004 $body = scale_external_images($body,false);
1006 elseif($source_xml->post->asphoto->image_url) {
1007 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1008 $body = scale_external_images($body);
1010 elseif($source_xml->post->status_message) {
1011 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1013 // Checking for embedded pictures
1014 if($source_xml->post->status_message->photo->remote_photo_path AND
1015 $source_xml->post->status_message->photo->remote_photo_name) {
1017 $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1018 $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1020 $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1022 logger('diaspora_reshare: embedded picture link found: '.$body, LOGGER_DEBUG);
1025 $body = scale_external_images($body);
1027 // Add OEmbed and other information to the body
1028 $body = diaspora_add_page_info_to_body($body);
1031 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1032 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
1038 // logger('diaspora_reshare: empty body: source= ' . $x);
1042 $person = find_diaspora_person_by_handle($orig_author);
1044 /*if(is_array($person) && x($person,'name') && x($person,'url'))
1045 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
1047 $details = $orig_author;
1049 $prefix = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8') . $details . "\n";*/
1052 // allocate a guid on our system - we aren't fixing any collisions.
1053 // we're ignoring them
1055 $g = q("select * from guid where guid = '%s' limit 1",
1059 q("insert into guid ( guid ) values ( '%s' )",
1064 $created = unxmlify($xml->created_at);
1065 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1067 $datarray = array();
1071 $tags = get_tags($body);
1074 foreach($tags as $tag) {
1075 if(strpos($tag,'#') === 0) {
1076 if(strpos($tag,'[url='))
1079 // don't link tags that are already embedded in links
1081 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1083 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1087 $basetag = str_replace('_',' ',substr($tag,1));
1088 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1089 if(strlen($str_tags))
1091 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1097 $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
1099 $datarray['uid'] = $importer['uid'];
1100 $datarray['contact-id'] = $contact['id'];
1101 $datarray['wall'] = 0;
1102 $datarray['network'] = NETWORK_DIASPORA;
1103 $datarray['guid'] = $guid;
1104 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1105 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1106 $datarray['private'] = $private;
1107 $datarray['parent'] = 0;
1108 $datarray['plink'] = $plink;
1109 $datarray['owner-name'] = $contact['name'];
1110 $datarray['owner-link'] = $contact['url'];
1111 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1112 if (!intval(get_config('system','wall-to-wall_share'))) {
1113 $prefix = "[share author='".str_replace(array("'", "[", "]"), array("'", "[", "]"),$person['name']).
1114 "' profile='".$person['url'].
1115 "' avatar='".((x($person,'thumb')) ? $person['thumb'] : $person['photo']).
1116 "' link='".str_replace(array("'", "[", "]"), array("'", "[", "]"),$orig_url)."']";
1117 $datarray['author-name'] = $contact['name'];
1118 $datarray['author-link'] = $contact['url'];
1119 $datarray['author-avatar'] = $contact['thumb'];
1120 $datarray['body'] = $prefix.$body."[/share]";
1122 // Let reshared messages look like wall-to-wall posts
1123 $datarray['author-name'] = $person['name'];
1124 $datarray['author-link'] = $person['url'];
1125 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1126 $datarray['body'] = $body;
1129 $datarray['tag'] = $str_tags;
1130 $datarray['app'] = 'Diaspora';
1132 // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1133 $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1135 $message_id = item_store($datarray);
1138 // q("update item set plink = '%s' where id = %d",
1139 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1140 // intval($message_id)
1149 function diaspora_asphoto($importer,$xml,$msg) {
1150 logger('diaspora_asphoto called');
1153 $guid = notags(unxmlify($xml->guid));
1154 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1156 if($diaspora_handle != $msg['author']) {
1157 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1161 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1165 if(! diaspora_post_allow($importer,$contact)) {
1166 logger('diaspora_asphoto: Ignoring this author.');
1170 $message_id = $diaspora_handle . ':' . $guid;
1171 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1172 intval($importer['uid']),
1177 logger('diaspora_asphoto: message exists: ' . $guid);
1181 // allocate a guid on our system - we aren't fixing any collisions.
1182 // we're ignoring them
1184 $g = q("select * from guid where guid = '%s' limit 1",
1188 q("insert into guid ( guid ) values ( '%s' )",
1193 $created = unxmlify($xml->created_at);
1194 $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1196 if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1197 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1198 $body = scale_external_images($body,false);
1200 elseif($xml->image_url) {
1201 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1202 $body = scale_external_images($body);
1205 logger('diaspora_asphoto: no photo url found.');
1209 $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
1211 $datarray = array();
1213 $datarray['uid'] = $importer['uid'];
1214 $datarray['contact-id'] = $contact['id'];
1215 $datarray['wall'] = 0;
1216 $datarray['network'] = NETWORK_DIASPORA;
1217 $datarray['guid'] = $guid;
1218 $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1219 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1220 $datarray['private'] = $private;
1221 $datarray['parent'] = 0;
1222 $datarray['plink'] = $plink;
1223 $datarray['owner-name'] = $contact['name'];
1224 $datarray['owner-link'] = $contact['url'];
1225 //$datarray['owner-avatar'] = $contact['thumb'];
1226 $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1227 $datarray['author-name'] = $contact['name'];
1228 $datarray['author-link'] = $contact['url'];
1229 $datarray['author-avatar'] = $contact['thumb'];
1230 $datarray['body'] = $body;
1232 $datarray['app'] = 'Diaspora/Cubbi.es';
1234 $message_id = item_store($datarray);
1237 // q("update item set plink = '%s' where id = %d",
1238 // dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1239 // intval($message_id)
1252 function diaspora_comment($importer,$xml,$msg) {
1255 $guid = notags(unxmlify($xml->guid));
1256 $parent_guid = notags(unxmlify($xml->parent_guid));
1257 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1258 $target_type = notags(unxmlify($xml->target_type));
1259 $text = unxmlify($xml->text);
1260 $author_signature = notags(unxmlify($xml->author_signature));
1262 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1264 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1266 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1270 if(! diaspora_post_allow($importer,$contact)) {
1271 logger('diaspora_comment: Ignoring this author.');
1275 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1276 intval($importer['uid']),
1280 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1284 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1285 intval($importer['uid']),
1289 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1292 $parent_item = $r[0];
1295 /* How Diaspora performs comment signature checking:
1297 - If an item has been sent by the comment author to the top-level post owner to relay on
1298 to the rest of the contacts on the top-level post, the top-level post owner should check
1299 the author_signature, then create a parent_author_signature before relaying the comment on
1300 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1301 check only the parent_author_signature. Basically, they trust that the top-level post
1302 owner has already verified the authenticity of anything he/she sends out
1303 - In either case, the signature that get checked is the signature created by the person
1307 $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1310 if($parent_author_signature) {
1311 // If a parent_author_signature exists, then we've received the comment
1312 // relayed from the top-level post owner. There's no need to check the
1313 // author_signature if the parent_author_signature is valid
1315 $parent_author_signature = base64_decode($parent_author_signature);
1317 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1318 logger('diaspora_comment: top-level owner verification failed.');
1323 // If there's no parent_author_signature, then we've received the comment
1324 // from the comment creator. In that case, the person is commenting on
1325 // our post, so he/she must be a contact of ours and his/her public key
1326 // should be in $msg['key']
1328 $author_signature = base64_decode($author_signature);
1330 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1331 logger('diaspora_comment: comment author verification failed.');
1336 // Phew! Everything checks out. Now create an item.
1338 // Find the original comment author information.
1339 // We need this to make sure we display the comment author
1340 // information (name and avatar) correctly.
1341 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1344 $person = find_diaspora_person_by_handle($diaspora_handle);
1346 if(! is_array($person)) {
1347 logger('diaspora_comment: unable to find author details');
1352 $body = diaspora2bb($text);
1353 $message_id = $diaspora_handle . ':' . $guid;
1355 $datarray = array();
1359 $tags = get_tags($body);
1362 foreach($tags as $tag) {
1363 if(strpos($tag,'#') === 0) {
1364 if(strpos($tag,'[url='))
1367 // don't link tags that are already embedded in links
1369 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1371 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1375 $basetag = str_replace('_',' ',substr($tag,1));
1376 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1377 if(strlen($str_tags))
1379 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1385 $datarray['uid'] = $importer['uid'];
1386 $datarray['contact-id'] = $contact['id'];
1387 $datarray['type'] = 'remote-comment';
1388 $datarray['wall'] = $parent_item['wall'];
1389 $datarray['network'] = NETWORK_DIASPORA;
1390 $datarray['gravity'] = GRAVITY_COMMENT;
1391 $datarray['guid'] = $guid;
1392 $datarray['uri'] = $message_id;
1393 $datarray['parent-uri'] = $parent_item['uri'];
1395 // No timestamps for comments? OK, we'll the use current time.
1396 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1397 $datarray['private'] = $parent_item['private'];
1399 $datarray['owner-name'] = $parent_item['owner-name'];
1400 $datarray['owner-link'] = $parent_item['owner-link'];
1401 $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1403 $datarray['author-name'] = $person['name'];
1404 $datarray['author-link'] = $person['url'];
1405 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1406 $datarray['body'] = $body;
1407 $datarray['tag'] = $str_tags;
1409 // We can't be certain what the original app is if the message is relayed.
1410 if(($parent_item['origin']) && (! $parent_author_signature))
1411 $datarray['app'] = 'Diaspora';
1413 $message_id = item_store($datarray);
1416 q("update item set plink = '%s' where id = %d",
1417 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1422 if(($parent_item['origin']) && (! $parent_author_signature)) {
1423 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1424 intval($message_id),
1425 dbesc($signed_data),
1426 dbesc(base64_encode($author_signature)),
1427 dbesc($diaspora_handle)
1430 // if the message isn't already being relayed, notify others
1431 // the existence of parent_author_signature means the parent_author or owner
1432 // is already relaying.
1434 proc_run('php','include/notifier.php','comment-import',$message_id);
1437 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1438 dbesc($parent_item['uri']),
1439 intval($importer['uid'])
1442 if(count($myconv)) {
1443 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1445 foreach($myconv as $conv) {
1447 // now if we find a match, it means we're in this conversation
1449 if(! link_compare($conv['author-link'],$importer_url))
1452 require_once('include/enotify.php');
1454 $conv_parent = $conv['parent'];
1457 'type' => NOTIFY_COMMENT,
1458 'notify_flags' => $importer['notify-flags'],
1459 'language' => $importer['language'],
1460 'to_name' => $importer['username'],
1461 'to_email' => $importer['email'],
1462 'uid' => $importer['uid'],
1463 'item' => $datarray,
1464 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id,
1465 'source_name' => $datarray['author-name'],
1466 'source_link' => $datarray['author-link'],
1467 'source_photo' => $datarray['author-avatar'],
1468 'verb' => ACTIVITY_POST,
1470 'parent' => $conv_parent,
1471 'parent_uri' => $parent_uri
1474 // only send one notification
1484 function diaspora_conversation($importer,$xml,$msg) {
1488 $guid = notags(unxmlify($xml->guid));
1489 $subject = notags(unxmlify($xml->subject));
1490 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1491 $participant_handles = notags(unxmlify($xml->participant_handles));
1492 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1494 $parent_uri = $diaspora_handle . ':' . $guid;
1496 $messages = $xml->message;
1498 if(! count($messages)) {
1499 logger('diaspora_conversation: empty conversation');
1503 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1505 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1509 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1510 logger('diaspora_conversation: Ignoring this author.');
1514 $conversation = null;
1516 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1517 intval($importer['uid']),
1521 $conversation = $c[0];
1523 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1524 intval($importer['uid']),
1526 dbesc($diaspora_handle),
1527 dbesc(datetime_convert('UTC','UTC',$created_at)),
1528 dbesc(datetime_convert()),
1530 dbesc($participant_handles)
1533 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1534 intval($importer['uid']),
1538 $conversation = $c[0];
1540 if(! $conversation) {
1541 logger('diaspora_conversation: unable to create conversation.');
1545 foreach($messages as $mesg) {
1549 $msg_guid = notags(unxmlify($mesg->guid));
1550 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1551 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1552 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1553 $msg_text = unxmlify($mesg->text);
1554 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1555 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1556 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1557 if($msg_conversation_guid != $guid) {
1558 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1562 $body = diaspora2bb($msg_text);
1563 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1565 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1567 $author_signature = base64_decode($msg_author_signature);
1569 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1574 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1576 if(is_array($person) && x($person,'pubkey'))
1577 $key = $person['pubkey'];
1579 logger('diaspora_conversation: unable to find author details');
1584 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1585 logger('diaspora_conversation: verification failed.');
1589 if($msg_parent_author_signature) {
1590 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1592 $parent_author_signature = base64_decode($msg_parent_author_signature);
1596 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1597 logger('diaspora_conversation: owner verification failed.');
1602 $r = q("select id from mail where `uri` = '%s' limit 1",
1606 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1610 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')",
1611 intval($importer['uid']),
1613 intval($conversation['id']),
1614 dbesc($person['name']),
1615 dbesc($person['photo']),
1616 dbesc($person['url']),
1617 intval($contact['id']),
1624 dbesc($msg_created_at)
1627 q("update conv set updated = '%s' where id = %d",
1628 dbesc(datetime_convert()),
1629 intval($conversation['id'])
1632 require_once('include/enotify.php');
1634 'type' => NOTIFY_MAIL,
1635 'notify_flags' => $importer['notify-flags'],
1636 'language' => $importer['language'],
1637 'to_name' => $importer['username'],
1638 'to_email' => $importer['email'],
1639 'uid' =>$importer['importer_uid'],
1640 'item' => array('subject' => $subject, 'body' => $body),
1641 'source_name' => $person['name'],
1642 'source_link' => $person['url'],
1643 'source_photo' => $person['thumb'],
1644 'verb' => ACTIVITY_POST,
1652 function diaspora_message($importer,$xml,$msg) {
1656 $msg_guid = notags(unxmlify($xml->guid));
1657 $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1658 $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1659 $msg_author_signature = notags(unxmlify($xml->author_signature));
1660 $msg_text = unxmlify($xml->text);
1661 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1662 $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1663 $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1665 $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1667 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1669 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1673 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1674 logger('diaspora_message: Ignoring this author.');
1678 $conversation = null;
1680 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1681 intval($importer['uid']),
1682 dbesc($msg_conversation_guid)
1685 $conversation = $c[0];
1687 logger('diaspora_message: conversation not available.');
1693 $body = diaspora2bb($msg_text);
1694 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1696 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1699 $author_signature = base64_decode($msg_author_signature);
1701 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1702 if(is_array($person) && x($person,'pubkey'))
1703 $key = $person['pubkey'];
1705 logger('diaspora_message: unable to find author details');
1709 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1710 logger('diaspora_message: verification failed.');
1714 $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1716 intval($importer['uid'])
1719 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1723 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')",
1724 intval($importer['uid']),
1726 intval($conversation['id']),
1727 dbesc($person['name']),
1728 dbesc($person['photo']),
1729 dbesc($person['url']),
1730 intval($contact['id']),
1731 dbesc($conversation['subject']),
1737 dbesc($msg_created_at)
1740 q("update conv set updated = '%s' where id = %d",
1741 dbesc(datetime_convert()),
1742 intval($conversation['id'])
1749 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1753 logger('diaspora_photo: init',LOGGER_DEBUG);
1755 $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1757 $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1759 $status_message_guid = notags(unxmlify($xml->status_message_guid));
1761 $guid = notags(unxmlify($xml->guid));
1763 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1765 $public = notags(unxmlify($xml->public));
1767 $created_at = notags(unxmlify($xml_created_at));
1769 logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1771 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1773 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1777 if(! diaspora_post_allow($importer,$contact)) {
1778 logger('diaspora_photo: Ignoring this author.');
1782 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1783 intval($importer['uid']),
1784 dbesc($status_message_guid)
1788 q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1789 intval($importer['uid']),
1790 dbesc(serialize($msg)),
1791 intval($attempt + 1)
1794 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1798 $parent_item = $r[0];
1800 $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1802 $link_text = scale_external_images($link_text, true,
1803 array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1805 if(strpos($parent_item['body'],$link_text) === false) {
1806 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d",
1807 dbesc($link_text . $parent_item['body']),
1808 intval($parent_item['id']),
1809 intval($parent_item['uid'])
1819 function diaspora_like($importer,$xml,$msg) {
1822 $guid = notags(unxmlify($xml->guid));
1823 $parent_guid = notags(unxmlify($xml->parent_guid));
1824 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1825 $target_type = notags(unxmlify($xml->target_type));
1826 $positive = notags(unxmlify($xml->positive));
1827 $author_signature = notags(unxmlify($xml->author_signature));
1829 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1831 // likes on comments not supported here and likes on photos not supported by Diaspora
1833 // if($target_type !== 'Post')
1836 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1838 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1842 if(! diaspora_post_allow($importer,$contact)) {
1843 logger('diaspora_like: Ignoring this author.');
1847 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1848 intval($importer['uid']),
1852 logger('diaspora_like: parent item not found: ' . $guid);
1856 $parent_item = $r[0];
1858 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1859 intval($importer['uid']),
1863 if($positive === 'true') {
1864 logger('diaspora_like: duplicate like: ' . $guid);
1867 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1868 // It looks like "RelayableRetractions" are used for "unlike" instead
1869 if($positive === 'false') {
1870 logger('diaspora_like: received a like with positive set to "false"...ignoring');
1871 /* q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
1872 intval($r[0]['id']),
1873 intval($importer['uid'])
1875 // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1876 // send notification via proc_run()
1880 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1881 // It looks like "RelayableRetractions" are used for "unlike" instead
1882 if($positive === 'false') {
1883 logger('diaspora_like: received a like with positive set to "false"');
1884 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1889 /* How Diaspora performs "like" signature checking:
1891 - If an item has been sent by the like author to the top-level post owner to relay on
1892 to the rest of the contacts on the top-level post, the top-level post owner should check
1893 the author_signature, then create a parent_author_signature before relaying the like on
1894 - If an item has been relayed on by the top-level post owner, the contacts who receive it
1895 check only the parent_author_signature. Basically, they trust that the top-level post
1896 owner has already verified the authenticity of anything he/she sends out
1897 - In either case, the signature that get checked is the signature created by the person
1901 $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1904 if($parent_author_signature) {
1905 // If a parent_author_signature exists, then we've received the like
1906 // relayed from the top-level post owner. There's no need to check the
1907 // author_signature if the parent_author_signature is valid
1909 $parent_author_signature = base64_decode($parent_author_signature);
1911 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1912 logger('diaspora_like: top-level owner verification failed.');
1917 // If there's no parent_author_signature, then we've received the like
1918 // from the like creator. In that case, the person is "like"ing
1919 // our post, so he/she must be a contact of ours and his/her public key
1920 // should be in $msg['key']
1922 $author_signature = base64_decode($author_signature);
1924 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1925 logger('diaspora_like: like creator verification failed.');
1930 // Phew! Everything checks out. Now create an item.
1932 // Find the original comment author information.
1933 // We need this to make sure we display the comment author
1934 // information (name and avatar) correctly.
1935 if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1938 $person = find_diaspora_person_by_handle($diaspora_handle);
1940 if(! is_array($person)) {
1941 logger('diaspora_like: unable to find author details');
1946 $uri = $diaspora_handle . ':' . $guid;
1948 $activity = ACTIVITY_LIKE;
1949 $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1950 $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
1951 $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1952 $body = $parent_item['body'];
1957 <type>$objtype</type>
1959 <id>{$parent_item['uri']}</id>
1962 <content>$body</content>
1965 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1970 $arr['uid'] = $importer['uid'];
1971 $arr['guid'] = $guid;
1972 $arr['network'] = NETWORK_DIASPORA;
1973 $arr['contact-id'] = $contact['id'];
1974 $arr['type'] = 'activity';
1975 $arr['wall'] = $parent_item['wall'];
1976 $arr['gravity'] = GRAVITY_LIKE;
1977 $arr['parent'] = $parent_item['id'];
1978 $arr['parent-uri'] = $parent_item['uri'];
1980 $arr['owner-name'] = $parent_item['name'];
1981 $arr['owner-link'] = $parent_item['url'];
1982 //$arr['owner-avatar'] = $parent_item['thumb'];
1983 $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
1985 $arr['author-name'] = $person['name'];
1986 $arr['author-link'] = $person['url'];
1987 $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1989 $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1990 $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1991 $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1992 $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink );
1994 $arr['app'] = 'Diaspora';
1996 $arr['private'] = $parent_item['private'];
1997 $arr['verb'] = $activity;
1998 $arr['object-type'] = $objtype;
1999 $arr['object'] = $obj;
2000 $arr['visible'] = 1;
2002 $arr['last-child'] = 0;
2004 $message_id = item_store($arr);
2008 q("update item set plink = '%s' where id = %d",
2009 dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2014 if(! $parent_author_signature) {
2015 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2016 intval($message_id),
2017 dbesc($signed_data),
2018 dbesc(base64_encode($author_signature)),
2019 dbesc($diaspora_handle)
2023 // if the message isn't already being relayed, notify others
2024 // the existence of parent_author_signature means the parent_author or owner
2025 // is already relaying. The parent_item['origin'] indicates the message was created on our system
2027 if(($parent_item['origin']) && (! $parent_author_signature))
2028 proc_run('php','include/notifier.php','comment-import',$message_id);
2033 function diaspora_retraction($importer,$xml) {
2036 $guid = notags(unxmlify($xml->guid));
2037 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2038 $type = notags(unxmlify($xml->type));
2040 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2044 if($type === 'Person') {
2045 require_once('include/Contact.php');
2046 contact_remove($contact['id']);
2048 elseif($type === 'Post') {
2049 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2051 intval($importer['uid'])
2054 if(link_compare($r[0]['author-link'],$contact['url'])) {
2055 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2056 dbesc(datetime_convert()),
2067 function diaspora_signed_retraction($importer,$xml,$msg) {
2070 $guid = notags(unxmlify($xml->target_guid));
2071 $diaspora_handle = notags(unxmlify($xml->sender_handle));
2072 $type = notags(unxmlify($xml->target_type));
2073 $sig = notags(unxmlify($xml->target_author_signature));
2075 $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2077 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2079 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2084 $signed_data = $guid . ';' . $type ;
2087 /* How Diaspora performs relayable_retraction signature checking:
2089 - If an item has been sent by the item author to the top-level post owner to relay on
2090 to the rest of the contacts on the top-level post, the top-level post owner checks
2091 the author_signature, then creates a parent_author_signature before relaying the item on
2092 - If an item has been relayed on by the top-level post owner, the contacts who receive it
2093 check only the parent_author_signature. Basically, they trust that the top-level post
2094 owner has already verified the authenticity of anything he/she sends out
2095 - In either case, the signature that get checked is the signature created by the person
2099 if($parent_author_signature) {
2101 $parent_author_signature = base64_decode($parent_author_signature);
2103 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2104 logger('diaspora_signed_retraction: top-level post owner verification failed');
2111 $sig_decode = base64_decode($sig);
2113 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2114 logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2119 if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2120 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2122 intval($importer['uid'])
2125 if(link_compare($r[0]['author-link'],$contact['url'])) {
2126 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2127 dbesc(datetime_convert()),
2128 dbesc(datetime_convert()),
2132 // Now check if the retraction needs to be relayed by us
2134 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2135 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2136 // The only item with `parent` and `id` as the parent id is the parent item.
2137 $p = q("select origin from item where parent = %d and id = %d limit 1",
2142 if(($p[0]['origin']) && (! $parent_author_signature)) {
2143 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2145 dbesc($signed_data),
2147 dbesc($diaspora_handle)
2150 // the existence of parent_author_signature would have meant the parent_author or owner
2151 // is already relaying.
2152 logger('diaspora_signed_retraction: relaying relayable_retraction');
2154 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2161 logger('diaspora_signed_retraction: unknown type: ' . $type);
2167 function diaspora_profile($importer,$xml,$msg) {
2170 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2173 if($diaspora_handle != $msg['author']) {
2174 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2178 $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2182 if($contact['blocked']) {
2183 logger('diaspora_post: Ignoring this author.');
2187 $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2188 $image_url = unxmlify($xml->image_url);
2189 $birthday = unxmlify($xml->birthday);
2192 $handle_parts = explode("@", $diaspora_handle);
2194 $name = $handle_parts[0];
2198 if( preg_match("|^https?://|", $image_url) === 0) {
2199 $image_url = "http://" . $handle_parts[1] . $image_url;
2202 /* $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2203 intval($importer['uid']),
2204 intval($contact['id'])
2206 $oldphotos = ((count($r)) ? $r : null);*/
2208 require_once('include/Photo.php');
2210 $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2212 // Generic birthday. We don't know the timezone. The year is irrelevant.
2214 $birthday = str_replace('1000','1901',$birthday);
2216 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2218 // this is to prevent multiple birthday notifications in a single year
2219 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2221 if(substr($birthday,5) === substr($contact['bd'],5))
2222 $birthday = $contact['bd'];
2224 // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2225 // Not doing this currently because D* protocol is scheduled for revision soon.
2227 $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",
2229 dbesc(datetime_convert()),
2233 dbesc(datetime_convert()),
2235 intval($contact['id']),
2236 intval($importer['uid'])
2241 foreach($oldphotos as $ph) {
2242 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2243 intval($importer['uid']),
2244 intval($contact['id']),
2245 dbesc($ph['resource-id'])
2255 function diaspora_share($me,$contact) {
2257 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2258 $theiraddr = $contact['addr'];
2260 $tpl = get_markup_template('diaspora_share.tpl');
2261 $msg = replace_macros($tpl, array(
2262 '$sender' => $myaddr,
2263 '$recipient' => $theiraddr
2266 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2267 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2269 return(diaspora_transmit($owner,$contact,$slap, false));
2272 function diaspora_unshare($me,$contact) {
2275 $myaddr = $me['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2277 $tpl = get_markup_template('diaspora_retract.tpl');
2278 $msg = replace_macros($tpl, array(
2279 '$guid' => $me['guid'],
2280 '$type' => 'Person',
2281 '$handle' => $myaddr
2284 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2285 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2287 return(diaspora_transmit($owner,$contact,$slap, false));
2292 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2295 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2296 $theiraddr = $contact['addr'];
2300 $title = $item['title'];
2301 $body = $item['body'];
2304 // We're trying to match Diaspora's split message/photo protocol but
2305 // all the photos are displayed on D* as links and not img's - even
2306 // though we're sending pretty much precisely what they send us when
2307 // doing the same operation.
2308 // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2309 // which seems to get through intact.
2311 $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2313 foreach($matches as $mtch) {
2315 $detail['str'] = $mtch[0];
2316 $detail['path'] = dirname($mtch[1]) . '/';
2317 $detail['file'] = basename($mtch[1]);
2318 $detail['guid'] = $item['guid'];
2319 $detail['handle'] = $myaddr;
2320 $images[] = $detail;
2321 $body = str_replace($detail['str'],$mtch[1],$body);
2326 //if(strlen($title))
2327 // $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2329 // convert to markdown
2330 $body = xmlify(html_entity_decode(bb2diaspora($body)));
2331 //$body = bb2diaspora($body);
2335 $body = "## ".html_entity_decode($title)."\n\n".$body;
2337 if($item['attach']) {
2338 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2340 $body .= "\n" . t('Attachments:') . "\n";
2341 foreach($matches as $mtch) {
2342 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2348 $public = (($item['private']) ? 'false' : 'true');
2350 require_once('include/datetime.php');
2351 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2353 $tpl = get_markup_template('diaspora_post.tpl');
2354 $msg = replace_macros($tpl, array(
2356 '$guid' => $item['guid'],
2357 '$handle' => xmlify($myaddr),
2358 '$public' => $public,
2359 '$created' => $created
2362 logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
2364 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2365 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2367 $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2369 if(count($images)) {
2370 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2373 return $return_code;
2377 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2379 if(! count($images))
2381 $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2383 $tpl = get_markup_template('diaspora_photo.tpl');
2384 foreach($images as $image) {
2385 if(! stristr($image['path'],$mysite))
2387 $resource = str_replace('.jpg','',$image['file']);
2388 $resource = substr($resource,0,strpos($resource,'-'));
2390 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2392 intval($owner['uid'])
2396 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2397 $msg = replace_macros($tpl,array(
2398 '$path' => xmlify($image['path']),
2399 '$filename' => xmlify($image['file']),
2400 '$msg_guid' => xmlify($image['guid']),
2401 '$guid' => xmlify($r[0]['guid']),
2402 '$handle' => xmlify($image['handle']),
2403 '$public' => xmlify($public),
2404 '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2408 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2409 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2410 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2412 diaspora_transmit($owner,$contact,$slap,$public_batch);
2417 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2420 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2421 // $theiraddr = $contact['addr'];
2423 // Diaspora doesn't support threaded comments, but some
2424 // versions of Diaspora (i.e. Diaspora-pistos) support
2425 // likes on comments
2426 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2427 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2428 dbesc($item['thr-parent'])
2432 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2433 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2434 // The only item with `parent` and `id` as the parent id is the parent item.
2435 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2436 intval($item['parent']),
2437 intval($item['parent'])
2445 if($item['verb'] === ACTIVITY_LIKE) {
2446 $tpl = get_markup_template('diaspora_like.tpl');
2448 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2449 // $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2450 // $positive = (($item['deleted']) ? 'false' : 'true');
2453 if(($item['deleted']))
2454 logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2457 $tpl = get_markup_template('diaspora_comment.tpl');
2461 $text = html_entity_decode(bb2diaspora($item['body']));
2466 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2468 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2470 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2472 $msg = replace_macros($tpl,array(
2473 '$guid' => xmlify($item['guid']),
2474 '$parent_guid' => xmlify($parent['guid']),
2475 '$target_type' =>xmlify($target_type),
2476 '$authorsig' => xmlify($authorsig),
2477 '$body' => xmlify($text),
2478 '$positive' => xmlify($positive),
2479 '$handle' => xmlify($myaddr)
2482 logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2484 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2485 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2487 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2491 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2495 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2496 // $theiraddr = $contact['addr'];
2498 $body = $item['body'];
2499 $text = html_entity_decode(bb2diaspora($body));
2501 // Diaspora doesn't support threaded comments, but some
2502 // versions of Diaspora (i.e. Diaspora-pistos) support
2503 // likes on comments
2504 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2505 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2506 dbesc($item['thr-parent'])
2510 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2511 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2512 // The only item with `parent` and `id` as the parent id is the parent item.
2513 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2514 intval($item['parent']),
2515 intval($item['parent'])
2524 $relay_retract = false;
2525 $sql_sign_id = 'iid';
2526 if( $item['deleted']) {
2527 $relay_retract = true;
2529 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2531 $sql_sign_id = 'retract_iid';
2532 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2534 elseif($item['verb'] === ACTIVITY_LIKE) {
2537 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2538 // $positive = (($item['deleted']) ? 'false' : 'true');
2541 $tpl = get_markup_template('diaspora_like_relay.tpl');
2543 else { // item is a comment
2544 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2548 // fetch the original signature if the relayable was created by a Diaspora
2549 // or DFRN user. Relayables for other networks are not supported.
2551 /* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2556 $signed_text = $orig_sign['signed_text'];
2557 $authorsig = $orig_sign['signature'];
2558 $handle = $orig_sign['signer'];
2562 // Author signature information (for likes, comments, and retractions of likes or comments,
2563 // whether from Diaspora or Friendica) must be placed in the `sign` table before this
2564 // function is called
2565 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2569 /* Since the author signature is only checked by the parent, not by the relay recipients,
2570 * I think it may not be necessary for us to do so much work to preserve all the original
2571 * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2572 * Let's just generate that and forget about all the original author signature stuff.
2574 * Note: this might be more of an problem if we want to support likes on comments for older
2575 * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2576 * doing that, let's ignore it for now.
2578 * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2582 $handle = diaspora_handle_from_contact($item['contact-id']);
2588 $sender_signed_text = $item['guid'] . ';' . $target_type;
2590 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2592 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2594 // Sign the relayable with the top-level owner's signature
2596 // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2597 // stored in the database, because that provides the best chance that Diaspora will
2598 // be able to reconstruct the signed text the same way we did. This is particularly a
2599 // concern for the comment, whose signed text includes the text of the comment. The
2600 // smallest change in the text of the comment, including removing whitespace, will
2601 // make the signature verification fail. Since we translate from BB code to Diaspora's
2602 // markup at the top of this function, which is AFTER we placed the original $signed_text
2603 // in the database, it's hazardous to trust the original $signed_text.
2605 $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2607 $msg = replace_macros($tpl,array(
2608 '$guid' => xmlify($item['guid']),
2609 '$parent_guid' => xmlify($parent['guid']),
2610 '$target_type' =>xmlify($target_type),
2611 '$authorsig' => xmlify($authorsig),
2612 '$parentsig' => xmlify($parentauthorsig),
2613 '$body' => xmlify($text),
2614 '$positive' => xmlify($positive),
2615 '$handle' => xmlify($handle)
2618 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2621 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2622 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2624 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2630 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2633 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2635 // Check whether the retraction is for a top-level post or whether it's a relayable
2636 if( $item['uri'] !== $item['parent-uri'] ) {
2638 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2639 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2643 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2644 $target_type = 'StatusMessage';
2647 $signed_text = $item['guid'] . ';' . $target_type;
2649 $msg = replace_macros($tpl, array(
2650 '$guid' => xmlify($item['guid']),
2651 '$type' => xmlify($target_type),
2652 '$handle' => xmlify($myaddr),
2653 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2656 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2657 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2659 return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2662 function diaspora_send_mail($item,$owner,$contact) {
2665 $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2667 $r = q("select * from conv where id = %d and uid = %d limit 1",
2668 intval($item['convid']),
2669 intval($item['uid'])
2673 logger('diaspora_send_mail: conversation not found.');
2679 'guid' => xmlify($cnv['guid']),
2680 'subject' => xmlify($cnv['subject']),
2681 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2682 'diaspora_handle' => xmlify($cnv['creator']),
2683 'participant_handles' => xmlify($cnv['recips'])
2686 $body = bb2diaspora($item['body']);
2687 $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2689 $signed_text = $item['guid'] . ';' . $cnv['guid'] . ';' . $body . ';'
2690 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2692 $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2695 'guid' => xmlify($item['guid']),
2696 'parent_guid' => xmlify($cnv['guid']),
2697 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2698 'author_signature' => xmlify($sig),
2699 'text' => xmlify($body),
2700 'created_at' => xmlify($created),
2701 'diaspora_handle' => xmlify($myaddr),
2702 'conversation_guid' => xmlify($cnv['guid'])
2705 if($item['reply']) {
2706 $tpl = get_markup_template('diaspora_message.tpl');
2707 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2710 $conv['messages'] = array($msg);
2711 $tpl = get_markup_template('diaspora_conversation.tpl');
2712 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2715 logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2717 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2718 //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2720 return(diaspora_transmit($owner,$contact,$slap,false));
2725 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2727 $enabled = intval(get_config('system','diaspora_enabled'));
2733 $logid = random_string(4);
2734 $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2736 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2740 logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2742 if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2746 if (!intval(get_config('system','diaspora_test'))) {
2747 post_url($dest_url . '/', $slap);
2748 $return_code = $a->get_curl_code();
2750 logger('diaspora_transmit: test_mode');
2755 logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2757 if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2758 logger('diaspora_transmit: queue message');
2760 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2761 intval($contact['id']),
2762 dbesc(NETWORK_DIASPORA),
2764 intval($public_batch)
2767 logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2770 // queue message for redelivery
2771 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2776 return(($return_code) ? $return_code : (-1));