3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
7 require_once("include/items.php");
8 require_once("include/bb2diaspora.php");
9 require_once("include/Scrape.php");
10 require_once("include/Contact.php");
11 require_once("include/Photo.php");
12 require_once("include/socgraph.php");
13 require_once("include/group.php");
14 require_once("include/xml.php");
15 require_once("include/datetime.php");
18 * @brief This class contain functions to create and send Diaspora XML files
23 public static function relay_list() {
25 $serverdata = get_config("system", "relay_server");
26 if ($serverdata == "")
31 $servers = explode(",", $serverdata);
33 foreach($servers AS $server) {
34 $server = trim($server);
35 $batch = $server."/receive/public";
37 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
40 $addr = "relay@".str_replace("http://", "", normalise_link($server));
42 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
43 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
48 dbesc(normalise_link($server)),
50 dbesc(NETWORK_DIASPORA),
51 intval(CONTACT_IS_FOLLOWER),
52 dbesc(datetime_convert()),
53 dbesc(datetime_convert()),
54 dbesc(datetime_convert())
57 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
59 $relay[] = $relais[0];
61 $relay[] = $relais[0];
67 function repair_signature($signature, $handle = "", $level = 1) {
72 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
73 $signature = base64_decode($signature);
74 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
76 // Do a recursive call to be able to fix even multiple levels
78 $signature = self::repair_signature($signature, $handle, ++$level);
85 * @brief: Decodes incoming Diaspora message
87 * @param array $importer from user table
88 * @param string $xml urldecoded Diaspora salmon
91 * 'message' -> decoded Diaspora XML message
92 * 'author' -> author diaspora handle
93 * 'key' -> author public key (converted to pkcs#8)
95 function decode($importer, $xml) {
98 $basedom = parse_xml_string($xml);
100 if (!is_object($basedom))
103 $children = $basedom->children('https://joindiaspora.com/protocol');
105 if($children->header) {
107 $author_link = str_replace('acct:','',$children->header->author_id);
110 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
112 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
113 $ciphertext = base64_decode($encrypted_header->ciphertext);
115 $outer_key_bundle = '';
116 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
118 $j_outer_key_bundle = json_decode($outer_key_bundle);
120 $outer_iv = base64_decode($j_outer_key_bundle->iv);
121 $outer_key = base64_decode($j_outer_key_bundle->key);
123 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
126 $decrypted = pkcs5_unpad($decrypted);
129 * $decrypted now contains something like
132 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
133 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
134 * <author_id>galaxor@diaspora.priateship.org</author_id>
135 * </decrypted_header>
138 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
139 $idom = parse_xml_string($decrypted,false);
141 $inner_iv = base64_decode($idom->iv);
142 $inner_aes_key = base64_decode($idom->aes_key);
144 $author_link = str_replace('acct:','',$idom->author_id);
147 $dom = $basedom->children(NAMESPACE_SALMON_ME);
149 // figure out where in the DOM tree our data is hiding
151 if($dom->provenance->data)
152 $base = $dom->provenance;
153 elseif($dom->env->data)
159 logger('unable to locate salmon data in xml');
160 http_status_exit(400);
164 // Stash the signature away for now. We have to find their key or it won't be good for anything.
165 $signature = base64url_decode($base->sig);
169 // strip whitespace so our data element will return to one big base64 blob
170 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
173 // stash away some other stuff for later
175 $type = $base->data[0]->attributes()->type[0];
176 $keyhash = $base->sig[0]->attributes()->keyhash[0];
177 $encoding = $base->encoding;
181 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
185 $data = base64url_decode($data);
189 $inner_decrypted = $data;
192 // Decode the encrypted blob
194 $inner_encrypted = base64_decode($data);
195 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
196 $inner_decrypted = pkcs5_unpad($inner_decrypted);
200 logger('Could not retrieve author URI.');
201 http_status_exit(400);
203 // Once we have the author URI, go to the web and try to find their public key
204 // (first this will look it up locally if it is in the fcontact cache)
205 // This will also convert diaspora public key from pkcs#1 to pkcs#8
207 logger('Fetching key for '.$author_link);
208 $key = self::key($author_link);
211 logger('Could not retrieve author key.');
212 http_status_exit(400);
215 $verify = rsa_verify($signed_data,$signature,$key);
218 logger('Message did not verify. Discarding.');
219 http_status_exit(400);
222 logger('Message verified.');
224 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
230 * @brief Dispatches public messages and find the fitting receivers
232 * @param array $msg The post that will be dispatched
234 * @return bool Was the message accepted?
236 public static function dispatch_public($msg) {
238 $enabled = intval(get_config("system", "diaspora_enabled"));
240 logger("diaspora is disabled");
244 // Use a dummy importer to import the data for the public copy
245 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
246 $item_id = self::dispatch($importer,$msg);
248 // Now distribute it to the followers
249 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
250 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
251 AND NOT `account_expired` AND NOT `account_removed`",
252 dbesc(NETWORK_DIASPORA),
253 dbesc($msg["author"])
257 logger("delivering to: ".$rr["username"]);
258 self::dispatch($rr,$msg);
261 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
267 * @brief Dispatches the different message types to the different functions
269 * @param array $importer Array of the importer user
270 * @param array $msg The post that will be dispatched
272 * @return bool Was the message accepted?
274 public static function dispatch($importer, $msg) {
276 // The sender is the handle of the contact that sent the message.
277 // This will often be different with relayed messages (for example "like" and "comment")
278 $sender = $msg["author"];
280 if (!diaspora::valid_posting($msg, $fields)) {
281 logger("Invalid posting");
285 $type = $fields->getName();
287 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
290 case "account_deletion":
291 return self::receive_account_deletion($importer, $fields);
294 return self::receive_comment($importer, $sender, $fields);
297 return self::receive_conversation($importer, $msg, $fields);
300 return self::receive_like($importer, $sender, $fields);
303 return self::receive_message($importer, $fields);
305 case "participation": // Not implemented
306 return self::receive_participation($importer, $fields);
308 case "photo": // Not implemented
309 return self::receive_photo($importer, $fields);
311 case "poll_participation": // Not implemented
312 return self::receive_poll_participation($importer, $fields);
315 return self::receive_profile($importer, $fields);
318 return self::receive_request($importer, $fields);
321 return self::receive_reshare($importer, $fields);
324 return self::receive_retraction($importer, $sender, $fields);
326 case "status_message":
327 return self::receive_status_message($importer, $fields);
330 logger("Unknown message type ".$type);
338 * @brief Checks if a posting is valid and fetches the data fields.
340 * This function does not only check the signature.
341 * It also does the conversion between the old and the new diaspora format.
343 * @param array $msg Array with the XML, the sender handle and the sender signature
344 * @param object $fields SimpleXML object that contains the posting when it is valid
346 * @return bool Is the posting valid?
348 private function valid_posting($msg, &$fields) {
350 $data = parse_xml_string($msg["message"], false);
352 if (!is_object($data))
355 $first_child = $data->getName();
357 // Is this the new or the old version?
358 if ($data->getName() == "XML") {
360 foreach ($data->post->children() as $child)
367 $type = $element->getName();
370 // All retractions are handled identically from now on.
371 // In the new version there will only be "retraction".
372 if (in_array($type, array("signed_retraction", "relayable_retraction")))
373 $type = "retraction";
375 $fields = new SimpleXMLElement("<".$type."/>");
379 foreach ($element->children() AS $fieldname => $entry) {
381 // Translation for the old XML structure
382 if ($fieldname == "diaspora_handle")
383 $fieldname = "author";
385 if ($fieldname == "participant_handles")
386 $fieldname = "participants";
388 if (in_array($type, array("like", "participation"))) {
389 if ($fieldname == "target_type")
390 $fieldname = "parent_type";
393 if ($fieldname == "sender_handle")
394 $fieldname = "author";
396 if ($fieldname == "recipient_handle")
397 $fieldname = "recipient";
399 if ($fieldname == "root_diaspora_id")
400 $fieldname = "root_author";
402 if ($type == "retraction") {
403 if ($fieldname == "post_guid")
404 $fieldname = "target_guid";
406 if ($fieldname == "type")
407 $fieldname = "target_type";
411 if ($fieldname == "author_signature")
412 $author_signature = base64_decode($entry);
413 elseif ($fieldname == "parent_author_signature")
414 $parent_author_signature = base64_decode($entry);
415 elseif ($fieldname != "target_author_signature") {
416 if ($signed_data != "") {
418 $signed_data_parent .= ";";
421 $signed_data .= $entry;
423 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
424 ($orig_type == "relayable_retraction"))
425 xml::copy($entry, $fields, $fieldname);
428 // This is something that shouldn't happen at all.
429 if (in_array($type, array("status_message", "reshare", "profile")))
430 if ($msg["author"] != $fields->author) {
431 logger("Message handle is not the same as envelope sender. Quitting this message.");
435 // Only some message types have signatures. So we quit here for the other types.
436 if (!in_array($type, array("comment", "message", "like")))
439 // No author_signature? This is a must, so we quit.
440 if (!isset($author_signature))
443 if (isset($parent_author_signature)) {
444 $key = self::key($msg["author"]);
446 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
450 $key = self::key($fields->author);
452 return rsa_verify($signed_data, $author_signature, $key, "sha256");
456 * @brief Fetches the public key for a given handle
458 * @param string $handle The handle
460 * @return string The public key
462 private function key($handle) {
463 logger("Fetching diaspora key for: ".$handle);
465 $r = self::person_by_handle($handle);
473 * @brief Fetches data for a given handle
475 * @param string $handle The handle
477 * @return array the queried data
479 private function person_by_handle($handle) {
481 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
482 dbesc(NETWORK_DIASPORA),
487 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
489 // update record occasionally so it doesn't get stale
490 $d = strtotime($person["updated"]." +00:00");
491 if ($d < strtotime("now - 14 days"))
495 if (!$person OR $update) {
496 logger("create or refresh", LOGGER_DEBUG);
497 $r = probe_url($handle, PROBE_DIASPORA);
499 // Note that Friendica contacts will return a "Diaspora person"
500 // if Diaspora connectivity is enabled on their server
501 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
502 self::add_fcontact($r, $update);
510 * @brief Updates the fcontact table
512 * @param array $arr The fcontact data
513 * @param bool $update Update or insert?
515 * @return string The id of the fcontact entry
517 private function add_fcontact($arr, $update = false) {
518 /// @todo Remove this function from include/network.php
521 $r = q("UPDATE `fcontact` SET
534 WHERE `url` = '%s' AND `network` = '%s'",
536 dbesc($arr["photo"]),
537 dbesc($arr["request"]),
540 dbesc($arr["batch"]),
541 dbesc($arr["notify"]),
543 dbesc($arr["confirm"]),
544 dbesc($arr["alias"]),
545 dbesc($arr["pubkey"]),
546 dbesc(datetime_convert()),
548 dbesc($arr["network"])
551 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
552 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
553 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
556 dbesc($arr["photo"]),
557 dbesc($arr["request"]),
560 dbesc($arr["batch"]),
561 dbesc($arr["notify"]),
563 dbesc($arr["confirm"]),
564 dbesc($arr["network"]),
565 dbesc($arr["alias"]),
566 dbesc($arr["pubkey"]),
567 dbesc(datetime_convert())
574 public static function handle_from_contact($contact_id) {
577 logger("contact id is ".$contact_id, LOGGER_DEBUG);
579 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
585 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
587 if($contact['addr'] != "")
588 $handle = $contact['addr'];
589 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
590 $baseurl_start = strpos($contact['url'],'://') + 3;
591 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
592 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
593 $handle = $contact['nick'].'@'.$baseurl;
600 private function contact_by_handle($uid, $handle) {
601 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
609 $handle_parts = explode("@", $handle);
610 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
611 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
622 private function post_allow($importer, $contact, $is_comment = false) {
624 // perhaps we were already sharing with this person. Now they're sharing with us.
625 // That makes us friends.
626 // Normally this should have handled by getting a request - but this could get lost
627 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
628 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
629 intval(CONTACT_IS_FRIEND),
630 intval($contact["id"]),
631 intval($importer["uid"])
633 $contact["rel"] = CONTACT_IS_FRIEND;
634 logger("defining user ".$contact["nick"]." as friend");
637 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
639 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
641 if($contact["rel"] == CONTACT_IS_FOLLOWER)
642 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
645 // Messages for the global users are always accepted
646 if ($importer["uid"] == 0)
652 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
653 $contact = self::contact_by_handle($importer["uid"], $handle);
655 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
659 if (!self::post_allow($importer, $contact, $is_comment)) {
660 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
666 private function message_exists($uid, $guid) {
667 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
673 logger("message ".$guid." already exists for user ".$uid);
680 private function fetch_guid($item) {
681 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
682 function ($match) use ($item){
683 return(self::fetch_guid_sub($match, $item));
687 private function fetch_guid_sub($match, $item) {
688 if (!self::store_by_guid($match[1], $item["author-link"]))
689 self::store_by_guid($match[1], $item["owner-link"]);
692 private function store_by_guid($guid, $server, $uid = 0) {
693 $serverparts = parse_url($server);
694 $server = $serverparts["scheme"]."://".$serverparts["host"];
696 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
698 $msg = self::message($guid, $server);
703 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
705 // Now call the dispatcher
706 return self::dispatch_public($msg);
709 private function message($guid, $server, $level = 0) {
714 // This will work for Diaspora and newer Friendica servers
715 $source_url = $server."/p/".$guid.".xml";
716 $x = fetch_url($source_url);
720 $source_xml = parse_xml_string($x, false);
722 if (!is_object($source_xml))
725 if ($source_xml->post->reshare) {
726 // Reshare of a reshare - old Diaspora version
727 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
728 } elseif ($source_xml->getName() == "reshare") {
729 // Reshare of a reshare - new Diaspora version
730 return self::message($source_xml->root_guid, $server, ++$level);
735 // Fetch the author - for the old and the new Diaspora version
736 if ($source_xml->post->status_message->diaspora_handle)
737 $author = (string)$source_xml->post->status_message->diaspora_handle;
738 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
739 $author = (string)$source_xml->author;
741 // If this isn't a "status_message" then quit
745 $msg = array("message" => $x, "author" => $author);
747 $msg["key"] = self::key($msg["author"]);
752 private function parent_item($uid, $guid, $author, $contact) {
753 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
754 `author-name`, `author-link`, `author-avatar`,
755 `owner-name`, `owner-link`, `owner-avatar`
756 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
757 intval($uid), dbesc($guid));
760 $result = self::store_by_guid($guid, $contact["url"], $uid);
763 $person = self::person_by_handle($author);
764 $result = self::store_by_guid($guid, $person["url"], $uid);
768 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
770 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
771 `author-name`, `author-link`, `author-avatar`,
772 `owner-name`, `owner-link`, `owner-avatar`
773 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
774 intval($uid), dbesc($guid));
779 logger("parent item not found: parent: ".$guid." - user: ".$uid);
782 logger("parent item found: parent: ".$guid." - user: ".$uid);
787 private function author_contact_by_url($contact, $person, $uid) {
789 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
790 dbesc(normalise_link($person["url"])), intval($uid));
793 $network = $r[0]["network"];
795 $cid = $contact["id"];
796 $network = NETWORK_DIASPORA;
799 return (array("cid" => $cid, "network" => $network));
802 public static function is_redmatrix($url) {
803 return(strstr($url, "/channel/"));
806 private function plink($addr, $guid) {
807 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
811 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
813 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
814 // So we try another way as well.
815 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
817 $r[0]["network"] = $s[0]["network"];
819 if ($r[0]["network"] == NETWORK_DFRN)
820 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
822 if (self::is_redmatrix($r[0]["url"]))
823 return $r[0]["url"]."/?f=&mid=".$guid;
825 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
828 private function receive_account_deletion($importer, $data) {
829 $author = notags(unxmlify($data->author));
831 $contact = self::contact_by_handle($importer["uid"], $author);
833 logger("cannot find contact for author: ".$author);
837 // We now remove the contact
838 contact_remove($contact["id"]);
842 private function receive_comment($importer, $sender, $data) {
843 $guid = notags(unxmlify($data->guid));
844 $parent_guid = notags(unxmlify($data->parent_guid));
845 $text = unxmlify($data->text);
846 $author = notags(unxmlify($data->author));
848 $contact = self::allowed_contact_by_handle($importer, $sender, true);
852 if (self::message_exists($importer["uid"], $guid))
855 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
859 $person = self::person_by_handle($author);
860 if (!is_array($person)) {
861 logger("unable to find author details");
865 // Fetch the contact id - if we know this contact
866 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
870 $datarray["uid"] = $importer["uid"];
871 $datarray["contact-id"] = $author_contact["cid"];
872 $datarray["network"] = $author_contact["network"];
874 $datarray["author-name"] = $person["name"];
875 $datarray["author-link"] = $person["url"];
876 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
878 $datarray["owner-name"] = $contact["name"];
879 $datarray["owner-link"] = $contact["url"];
880 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
882 $datarray["guid"] = $guid;
883 $datarray["uri"] = $author.":".$guid;
885 $datarray["type"] = "remote-comment";
886 $datarray["verb"] = ACTIVITY_POST;
887 $datarray["gravity"] = GRAVITY_COMMENT;
888 $datarray["parent-uri"] = $parent_item["uri"];
890 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
891 $datarray["object"] = json_encode($data);
893 $datarray["body"] = diaspora2bb($text);
895 self::fetch_guid($datarray);
897 $message_id = item_store($datarray);
900 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
902 // If we are the origin of the parent we store the original data and notify our followers
903 if($message_id AND $parent_item["origin"]) {
905 // Formerly we stored the signed text, the signature and the author in different fields.
906 // We now store the raw data so that we are more flexible.
907 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
909 dbesc(json_encode($data))
913 proc_run("php", "include/notifier.php", "comment-import", $message_id);
919 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg) {
920 $guid = notags(unxmlify($data->guid));
921 $subject = notags(unxmlify($data->subject));
922 $author = notags(unxmlify($data->author));
926 $msg_guid = notags(unxmlify($mesg->guid));
927 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
928 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
929 $msg_author_signature = notags(unxmlify($mesg->author_signature));
930 $msg_text = unxmlify($mesg->text);
931 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
933 // "diaspora_handle" is the element name from the old version
934 // "author" is the element name from the new version
936 $msg_author = notags(unxmlify($mesg->author));
937 elseif ($mesg->diaspora_handle)
938 $msg_author = notags(unxmlify($mesg->diaspora_handle));
942 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
944 if($msg_conversation_guid != $guid) {
945 logger("message conversation guid does not belong to the current conversation.");
949 $body = diaspora2bb($msg_text);
950 $message_uri = $msg_author.":".$msg_guid;
952 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
954 $author_signature = base64_decode($msg_author_signature);
956 if(strcasecmp($msg_author,$msg["author"]) == 0) {
960 $person = self::person_by_handle($msg_author);
962 if (is_array($person) && x($person, "pubkey"))
963 $key = $person["pubkey"];
965 logger("unable to find author details");
970 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
971 logger("verification failed.");
975 if($msg_parent_author_signature) {
976 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
978 $parent_author_signature = base64_decode($msg_parent_author_signature);
982 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
983 logger("owner verification failed.");
988 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
992 logger("duplicate message already delivered.", LOGGER_DEBUG);
996 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
997 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
998 intval($importer["uid"]),
1000 intval($conversation["id"]),
1001 dbesc($person["name"]),
1002 dbesc($person["photo"]),
1003 dbesc($person["url"]),
1004 intval($contact["id"]),
1009 dbesc($message_uri),
1010 dbesc($author.":".$guid),
1011 dbesc($msg_created_at)
1014 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1015 dbesc(datetime_convert()),
1016 intval($conversation["id"])
1020 "type" => NOTIFY_MAIL,
1021 "notify_flags" => $importer["notify-flags"],
1022 "language" => $importer["language"],
1023 "to_name" => $importer["username"],
1024 "to_email" => $importer["email"],
1025 "uid" =>$importer["uid"],
1026 "item" => array("subject" => $subject, "body" => $body),
1027 "source_name" => $person["name"],
1028 "source_link" => $person["url"],
1029 "source_photo" => $person["thumb"],
1030 "verb" => ACTIVITY_POST,
1035 private function receive_conversation($importer, $msg, $data) {
1036 $guid = notags(unxmlify($data->guid));
1037 $subject = notags(unxmlify($data->subject));
1038 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1039 $author = notags(unxmlify($data->author));
1040 $participants = notags(unxmlify($data->participants));
1042 $messages = $data->message;
1044 if (!count($messages)) {
1045 logger("empty conversation");
1049 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1053 $conversation = null;
1055 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1056 intval($importer["uid"]),
1060 $conversation = $c[0];
1062 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1063 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1064 intval($importer["uid"]),
1067 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1068 dbesc(datetime_convert()),
1070 dbesc($participants)
1073 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1074 intval($importer["uid"]),
1079 $conversation = $c[0];
1081 if (!$conversation) {
1082 logger("unable to create conversation.");
1086 foreach($messages as $mesg)
1087 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg);
1092 private function construct_like_body($contact, $parent_item, $guid) {
1093 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1095 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1096 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1097 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1099 return sprintf($bodyverb, $ulink, $alink, $plink);
1102 private function construct_like_object($importer, $parent_item) {
1103 $objtype = ACTIVITY_OBJ_NOTE;
1104 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1105 $parent_body = $parent_item["body"];
1107 $xmldata = array("object" => array("type" => $objtype,
1109 "id" => $parent_item["uri"],
1112 "content" => $parent_body));
1114 return xml::from_array($xmldata, $xml, true);
1117 private function receive_like($importer, $sender, $data) {
1118 $positive = notags(unxmlify($data->positive));
1119 $guid = notags(unxmlify($data->guid));
1120 $parent_type = notags(unxmlify($data->parent_type));
1121 $parent_guid = notags(unxmlify($data->parent_guid));
1122 $author = notags(unxmlify($data->author));
1124 // likes on comments aren't supported by Diaspora - only on posts
1125 // But maybe this will be supported in the future, so we will accept it.
1126 if (!in_array($parent_type, array("Post", "Comment")))
1129 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1133 if (self::message_exists($importer["uid"], $guid))
1136 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1140 $person = self::person_by_handle($author);
1141 if (!is_array($person)) {
1142 logger("unable to find author details");
1146 // Fetch the contact id - if we know this contact
1147 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1149 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1150 // We would accept this anyhow.
1151 if ($positive === "true")
1152 $verb = ACTIVITY_LIKE;
1154 $verb = ACTIVITY_DISLIKE;
1156 $datarray = array();
1158 $datarray["uid"] = $importer["uid"];
1159 $datarray["contact-id"] = $author_contact["cid"];
1160 $datarray["network"] = $author_contact["network"];
1162 $datarray["author-name"] = $person["name"];
1163 $datarray["author-link"] = $person["url"];
1164 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1166 $datarray["owner-name"] = $contact["name"];
1167 $datarray["owner-link"] = $contact["url"];
1168 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1170 $datarray["guid"] = $guid;
1171 $datarray["uri"] = $author.":".$guid;
1173 $datarray["type"] = "activity";
1174 $datarray["verb"] = $verb;
1175 $datarray["gravity"] = GRAVITY_LIKE;
1176 $datarray["parent-uri"] = $parent_item["uri"];
1178 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1179 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1181 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1183 $message_id = item_store($datarray);
1186 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1188 // If we are the origin of the parent we store the original data and notify our followers
1189 if($message_id AND $parent_item["origin"]) {
1191 // Formerly we stored the signed text, the signature and the author in different fields.
1192 // We now store the raw data so that we are more flexible.
1193 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1194 intval($message_id),
1195 dbesc(json_encode($data))
1199 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1205 private function receive_message($importer, $data) {
1206 $guid = notags(unxmlify($data->guid));
1207 $parent_guid = notags(unxmlify($data->parent_guid));
1208 $text = unxmlify($data->text);
1209 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1210 $author = notags(unxmlify($data->author));
1211 $conversation_guid = notags(unxmlify($data->conversation_guid));
1213 $contact = self::allowed_contact_by_handle($importer, $author, true);
1217 $conversation = null;
1219 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1220 intval($importer["uid"]),
1221 dbesc($conversation_guid)
1224 $conversation = $c[0];
1226 logger("conversation not available.");
1232 $body = diaspora2bb($text);
1233 $message_uri = $author.":".$guid;
1235 $person = self::person_by_handle($author);
1237 logger("unable to find author details");
1241 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1242 dbesc($message_uri),
1243 intval($importer["uid"])
1246 logger("duplicate message already delivered.", LOGGER_DEBUG);
1250 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1251 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1252 intval($importer["uid"]),
1254 intval($conversation["id"]),
1255 dbesc($person["name"]),
1256 dbesc($person["photo"]),
1257 dbesc($person["url"]),
1258 intval($contact["id"]),
1259 dbesc($conversation["subject"]),
1263 dbesc($message_uri),
1264 dbesc($author.":".$parent_guid),
1268 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1269 dbesc(datetime_convert()),
1270 intval($conversation["id"])
1276 private function receive_participation($importer, $data) {
1277 // I'm not sure if we can fully support this message type
1281 private function receive_photo($importer, $data) {
1282 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1286 private function receive_poll_participation($importer, $data) {
1287 // We don't support polls by now
1291 private function receive_profile($importer, $data) {
1292 $author = notags(unxmlify($data->author));
1294 $contact = self::contact_by_handle($importer["uid"], $author);
1298 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1299 $image_url = unxmlify($data->image_url);
1300 $birthday = unxmlify($data->birthday);
1301 $location = diaspora2bb(unxmlify($data->location));
1302 $about = diaspora2bb(unxmlify($data->bio));
1303 $gender = unxmlify($data->gender);
1304 $searchable = (unxmlify($data->searchable) == "true");
1305 $nsfw = (unxmlify($data->nsfw) == "true");
1306 $tags = unxmlify($data->tag_string);
1308 $tags = explode("#", $tags);
1310 $keywords = array();
1311 foreach ($tags as $tag) {
1312 $tag = trim(strtolower($tag));
1317 $keywords = implode(", ", $keywords);
1319 $handle_parts = explode("@", $author);
1320 $nick = $handle_parts[0];
1323 $name = $handle_parts[0];
1325 if( preg_match("|^https?://|", $image_url) === 0)
1326 $image_url = "http://".$handle_parts[1].$image_url;
1328 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1330 // Generic birthday. We don't know the timezone. The year is irrelevant.
1332 $birthday = str_replace("1000", "1901", $birthday);
1334 if ($birthday != "")
1335 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1337 // this is to prevent multiple birthday notifications in a single year
1338 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1340 if(substr($birthday,5) === substr($contact["bd"],5))
1341 $birthday = $contact["bd"];
1343 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1344 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1348 dbesc(datetime_convert()),
1354 intval($contact["id"]),
1355 intval($importer["uid"])
1359 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1360 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1363 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1364 "photo" => $image_url, "name" => $name, "location" => $location,
1365 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1366 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1367 "hide" => !$searchable, "nsfw" => $nsfw);
1369 update_gcontact($gcontact);
1371 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1376 private function receive_request_make_friend($importer, $contact) {
1380 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1381 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1382 intval(CONTACT_IS_FRIEND),
1383 intval($contact["id"]),
1384 intval($importer["uid"])
1387 // send notification
1389 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1390 intval($importer["uid"])
1393 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1395 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1396 intval($importer["uid"])
1399 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1401 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1404 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1405 $arr["uid"] = $importer["uid"];
1406 $arr["contact-id"] = $self[0]["id"];
1408 $arr["type"] = 'wall';
1409 $arr["gravity"] = 0;
1411 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1412 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1413 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1414 $arr["verb"] = ACTIVITY_FRIEND;
1415 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1417 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1418 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1419 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1420 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1422 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1423 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1424 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1425 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1426 $arr["object"] .= "</link></object>\n";
1427 $arr["last-child"] = 1;
1429 $arr["allow_cid"] = $user[0]["allow_cid"];
1430 $arr["allow_gid"] = $user[0]["allow_gid"];
1431 $arr["deny_cid"] = $user[0]["deny_cid"];
1432 $arr["deny_gid"] = $user[0]["deny_gid"];
1434 $i = item_store($arr);
1436 proc_run("php", "include/notifier.php", "activity", $i);
1443 private function receive_request($importer, $data) {
1444 $author = unxmlify($data->author);
1445 $recipient = unxmlify($data->recipient);
1447 if (!$author || !$recipient)
1450 $contact = self::contact_by_handle($importer["uid"],$author);
1454 // perhaps we were already sharing with this person. Now they're sharing with us.
1455 // That makes us friends.
1457 self::receive_request_make_friend($importer, $contact);
1461 $ret = self::person_by_handle($author);
1463 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1464 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1468 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1470 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1471 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1472 intval($importer["uid"]),
1473 dbesc($ret["network"]),
1474 dbesc($ret["addr"]),
1477 dbesc(normalise_link($ret["url"])),
1479 dbesc($ret["name"]),
1480 dbesc($ret["nick"]),
1481 dbesc($ret["photo"]),
1482 dbesc($ret["pubkey"]),
1483 dbesc($ret["notify"]),
1484 dbesc($ret["poll"]),
1489 // find the contact record we just created
1491 $contact_record = self::contact_by_handle($importer["uid"],$author);
1493 if (!$contact_record) {
1494 logger("unable to locate newly created contact record.");
1498 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1499 intval($importer["uid"])
1502 if($g && intval($g[0]["def_gid"]))
1503 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1505 if($importer["page-flags"] == PAGE_NORMAL) {
1507 $hash = random_string().(string)time(); // Generate a confirm_key
1509 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1510 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1511 intval($importer["uid"]),
1512 intval($contact_record["id"]),
1515 dbesc(t("Sharing notification from Diaspora network")),
1517 dbesc(datetime_convert())
1521 // automatic friend approval
1523 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1525 // technically they are sharing with us (CONTACT_IS_SHARING),
1526 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1527 // we are going to change the relationship and make them a follower.
1529 if($importer["page-flags"] == PAGE_FREELOVE)
1530 $new_relation = CONTACT_IS_FRIEND;
1532 $new_relation = CONTACT_IS_FOLLOWER;
1534 $r = q("UPDATE `contact` SET `rel` = %d,
1542 intval($new_relation),
1543 dbesc(datetime_convert()),
1544 dbesc(datetime_convert()),
1545 intval($contact_record["id"])
1548 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1550 $ret = self::send_share($u[0], $contact_record);
1556 private function original_item($guid, $orig_author, $author) {
1558 // Do we already have this item?
1559 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1560 `author-name`, `author-link`, `author-avatar`
1561 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1565 logger("reshared message ".$guid." already exists on system.");
1567 // Maybe it is already a reshared item?
1568 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1569 if (self::is_reshare($r[0]["body"]))
1576 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1577 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1578 $item_id = self::store_by_guid($guid, $server);
1581 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1582 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1583 $item_id = self::store_by_guid($guid, $server);
1586 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1588 $server = "https://".substr($author, strpos($author, "@") + 1);
1589 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1590 $item_id = self::store_by_guid($guid, $server);
1593 $server = "http://".substr($author, strpos($author, "@") + 1);
1594 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1595 $item_id = self::store_by_guid($guid, $server);
1599 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1600 `author-name`, `author-link`, `author-avatar`
1601 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1612 private function receive_reshare($importer, $data) {
1613 $root_author = notags(unxmlify($data->root_author));
1614 $root_guid = notags(unxmlify($data->root_guid));
1615 $guid = notags(unxmlify($data->guid));
1616 $author = notags(unxmlify($data->author));
1617 $public = notags(unxmlify($data->public));
1618 $created_at = notags(unxmlify($data->created_at));
1620 $contact = self::allowed_contact_by_handle($importer, $author, false);
1624 if (self::message_exists($importer["uid"], $guid))
1627 $original_item = self::original_item($root_guid, $root_author, $author);
1628 if (!$original_item)
1631 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1633 $datarray = array();
1635 $datarray["uid"] = $importer["uid"];
1636 $datarray["contact-id"] = $contact["id"];
1637 $datarray["network"] = NETWORK_DIASPORA;
1639 $datarray["author-name"] = $contact["name"];
1640 $datarray["author-link"] = $contact["url"];
1641 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1643 $datarray["owner-name"] = $datarray["author-name"];
1644 $datarray["owner-link"] = $datarray["author-link"];
1645 $datarray["owner-avatar"] = $datarray["author-avatar"];
1647 $datarray["guid"] = $guid;
1648 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1650 $datarray["verb"] = ACTIVITY_POST;
1651 $datarray["gravity"] = GRAVITY_PARENT;
1653 $datarray["object"] = json_encode($data);
1655 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1656 $original_item["guid"], $original_item["created"], $orig_url);
1657 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1659 $datarray["tag"] = $original_item["tag"];
1660 $datarray["app"] = $original_item["app"];
1662 $datarray["plink"] = self::plink($author, $guid);
1663 $datarray["private"] = (($public == "false") ? 1 : 0);
1664 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1666 $datarray["object-type"] = $original_item["object-type"];
1668 self::fetch_guid($datarray);
1669 $message_id = item_store($datarray);
1672 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1677 private function item_retraction($importer, $contact, $data) {
1678 $target_type = notags(unxmlify($data->target_type));
1679 $target_guid = notags(unxmlify($data->target_guid));
1680 $author = notags(unxmlify($data->author));
1682 $person = self::person_by_handle($author);
1683 if (!is_array($person)) {
1684 logger("unable to find author detail for ".$author);
1688 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1689 dbesc($target_guid),
1690 intval($importer["uid"])
1695 // Only delete it if the author really fits
1696 if (!link_compare($r[0]["author-link"], $person["url"])) {
1697 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
1701 // Check if the sender is the thread owner
1702 $p = q("SELECT `author-link`, `origin` FROM `item` WHERE `id` = %d",
1703 intval($r[0]["parent"]));
1705 // Only delete it if the parent author really fits
1706 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
1707 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
1711 // Currently we don't have a central deletion function that we could use in this case. The function "item_drop" doesn't work for that case
1712 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1713 dbesc(datetime_convert()),
1714 dbesc(datetime_convert()),
1717 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1719 logger("Deleted target ".$target_guid." from user ".$importer["uid"], LOGGER_DEBUG);
1721 // Now check if the retraction needs to be relayed by us
1722 if($p[0]["origin"]) {
1724 // Formerly we stored the signed text, the signature and the author in different fields.
1725 // We now store the raw data so that we are more flexible.
1726 q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1727 intval($r[0]["id"]),
1728 dbesc(json_encode($data))
1732 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1736 private function receive_retraction($importer, $sender, $data) {
1737 $target_type = notags(unxmlify($data->target_type));
1739 $contact = self::contact_by_handle($importer["uid"], $sender);
1741 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1745 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
1747 switch ($target_type) {
1750 case "Post": // "Post" will be supported in a future version
1752 case "StatusMessage":
1753 return self::item_retraction($importer, $contact, $data);;
1756 /// @todo What should we do with an "unshare"?
1757 // Removing the contact isn't correct since we still can read the public items
1758 //contact_remove($contact["id"]);
1762 logger("Unknown target type ".$target_type);
1768 private function receive_status_message($importer, $data) {
1770 $raw_message = unxmlify($data->raw_message);
1771 $guid = notags(unxmlify($data->guid));
1772 $author = notags(unxmlify($data->author));
1773 $public = notags(unxmlify($data->public));
1774 $created_at = notags(unxmlify($data->created_at));
1775 $provider_display_name = notags(unxmlify($data->provider_display_name));
1777 /// @todo enable support for polls
1778 //if ($data->poll) {
1779 // foreach ($data->poll AS $poll)
1783 $contact = self::allowed_contact_by_handle($importer, $author, false);
1787 if (self::message_exists($importer["uid"], $guid))
1791 if ($data->location)
1792 foreach ($data->location->children() AS $fieldname => $data)
1793 $address[$fieldname] = notags(unxmlify($data));
1795 $body = diaspora2bb($raw_message);
1797 $datarray = array();
1800 foreach ($data->photo AS $photo)
1801 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1803 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1805 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1807 // Add OEmbed and other information to the body
1808 if (!self::is_redmatrix($contact["url"]))
1809 $body = add_page_info_to_body($body, false, true);
1812 $datarray["uid"] = $importer["uid"];
1813 $datarray["contact-id"] = $contact["id"];
1814 $datarray["network"] = NETWORK_DIASPORA;
1816 $datarray["author-name"] = $contact["name"];
1817 $datarray["author-link"] = $contact["url"];
1818 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1820 $datarray["owner-name"] = $datarray["author-name"];
1821 $datarray["owner-link"] = $datarray["author-link"];
1822 $datarray["owner-avatar"] = $datarray["author-avatar"];
1824 $datarray["guid"] = $guid;
1825 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1827 $datarray["verb"] = ACTIVITY_POST;
1828 $datarray["gravity"] = GRAVITY_PARENT;
1830 $datarray["object"] = json_encode($data);
1832 $datarray["body"] = $body;
1834 if ($provider_display_name != "")
1835 $datarray["app"] = $provider_display_name;
1837 $datarray["plink"] = self::plink($author, $guid);
1838 $datarray["private"] = (($public == "false") ? 1 : 0);
1839 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1841 if (isset($address["address"]))
1842 $datarray["location"] = $address["address"];
1844 if (isset($address["lat"]) AND isset($address["lng"]))
1845 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1847 self::fetch_guid($datarray);
1848 $message_id = item_store($datarray);
1851 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1856 /******************************************************************************************
1857 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1858 ******************************************************************************************/
1860 private function my_handle($me) {
1861 if ($contact["addr"] != "")
1862 return $contact["addr"];
1864 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1865 // So - just in case - we build the the address here.
1866 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1869 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1871 logger("Message: ".$msg, LOGGER_DATA);
1873 $handle = self::my_handle($user);
1875 $b64url_data = base64url_encode($msg);
1877 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1879 $type = "application/xml";
1880 $encoding = "base64url";
1881 $alg = "RSA-SHA256";
1883 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1885 $signature = rsa_sign($signable_data,$prvkey);
1886 $sig = base64url_encode($signature);
1888 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1889 "me:env" => array("me:encoding" => "base64url",
1890 "me:alg" => "RSA-SHA256",
1892 "@attributes" => array("type" => "application/xml"),
1893 "me:sig" => $sig)));
1895 $namespaces = array("" => "https://joindiaspora.com/protocol",
1896 "me" => "http://salmon-protocol.org/ns/magic-env");
1898 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1900 logger("magic_env: ".$magic_env, LOGGER_DATA);
1904 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1906 logger("Message: ".$msg, LOGGER_DATA);
1908 // without a public key nothing will work
1911 logger("pubkey missing: contact id: ".$contact["id"]);
1915 $inner_aes_key = random_string(32);
1916 $b_inner_aes_key = base64_encode($inner_aes_key);
1917 $inner_iv = random_string(16);
1918 $b_inner_iv = base64_encode($inner_iv);
1920 $outer_aes_key = random_string(32);
1921 $b_outer_aes_key = base64_encode($outer_aes_key);
1922 $outer_iv = random_string(16);
1923 $b_outer_iv = base64_encode($outer_iv);
1925 $handle = self::my_handle($user);
1927 $padded_data = pkcs5_pad($msg,16);
1928 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1930 $b64_data = base64_encode($inner_encrypted);
1933 $b64url_data = base64url_encode($b64_data);
1934 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1936 $type = "application/xml";
1937 $encoding = "base64url";
1938 $alg = "RSA-SHA256";
1940 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1942 $signature = rsa_sign($signable_data,$prvkey);
1943 $sig = base64url_encode($signature);
1945 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1946 "aes_key" => $b_inner_aes_key,
1947 "author_id" => $handle));
1949 $decrypted_header = xml::from_array($xmldata, $xml, true);
1950 $decrypted_header = pkcs5_pad($decrypted_header,16);
1952 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1954 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1956 $encrypted_outer_key_bundle = "";
1957 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1959 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1961 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1963 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1964 "ciphertext" => base64_encode($ciphertext)));
1965 $cipher_json = base64_encode($encrypted_header_json_object);
1967 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
1968 "me:env" => array("me:encoding" => "base64url",
1969 "me:alg" => "RSA-SHA256",
1971 "@attributes" => array("type" => "application/xml"),
1972 "me:sig" => $sig)));
1974 $namespaces = array("" => "https://joindiaspora.com/protocol",
1975 "me" => "http://salmon-protocol.org/ns/magic-env");
1977 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1979 logger("magic_env: ".$magic_env, LOGGER_DATA);
1983 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1986 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1988 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1990 // The data that will be transmitted is double encoded via "urlencode", strange ...
1991 $slap = "xml=".urlencode(urlencode($magic_env));
1995 private function signature($owner, $message) {
1997 unset($sigmsg["author_signature"]);
1998 unset($sigmsg["parent_author_signature"]);
2000 $signed_text = implode(";", $sigmsg);
2002 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2005 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2009 $enabled = intval(get_config("system", "diaspora_enabled"));
2013 $logid = random_string(4);
2014 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2016 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2020 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2022 if (!$queue_run && was_recently_delayed($contact["id"])) {
2025 if (!intval(get_config("system", "diaspora_test"))) {
2026 post_url($dest_url."/", $slap);
2027 $return_code = $a->get_curl_code();
2029 logger("test_mode");
2034 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2036 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2037 logger("queue message");
2039 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2040 intval($contact["id"]),
2041 dbesc(NETWORK_DIASPORA),
2043 intval($public_batch)
2046 logger("add_to_queue ignored - identical item already in queue");
2048 // queue message for redelivery
2049 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2053 return(($return_code) ? $return_code : (-1));
2057 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "") {
2059 $data = array("XML" => array("post" => array($type => $message)));
2061 $msg = xml::from_array($data, $xml);
2063 logger('message: '.$msg, LOGGER_DATA);
2064 logger('send guid '.$guid, LOGGER_DEBUG);
2066 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2068 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2070 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2072 return $return_code;
2075 public static function send_share($owner,$contact) {
2077 $message = array("sender_handle" => self::my_handle($owner),
2078 "recipient_handle" => $contact["addr"]);
2080 return self::build_and_transmit($owner, $contact, "request", $message);
2083 public static function send_unshare($owner,$contact) {
2085 $message = array("post_guid" => $owner["guid"],
2086 "diaspora_handle" => self::my_handle($owner),
2087 "type" => "Person");
2089 return self::build_and_transmit($owner, $contact, "retraction", $message);
2092 private function is_reshare($body) {
2093 $body = trim($body);
2095 // Skip if it isn't a pure repeated messages
2096 // Does it start with a share?
2097 if (strpos($body, "[share") > 0)
2100 // Does it end with a share?
2101 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2104 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2105 // Skip if there is no shared message in there
2106 if ($body == $attributes)
2110 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2111 if ($matches[1] != "")
2112 $guid = $matches[1];
2114 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2115 if ($matches[1] != "")
2116 $guid = $matches[1];
2119 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2120 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2123 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2124 $ret["root_guid"] = $guid;
2130 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2131 if ($matches[1] != "")
2132 $profile = $matches[1];
2134 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2135 if ($matches[1] != "")
2136 $profile = $matches[1];
2140 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2141 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2145 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2146 if ($matches[1] != "")
2147 $link = $matches[1];
2149 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2150 if ($matches[1] != "")
2151 $link = $matches[1];
2153 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2154 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2159 public static function send_status($item, $owner, $contact, $public_batch = false) {
2161 $myaddr = self::my_handle($owner);
2163 $public = (($item["private"]) ? "false" : "true");
2165 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2167 // Detect a share element and do a reshare
2168 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2169 $message = array("root_diaspora_id" => $ret["root_handle"],
2170 "root_guid" => $ret["root_guid"],
2171 "guid" => $item["guid"],
2172 "diaspora_handle" => $myaddr,
2173 "public" => $public,
2174 "created_at" => $created,
2175 "provider_display_name" => $item["app"]);
2179 $title = $item["title"];
2180 $body = $item["body"];
2182 // convert to markdown
2183 $body = html_entity_decode(bb2diaspora($body));
2187 $body = "## ".html_entity_decode($title)."\n\n".$body;
2189 if ($item["attach"]) {
2190 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2192 $body .= "\n".t("Attachments:")."\n";
2193 foreach($matches as $mtch)
2194 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2198 $location = array();
2200 if ($item["location"] != "")
2201 $location["address"] = $item["location"];
2203 if ($item["coord"] != "") {
2204 $coord = explode(" ", $item["coord"]);
2205 $location["lat"] = $coord[0];
2206 $location["lng"] = $coord[1];
2209 $message = array("raw_message" => $body,
2210 "location" => $location,
2211 "guid" => $item["guid"],
2212 "diaspora_handle" => $myaddr,
2213 "public" => $public,
2214 "created_at" => $created,
2215 "provider_display_name" => $item["app"]);
2217 if (count($location) == 0)
2218 unset($message["location"]);
2220 $type = "status_message";
2223 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2226 private function construct_like($item, $owner) {
2228 $myaddr = self::my_handle($owner);
2230 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2231 dbesc($item["thr-parent"]));
2237 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2240 return(array("positive" => $positive,
2241 "guid" => $item["guid"],
2242 "target_type" => $target_type,
2243 "parent_guid" => $parent["guid"],
2244 "author_signature" => $authorsig,
2245 "diaspora_handle" => $myaddr));
2248 private function construct_comment($item, $owner) {
2250 $myaddr = self::my_handle($owner);
2252 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2253 intval($item["parent"]),
2254 intval($item["parent"])
2262 $text = html_entity_decode(bb2diaspora($item["body"]));
2264 return(array("guid" => $item["guid"],
2265 "parent_guid" => $parent["guid"],
2266 "author_signature" => "",
2268 "diaspora_handle" => $myaddr));
2271 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2273 if($item['verb'] === ACTIVITY_LIKE) {
2274 $message = self::construct_like($item, $owner);
2277 $message = self::construct_comment($item, $owner);
2284 $message["author_signature"] = self::signature($owner, $message);
2286 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2289 private function message_from_signatur($item, $signature) {
2291 // Split the signed text
2292 $signed_parts = explode(";", $signature['signed_text']);
2294 if ($item["deleted"])
2295 $message = array("parent_author_signature" => "",
2296 "target_guid" => $signed_parts[0],
2297 "target_type" => $signed_parts[1],
2298 "sender_handle" => $signature['signer'],
2299 "target_author_signature" => $signature['signature']);
2300 elseif ($item['verb'] === ACTIVITY_LIKE)
2301 $message = array("positive" => $signed_parts[0],
2302 "guid" => $signed_parts[1],
2303 "target_type" => $signed_parts[2],
2304 "parent_guid" => $signed_parts[3],
2305 "parent_author_signature" => "",
2306 "author_signature" => $signature['signature'],
2307 "diaspora_handle" => $signed_parts[4]);
2309 // Remove the comment guid
2310 $guid = array_shift($signed_parts);
2312 // Remove the parent guid
2313 $parent_guid = array_shift($signed_parts);
2315 // Remove the handle
2316 $handle = array_pop($signed_parts);
2318 // Glue the parts together
2319 $text = implode(";", $signed_parts);
2321 $message = array("guid" => $guid,
2322 "parent_guid" => $parent_guid,
2323 "parent_author_signature" => "",
2324 "author_signature" => $signature['signature'],
2325 "text" => implode(";", $signed_parts),
2326 "diaspora_handle" => $handle);
2331 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2333 if ($item["deleted"]) {
2334 $sql_sign_id = "retract_iid";
2335 $type = "relayable_retraction";
2336 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2337 $sql_sign_id = "iid";
2340 $sql_sign_id = "iid";
2344 // fetch the original signature
2346 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2347 intval($item["id"]));
2350 return self::send_followup($item, $owner, $contact, $public_batch);
2354 // Old way - is used by the internal Friendica functions
2355 /// @todo Change all signatur storing functions to the new format
2356 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2357 $message = self::message_from_signatur($item, $signature);
2359 $msg = json_decode($signature['signed_text'], true);
2362 foreach ($msg AS $field => $data) {
2363 if (!$item["deleted"]) {
2364 if ($field == "author")
2365 $field = "diaspora_handle";
2366 if ($field == "parent_type")
2367 $field = "target_type";
2370 $message[$field] = $data;
2374 if ($item["deleted"]) {
2375 $signed_text = $message["target_guid"].';'.$message["target_type"];
2376 $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2378 $message["parent_author_signature"] = self::signature($owner, $message);
2380 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2382 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2385 public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2387 $myaddr = self::my_handle($owner);
2389 // Check whether the retraction is for a top-level post or whether it's a relayable
2390 if ($item["uri"] !== $item["parent-uri"]) {
2391 $msg_type = "relayable_retraction";
2392 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2394 $msg_type = "signed_retraction";
2395 $target_type = "StatusMessage";
2398 $signed_text = $item["guid"].";".$target_type;
2400 $message = array("target_guid" => $item['guid'],
2401 "target_type" => $target_type,
2402 "sender_handle" => $myaddr,
2403 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2405 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2408 public static function send_mail($item, $owner, $contact) {
2410 $myaddr = self::my_handle($owner);
2412 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2413 intval($item["convid"]),
2414 intval($item["uid"])
2418 logger("conversation not found.");
2424 "guid" => $cnv["guid"],
2425 "subject" => $cnv["subject"],
2426 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2427 "diaspora_handle" => $cnv["creator"],
2428 "participant_handles" => $cnv["recips"]
2431 $body = bb2diaspora($item["body"]);
2432 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2434 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2435 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2438 "guid" => $item["guid"],
2439 "parent_guid" => $cnv["guid"],
2440 "parent_author_signature" => $sig,
2441 "author_signature" => $sig,
2443 "created_at" => $created,
2444 "diaspora_handle" => $myaddr,
2445 "conversation_guid" => $cnv["guid"]
2448 if ($item["reply"]) {
2452 $message = array("guid" => $cnv["guid"],
2453 "subject" => $cnv["subject"],
2454 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2456 "diaspora_handle" => $cnv["creator"],
2457 "participant_handles" => $cnv["recips"]);
2459 $type = "conversation";
2462 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);