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 $handle = strval($handle);
465 logger("Fetching diaspora key for: ".$handle);
467 $r = self::person_by_handle($handle);
475 * @brief Fetches data for a given handle
477 * @param string $handle The handle
479 * @return array the queried data
481 private function person_by_handle($handle) {
483 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
484 dbesc(NETWORK_DIASPORA),
489 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
491 // update record occasionally so it doesn't get stale
492 $d = strtotime($person["updated"]." +00:00");
493 if ($d < strtotime("now - 14 days"))
497 if (!$person OR $update) {
498 logger("create or refresh", LOGGER_DEBUG);
499 $r = probe_url($handle, PROBE_DIASPORA);
501 // Note that Friendica contacts will return a "Diaspora person"
502 // if Diaspora connectivity is enabled on their server
503 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
504 self::add_fcontact($r, $update);
512 * @brief Updates the fcontact table
514 * @param array $arr The fcontact data
515 * @param bool $update Update or insert?
517 * @return string The id of the fcontact entry
519 private function add_fcontact($arr, $update = false) {
520 /// @todo Remove this function from include/network.php
523 $r = q("UPDATE `fcontact` SET
536 WHERE `url` = '%s' AND `network` = '%s'",
538 dbesc($arr["photo"]),
539 dbesc($arr["request"]),
542 dbesc($arr["batch"]),
543 dbesc($arr["notify"]),
545 dbesc($arr["confirm"]),
546 dbesc($arr["alias"]),
547 dbesc($arr["pubkey"]),
548 dbesc(datetime_convert()),
550 dbesc($arr["network"])
553 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
554 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
555 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
558 dbesc($arr["photo"]),
559 dbesc($arr["request"]),
562 dbesc($arr["batch"]),
563 dbesc($arr["notify"]),
565 dbesc($arr["confirm"]),
566 dbesc($arr["network"]),
567 dbesc($arr["alias"]),
568 dbesc($arr["pubkey"]),
569 dbesc(datetime_convert())
576 public static function handle_from_contact($contact_id) {
579 logger("contact id is ".$contact_id, LOGGER_DEBUG);
581 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
587 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
589 if($contact['addr'] != "")
590 $handle = $contact['addr'];
591 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
592 $baseurl_start = strpos($contact['url'],'://') + 3;
593 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
594 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
595 $handle = $contact['nick'].'@'.$baseurl;
602 private function contact_by_handle($uid, $handle) {
603 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
611 $handle_parts = explode("@", $handle);
612 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
613 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
624 private function post_allow($importer, $contact, $is_comment = false) {
626 // perhaps we were already sharing with this person. Now they're sharing with us.
627 // That makes us friends.
628 // Normally this should have handled by getting a request - but this could get lost
629 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
630 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
631 intval(CONTACT_IS_FRIEND),
632 intval($contact["id"]),
633 intval($importer["uid"])
635 $contact["rel"] = CONTACT_IS_FRIEND;
636 logger("defining user ".$contact["nick"]." as friend");
639 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
641 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
643 if($contact["rel"] == CONTACT_IS_FOLLOWER)
644 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
647 // Messages for the global users are always accepted
648 if ($importer["uid"] == 0)
654 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
655 $contact = self::contact_by_handle($importer["uid"], $handle);
657 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
661 if (!self::post_allow($importer, $contact, $is_comment)) {
662 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
668 private function message_exists($uid, $guid) {
669 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
675 logger("message ".$guid." already exists for user ".$uid);
682 private function fetch_guid($item) {
683 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
684 function ($match) use ($item){
685 return(self::fetch_guid_sub($match, $item));
689 private function fetch_guid_sub($match, $item) {
690 if (!self::store_by_guid($match[1], $item["author-link"]))
691 self::store_by_guid($match[1], $item["owner-link"]);
694 private function store_by_guid($guid, $server, $uid = 0) {
695 $serverparts = parse_url($server);
696 $server = $serverparts["scheme"]."://".$serverparts["host"];
698 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
700 $msg = self::message($guid, $server);
705 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
707 // Now call the dispatcher
708 return self::dispatch_public($msg);
711 private function message($guid, $server, $level = 0) {
716 // This will work for Diaspora and newer Friendica servers
717 $source_url = $server."/p/".$guid.".xml";
718 $x = fetch_url($source_url);
722 $source_xml = parse_xml_string($x, false);
724 if (!is_object($source_xml))
727 if ($source_xml->post->reshare) {
728 // Reshare of a reshare - old Diaspora version
729 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
730 } elseif ($source_xml->getName() == "reshare") {
731 // Reshare of a reshare - new Diaspora version
732 return self::message($source_xml->root_guid, $server, ++$level);
737 // Fetch the author - for the old and the new Diaspora version
738 if ($source_xml->post->status_message->diaspora_handle)
739 $author = (string)$source_xml->post->status_message->diaspora_handle;
740 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
741 $author = (string)$source_xml->author;
743 // If this isn't a "status_message" then quit
747 $msg = array("message" => $x, "author" => $author);
749 $msg["key"] = self::key($msg["author"]);
754 private function parent_item($uid, $guid, $author, $contact) {
755 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
756 `author-name`, `author-link`, `author-avatar`,
757 `owner-name`, `owner-link`, `owner-avatar`
758 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
759 intval($uid), dbesc($guid));
762 $result = self::store_by_guid($guid, $contact["url"], $uid);
765 $person = self::person_by_handle($author);
766 $result = self::store_by_guid($guid, $person["url"], $uid);
770 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
772 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
773 `author-name`, `author-link`, `author-avatar`,
774 `owner-name`, `owner-link`, `owner-avatar`
775 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
776 intval($uid), dbesc($guid));
781 logger("parent item not found: parent: ".$guid." - user: ".$uid);
784 logger("parent item found: parent: ".$guid." - user: ".$uid);
789 private function author_contact_by_url($contact, $person, $uid) {
791 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
792 dbesc(normalise_link($person["url"])), intval($uid));
795 $network = $r[0]["network"];
797 $cid = $contact["id"];
798 $network = NETWORK_DIASPORA;
801 return (array("cid" => $cid, "network" => $network));
804 public static function is_redmatrix($url) {
805 return(strstr($url, "/channel/"));
808 private function plink($addr, $guid) {
809 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
813 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
815 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
816 // So we try another way as well.
817 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
819 $r[0]["network"] = $s[0]["network"];
821 if ($r[0]["network"] == NETWORK_DFRN)
822 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
824 if (self::is_redmatrix($r[0]["url"]))
825 return $r[0]["url"]."/?f=&mid=".$guid;
827 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
830 private function receive_account_deletion($importer, $data) {
831 $author = notags(unxmlify($data->author));
833 $contact = self::contact_by_handle($importer["uid"], $author);
835 logger("cannot find contact for author: ".$author);
839 // We now remove the contact
840 contact_remove($contact["id"]);
844 private function receive_comment($importer, $sender, $data) {
845 $guid = notags(unxmlify($data->guid));
846 $parent_guid = notags(unxmlify($data->parent_guid));
847 $text = unxmlify($data->text);
848 $author = notags(unxmlify($data->author));
850 $contact = self::allowed_contact_by_handle($importer, $sender, true);
854 if (self::message_exists($importer["uid"], $guid))
857 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
861 $person = self::person_by_handle($author);
862 if (!is_array($person)) {
863 logger("unable to find author details");
867 // Fetch the contact id - if we know this contact
868 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
872 $datarray["uid"] = $importer["uid"];
873 $datarray["contact-id"] = $author_contact["cid"];
874 $datarray["network"] = $author_contact["network"];
876 $datarray["author-name"] = $person["name"];
877 $datarray["author-link"] = $person["url"];
878 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
880 $datarray["owner-name"] = $contact["name"];
881 $datarray["owner-link"] = $contact["url"];
882 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
884 $datarray["guid"] = $guid;
885 $datarray["uri"] = $author.":".$guid;
887 $datarray["type"] = "remote-comment";
888 $datarray["verb"] = ACTIVITY_POST;
889 $datarray["gravity"] = GRAVITY_COMMENT;
890 $datarray["parent-uri"] = $parent_item["uri"];
892 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
893 $datarray["object"] = json_encode($data);
895 $datarray["body"] = diaspora2bb($text);
897 self::fetch_guid($datarray);
899 $message_id = item_store($datarray);
902 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
904 // If we are the origin of the parent we store the original data and notify our followers
905 if($message_id AND $parent_item["origin"]) {
907 // Formerly we stored the signed text, the signature and the author in different fields.
908 // We now store the raw data so that we are more flexible.
909 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
911 dbesc(json_encode($data))
915 proc_run("php", "include/notifier.php", "comment-import", $message_id);
921 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
922 $guid = notags(unxmlify($data->guid));
923 $subject = notags(unxmlify($data->subject));
924 $author = notags(unxmlify($data->author));
928 $msg_guid = notags(unxmlify($mesg->guid));
929 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
930 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
931 $msg_author_signature = notags(unxmlify($mesg->author_signature));
932 $msg_text = unxmlify($mesg->text);
933 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
935 // "diaspora_handle" is the element name from the old version
936 // "author" is the element name from the new version
938 $msg_author = notags(unxmlify($mesg->author));
939 elseif ($mesg->diaspora_handle)
940 $msg_author = notags(unxmlify($mesg->diaspora_handle));
944 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
946 if($msg_conversation_guid != $guid) {
947 logger("message conversation guid does not belong to the current conversation.");
951 $body = diaspora2bb($msg_text);
952 $message_uri = $msg_author.":".$msg_guid;
954 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
956 $author_signature = base64_decode($msg_author_signature);
958 if(strcasecmp($msg_author,$msg["author"]) == 0) {
962 $person = self::person_by_handle($msg_author);
964 if (is_array($person) && x($person, "pubkey"))
965 $key = $person["pubkey"];
967 logger("unable to find author details");
972 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
973 logger("verification failed.");
977 if($msg_parent_author_signature) {
978 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
980 $parent_author_signature = base64_decode($msg_parent_author_signature);
984 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
985 logger("owner verification failed.");
990 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
994 logger("duplicate message already delivered.", LOGGER_DEBUG);
998 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
999 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1000 intval($importer["uid"]),
1002 intval($conversation["id"]),
1003 dbesc($person["name"]),
1004 dbesc($person["photo"]),
1005 dbesc($person["url"]),
1006 intval($contact["id"]),
1011 dbesc($message_uri),
1012 dbesc($author.":".$guid),
1013 dbesc($msg_created_at)
1016 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1017 dbesc(datetime_convert()),
1018 intval($conversation["id"])
1022 "type" => NOTIFY_MAIL,
1023 "notify_flags" => $importer["notify-flags"],
1024 "language" => $importer["language"],
1025 "to_name" => $importer["username"],
1026 "to_email" => $importer["email"],
1027 "uid" =>$importer["uid"],
1028 "item" => array("subject" => $subject, "body" => $body),
1029 "source_name" => $person["name"],
1030 "source_link" => $person["url"],
1031 "source_photo" => $person["thumb"],
1032 "verb" => ACTIVITY_POST,
1037 private function receive_conversation($importer, $msg, $data) {
1038 $guid = notags(unxmlify($data->guid));
1039 $subject = notags(unxmlify($data->subject));
1040 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1041 $author = notags(unxmlify($data->author));
1042 $participants = notags(unxmlify($data->participants));
1044 $messages = $data->message;
1046 if (!count($messages)) {
1047 logger("empty conversation");
1051 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1055 $conversation = null;
1057 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1058 intval($importer["uid"]),
1062 $conversation = $c[0];
1064 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1065 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1066 intval($importer["uid"]),
1069 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1070 dbesc(datetime_convert()),
1072 dbesc($participants)
1075 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1076 intval($importer["uid"]),
1081 $conversation = $c[0];
1083 if (!$conversation) {
1084 logger("unable to create conversation.");
1088 foreach($messages as $mesg)
1089 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1094 private function construct_like_body($contact, $parent_item, $guid) {
1095 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1097 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1098 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1099 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1101 return sprintf($bodyverb, $ulink, $alink, $plink);
1104 private function construct_like_object($importer, $parent_item) {
1105 $objtype = ACTIVITY_OBJ_NOTE;
1106 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1107 $parent_body = $parent_item["body"];
1109 $xmldata = array("object" => array("type" => $objtype,
1111 "id" => $parent_item["uri"],
1114 "content" => $parent_body));
1116 return xml::from_array($xmldata, $xml, true);
1119 private function receive_like($importer, $sender, $data) {
1120 $positive = notags(unxmlify($data->positive));
1121 $guid = notags(unxmlify($data->guid));
1122 $parent_type = notags(unxmlify($data->parent_type));
1123 $parent_guid = notags(unxmlify($data->parent_guid));
1124 $author = notags(unxmlify($data->author));
1126 // likes on comments aren't supported by Diaspora - only on posts
1127 // But maybe this will be supported in the future, so we will accept it.
1128 if (!in_array($parent_type, array("Post", "Comment")))
1131 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1135 if (self::message_exists($importer["uid"], $guid))
1138 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1142 $person = self::person_by_handle($author);
1143 if (!is_array($person)) {
1144 logger("unable to find author details");
1148 // Fetch the contact id - if we know this contact
1149 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1151 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1152 // We would accept this anyhow.
1153 if ($positive === "true")
1154 $verb = ACTIVITY_LIKE;
1156 $verb = ACTIVITY_DISLIKE;
1158 $datarray = array();
1160 $datarray["uid"] = $importer["uid"];
1161 $datarray["contact-id"] = $author_contact["cid"];
1162 $datarray["network"] = $author_contact["network"];
1164 $datarray["author-name"] = $person["name"];
1165 $datarray["author-link"] = $person["url"];
1166 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1168 $datarray["owner-name"] = $contact["name"];
1169 $datarray["owner-link"] = $contact["url"];
1170 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1172 $datarray["guid"] = $guid;
1173 $datarray["uri"] = $author.":".$guid;
1175 $datarray["type"] = "activity";
1176 $datarray["verb"] = $verb;
1177 $datarray["gravity"] = GRAVITY_LIKE;
1178 $datarray["parent-uri"] = $parent_item["uri"];
1180 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1181 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1183 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1185 $message_id = item_store($datarray);
1188 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1190 // If we are the origin of the parent we store the original data and notify our followers
1191 if($message_id AND $parent_item["origin"]) {
1193 // Formerly we stored the signed text, the signature and the author in different fields.
1194 // We now store the raw data so that we are more flexible.
1195 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1196 intval($message_id),
1197 dbesc(json_encode($data))
1201 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1207 private function receive_message($importer, $data) {
1208 $guid = notags(unxmlify($data->guid));
1209 $parent_guid = notags(unxmlify($data->parent_guid));
1210 $text = unxmlify($data->text);
1211 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1212 $author = notags(unxmlify($data->author));
1213 $conversation_guid = notags(unxmlify($data->conversation_guid));
1215 $contact = self::allowed_contact_by_handle($importer, $author, true);
1219 $conversation = null;
1221 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1222 intval($importer["uid"]),
1223 dbesc($conversation_guid)
1226 $conversation = $c[0];
1228 logger("conversation not available.");
1234 $body = diaspora2bb($text);
1235 $message_uri = $author.":".$guid;
1237 $person = self::person_by_handle($author);
1239 logger("unable to find author details");
1243 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1244 dbesc($message_uri),
1245 intval($importer["uid"])
1248 logger("duplicate message already delivered.", LOGGER_DEBUG);
1252 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1253 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1254 intval($importer["uid"]),
1256 intval($conversation["id"]),
1257 dbesc($person["name"]),
1258 dbesc($person["photo"]),
1259 dbesc($person["url"]),
1260 intval($contact["id"]),
1261 dbesc($conversation["subject"]),
1265 dbesc($message_uri),
1266 dbesc($author.":".$parent_guid),
1270 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1271 dbesc(datetime_convert()),
1272 intval($conversation["id"])
1278 private function receive_participation($importer, $data) {
1279 // I'm not sure if we can fully support this message type
1283 private function receive_photo($importer, $data) {
1284 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1288 private function receive_poll_participation($importer, $data) {
1289 // We don't support polls by now
1293 private function receive_profile($importer, $data) {
1294 $author = notags(unxmlify($data->author));
1296 $contact = self::contact_by_handle($importer["uid"], $author);
1300 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1301 $image_url = unxmlify($data->image_url);
1302 $birthday = unxmlify($data->birthday);
1303 $location = diaspora2bb(unxmlify($data->location));
1304 $about = diaspora2bb(unxmlify($data->bio));
1305 $gender = unxmlify($data->gender);
1306 $searchable = (unxmlify($data->searchable) == "true");
1307 $nsfw = (unxmlify($data->nsfw) == "true");
1308 $tags = unxmlify($data->tag_string);
1310 $tags = explode("#", $tags);
1312 $keywords = array();
1313 foreach ($tags as $tag) {
1314 $tag = trim(strtolower($tag));
1319 $keywords = implode(", ", $keywords);
1321 $handle_parts = explode("@", $author);
1322 $nick = $handle_parts[0];
1325 $name = $handle_parts[0];
1327 if( preg_match("|^https?://|", $image_url) === 0)
1328 $image_url = "http://".$handle_parts[1].$image_url;
1330 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1332 // Generic birthday. We don't know the timezone. The year is irrelevant.
1334 $birthday = str_replace("1000", "1901", $birthday);
1336 if ($birthday != "")
1337 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1339 // this is to prevent multiple birthday notifications in a single year
1340 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1342 if(substr($birthday,5) === substr($contact["bd"],5))
1343 $birthday = $contact["bd"];
1345 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1346 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1350 dbesc(datetime_convert()),
1356 intval($contact["id"]),
1357 intval($importer["uid"])
1361 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1362 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1365 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1366 "photo" => $image_url, "name" => $name, "location" => $location,
1367 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1368 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1369 "hide" => !$searchable, "nsfw" => $nsfw);
1371 update_gcontact($gcontact);
1373 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1378 private function receive_request_make_friend($importer, $contact) {
1382 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1383 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1384 intval(CONTACT_IS_FRIEND),
1385 intval($contact["id"]),
1386 intval($importer["uid"])
1389 // send notification
1391 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1392 intval($importer["uid"])
1395 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1397 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1398 intval($importer["uid"])
1401 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1403 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1406 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1407 $arr["uid"] = $importer["uid"];
1408 $arr["contact-id"] = $self[0]["id"];
1410 $arr["type"] = 'wall';
1411 $arr["gravity"] = 0;
1413 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1414 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1415 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1416 $arr["verb"] = ACTIVITY_FRIEND;
1417 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1419 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1420 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1421 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1422 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1424 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1425 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1426 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1427 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1428 $arr["object"] .= "</link></object>\n";
1429 $arr["last-child"] = 1;
1431 $arr["allow_cid"] = $user[0]["allow_cid"];
1432 $arr["allow_gid"] = $user[0]["allow_gid"];
1433 $arr["deny_cid"] = $user[0]["deny_cid"];
1434 $arr["deny_gid"] = $user[0]["deny_gid"];
1436 $i = item_store($arr);
1438 proc_run("php", "include/notifier.php", "activity", $i);
1445 private function receive_request($importer, $data) {
1446 $author = unxmlify($data->author);
1447 $recipient = unxmlify($data->recipient);
1449 if (!$author || !$recipient)
1452 $contact = self::contact_by_handle($importer["uid"],$author);
1456 // perhaps we were already sharing with this person. Now they're sharing with us.
1457 // That makes us friends.
1459 self::receive_request_make_friend($importer, $contact);
1463 $ret = self::person_by_handle($author);
1465 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1466 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1470 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1472 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1473 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1474 intval($importer["uid"]),
1475 dbesc($ret["network"]),
1476 dbesc($ret["addr"]),
1479 dbesc(normalise_link($ret["url"])),
1481 dbesc($ret["name"]),
1482 dbesc($ret["nick"]),
1483 dbesc($ret["photo"]),
1484 dbesc($ret["pubkey"]),
1485 dbesc($ret["notify"]),
1486 dbesc($ret["poll"]),
1491 // find the contact record we just created
1493 $contact_record = self::contact_by_handle($importer["uid"],$author);
1495 if (!$contact_record) {
1496 logger("unable to locate newly created contact record.");
1500 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1501 intval($importer["uid"])
1504 if($g && intval($g[0]["def_gid"]))
1505 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1507 if($importer["page-flags"] == PAGE_NORMAL) {
1509 $hash = random_string().(string)time(); // Generate a confirm_key
1511 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1512 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1513 intval($importer["uid"]),
1514 intval($contact_record["id"]),
1517 dbesc(t("Sharing notification from Diaspora network")),
1519 dbesc(datetime_convert())
1523 // automatic friend approval
1525 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1527 // technically they are sharing with us (CONTACT_IS_SHARING),
1528 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1529 // we are going to change the relationship and make them a follower.
1531 if($importer["page-flags"] == PAGE_FREELOVE)
1532 $new_relation = CONTACT_IS_FRIEND;
1534 $new_relation = CONTACT_IS_FOLLOWER;
1536 $r = q("UPDATE `contact` SET `rel` = %d,
1544 intval($new_relation),
1545 dbesc(datetime_convert()),
1546 dbesc(datetime_convert()),
1547 intval($contact_record["id"])
1550 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1552 $ret = self::send_share($u[0], $contact_record);
1558 private function original_item($guid, $orig_author, $author) {
1560 // Do we already have this item?
1561 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1562 `author-name`, `author-link`, `author-avatar`
1563 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1567 logger("reshared message ".$guid." already exists on system.");
1569 // Maybe it is already a reshared item?
1570 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1571 if (self::is_reshare($r[0]["body"]))
1578 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1579 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1580 $item_id = self::store_by_guid($guid, $server);
1583 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1584 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1585 $item_id = self::store_by_guid($guid, $server);
1588 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1590 $server = "https://".substr($author, strpos($author, "@") + 1);
1591 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1592 $item_id = self::store_by_guid($guid, $server);
1595 $server = "http://".substr($author, strpos($author, "@") + 1);
1596 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1597 $item_id = self::store_by_guid($guid, $server);
1601 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1602 `author-name`, `author-link`, `author-avatar`
1603 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1614 private function receive_reshare($importer, $data) {
1615 $root_author = notags(unxmlify($data->root_author));
1616 $root_guid = notags(unxmlify($data->root_guid));
1617 $guid = notags(unxmlify($data->guid));
1618 $author = notags(unxmlify($data->author));
1619 $public = notags(unxmlify($data->public));
1620 $created_at = notags(unxmlify($data->created_at));
1622 $contact = self::allowed_contact_by_handle($importer, $author, false);
1626 if (self::message_exists($importer["uid"], $guid))
1629 $original_item = self::original_item($root_guid, $root_author, $author);
1630 if (!$original_item)
1633 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1635 $datarray = array();
1637 $datarray["uid"] = $importer["uid"];
1638 $datarray["contact-id"] = $contact["id"];
1639 $datarray["network"] = NETWORK_DIASPORA;
1641 $datarray["author-name"] = $contact["name"];
1642 $datarray["author-link"] = $contact["url"];
1643 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1645 $datarray["owner-name"] = $datarray["author-name"];
1646 $datarray["owner-link"] = $datarray["author-link"];
1647 $datarray["owner-avatar"] = $datarray["author-avatar"];
1649 $datarray["guid"] = $guid;
1650 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1652 $datarray["verb"] = ACTIVITY_POST;
1653 $datarray["gravity"] = GRAVITY_PARENT;
1655 $datarray["object"] = json_encode($data);
1657 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1658 $original_item["guid"], $original_item["created"], $orig_url);
1659 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1661 $datarray["tag"] = $original_item["tag"];
1662 $datarray["app"] = $original_item["app"];
1664 $datarray["plink"] = self::plink($author, $guid);
1665 $datarray["private"] = (($public == "false") ? 1 : 0);
1666 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1668 $datarray["object-type"] = $original_item["object-type"];
1670 self::fetch_guid($datarray);
1671 $message_id = item_store($datarray);
1674 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1679 private function item_retraction($importer, $contact, $data) {
1680 $target_type = notags(unxmlify($data->target_type));
1681 $target_guid = notags(unxmlify($data->target_guid));
1682 $author = notags(unxmlify($data->author));
1684 $person = self::person_by_handle($author);
1685 if (!is_array($person)) {
1686 logger("unable to find author detail for ".$author);
1690 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1691 dbesc($target_guid),
1692 intval($importer["uid"])
1697 // Only delete it if the author really fits
1698 if (!link_compare($r[0]["author-link"], $person["url"])) {
1699 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
1703 // Check if the sender is the thread owner
1704 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
1705 intval($r[0]["parent"]));
1707 // Only delete it if the parent author really fits
1708 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
1709 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
1713 // 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
1714 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1715 dbesc(datetime_convert()),
1716 dbesc(datetime_convert()),
1719 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1721 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
1723 // Now check if the retraction needs to be relayed by us
1724 if($p[0]["origin"]) {
1726 // Formerly we stored the signed text, the signature and the author in different fields.
1727 // We now store the raw data so that we are more flexible.
1728 q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1729 intval($r[0]["id"]),
1730 dbesc(json_encode($data))
1732 $s = q("select * from sign where retract_iid = %d", intval($r[0]["id"]));
1733 logger("Stored signatur for item ".$r[0]["id"]." - ".print_r($s, true), LOGGER_DEBUG);
1736 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1740 private function receive_retraction($importer, $sender, $data) {
1741 $target_type = notags(unxmlify($data->target_type));
1743 $contact = self::contact_by_handle($importer["uid"], $sender);
1745 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1749 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
1751 switch ($target_type) {
1754 case "Post": // "Post" will be supported in a future version
1756 case "StatusMessage":
1757 return self::item_retraction($importer, $contact, $data);;
1760 /// @todo What should we do with an "unshare"?
1761 // Removing the contact isn't correct since we still can read the public items
1762 //contact_remove($contact["id"]);
1766 logger("Unknown target type ".$target_type);
1772 private function receive_status_message($importer, $data) {
1774 $raw_message = unxmlify($data->raw_message);
1775 $guid = notags(unxmlify($data->guid));
1776 $author = notags(unxmlify($data->author));
1777 $public = notags(unxmlify($data->public));
1778 $created_at = notags(unxmlify($data->created_at));
1779 $provider_display_name = notags(unxmlify($data->provider_display_name));
1781 /// @todo enable support for polls
1782 //if ($data->poll) {
1783 // foreach ($data->poll AS $poll)
1787 $contact = self::allowed_contact_by_handle($importer, $author, false);
1791 if (self::message_exists($importer["uid"], $guid))
1795 if ($data->location)
1796 foreach ($data->location->children() AS $fieldname => $data)
1797 $address[$fieldname] = notags(unxmlify($data));
1799 $body = diaspora2bb($raw_message);
1801 $datarray = array();
1804 foreach ($data->photo AS $photo)
1805 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1807 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1809 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1811 // Add OEmbed and other information to the body
1812 if (!self::is_redmatrix($contact["url"]))
1813 $body = add_page_info_to_body($body, false, true);
1816 $datarray["uid"] = $importer["uid"];
1817 $datarray["contact-id"] = $contact["id"];
1818 $datarray["network"] = NETWORK_DIASPORA;
1820 $datarray["author-name"] = $contact["name"];
1821 $datarray["author-link"] = $contact["url"];
1822 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1824 $datarray["owner-name"] = $datarray["author-name"];
1825 $datarray["owner-link"] = $datarray["author-link"];
1826 $datarray["owner-avatar"] = $datarray["author-avatar"];
1828 $datarray["guid"] = $guid;
1829 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1831 $datarray["verb"] = ACTIVITY_POST;
1832 $datarray["gravity"] = GRAVITY_PARENT;
1834 $datarray["object"] = json_encode($data);
1836 $datarray["body"] = $body;
1838 if ($provider_display_name != "")
1839 $datarray["app"] = $provider_display_name;
1841 $datarray["plink"] = self::plink($author, $guid);
1842 $datarray["private"] = (($public == "false") ? 1 : 0);
1843 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1845 if (isset($address["address"]))
1846 $datarray["location"] = $address["address"];
1848 if (isset($address["lat"]) AND isset($address["lng"]))
1849 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1851 self::fetch_guid($datarray);
1852 $message_id = item_store($datarray);
1855 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1860 /******************************************************************************************
1861 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1862 ******************************************************************************************/
1864 private function my_handle($me) {
1865 if ($contact["addr"] != "")
1866 return $contact["addr"];
1868 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1869 // So - just in case - we build the the address here.
1870 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1873 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1875 logger("Message: ".$msg, LOGGER_DATA);
1877 $handle = self::my_handle($user);
1879 $b64url_data = base64url_encode($msg);
1881 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1883 $type = "application/xml";
1884 $encoding = "base64url";
1885 $alg = "RSA-SHA256";
1887 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1889 $signature = rsa_sign($signable_data,$prvkey);
1890 $sig = base64url_encode($signature);
1892 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1893 "me:env" => array("me:encoding" => "base64url",
1894 "me:alg" => "RSA-SHA256",
1896 "@attributes" => array("type" => "application/xml"),
1897 "me:sig" => $sig)));
1899 $namespaces = array("" => "https://joindiaspora.com/protocol",
1900 "me" => "http://salmon-protocol.org/ns/magic-env");
1902 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1904 logger("magic_env: ".$magic_env, LOGGER_DATA);
1908 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1910 logger("Message: ".$msg, LOGGER_DATA);
1912 // without a public key nothing will work
1915 logger("pubkey missing: contact id: ".$contact["id"]);
1919 $inner_aes_key = random_string(32);
1920 $b_inner_aes_key = base64_encode($inner_aes_key);
1921 $inner_iv = random_string(16);
1922 $b_inner_iv = base64_encode($inner_iv);
1924 $outer_aes_key = random_string(32);
1925 $b_outer_aes_key = base64_encode($outer_aes_key);
1926 $outer_iv = random_string(16);
1927 $b_outer_iv = base64_encode($outer_iv);
1929 $handle = self::my_handle($user);
1931 $padded_data = pkcs5_pad($msg,16);
1932 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1934 $b64_data = base64_encode($inner_encrypted);
1937 $b64url_data = base64url_encode($b64_data);
1938 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1940 $type = "application/xml";
1941 $encoding = "base64url";
1942 $alg = "RSA-SHA256";
1944 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1946 $signature = rsa_sign($signable_data,$prvkey);
1947 $sig = base64url_encode($signature);
1949 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1950 "aes_key" => $b_inner_aes_key,
1951 "author_id" => $handle));
1953 $decrypted_header = xml::from_array($xmldata, $xml, true);
1954 $decrypted_header = pkcs5_pad($decrypted_header,16);
1956 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1958 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1960 $encrypted_outer_key_bundle = "";
1961 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1963 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1965 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1967 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1968 "ciphertext" => base64_encode($ciphertext)));
1969 $cipher_json = base64_encode($encrypted_header_json_object);
1971 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
1972 "me:env" => array("me:encoding" => "base64url",
1973 "me:alg" => "RSA-SHA256",
1975 "@attributes" => array("type" => "application/xml"),
1976 "me:sig" => $sig)));
1978 $namespaces = array("" => "https://joindiaspora.com/protocol",
1979 "me" => "http://salmon-protocol.org/ns/magic-env");
1981 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1983 logger("magic_env: ".$magic_env, LOGGER_DATA);
1987 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1990 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1992 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1994 // The data that will be transmitted is double encoded via "urlencode", strange ...
1995 $slap = "xml=".urlencode(urlencode($magic_env));
1999 private function signature($owner, $message) {
2001 unset($sigmsg["author_signature"]);
2002 unset($sigmsg["parent_author_signature"]);
2004 $signed_text = implode(";", $sigmsg);
2006 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2009 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2013 $enabled = intval(get_config("system", "diaspora_enabled"));
2017 $logid = random_string(4);
2018 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2020 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2024 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2026 if (!$queue_run && was_recently_delayed($contact["id"])) {
2029 if (!intval(get_config("system", "diaspora_test"))) {
2030 post_url($dest_url."/", $slap);
2031 $return_code = $a->get_curl_code();
2033 logger("test_mode");
2038 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2040 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2041 logger("queue message");
2043 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2044 intval($contact["id"]),
2045 dbesc(NETWORK_DIASPORA),
2047 intval($public_batch)
2050 logger("add_to_queue ignored - identical item already in queue");
2052 // queue message for redelivery
2053 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2057 return(($return_code) ? $return_code : (-1));
2061 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "") {
2063 $data = array("XML" => array("post" => array($type => $message)));
2065 $msg = xml::from_array($data, $xml);
2067 logger('message: '.$msg, LOGGER_DATA);
2068 logger('send guid '.$guid, LOGGER_DEBUG);
2070 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2072 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2074 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2076 return $return_code;
2079 public static function send_share($owner,$contact) {
2081 $message = array("sender_handle" => self::my_handle($owner),
2082 "recipient_handle" => $contact["addr"]);
2084 return self::build_and_transmit($owner, $contact, "request", $message);
2087 public static function send_unshare($owner,$contact) {
2089 $message = array("post_guid" => $owner["guid"],
2090 "diaspora_handle" => self::my_handle($owner),
2091 "type" => "Person");
2093 return self::build_and_transmit($owner, $contact, "retraction", $message);
2096 private function is_reshare($body) {
2097 $body = trim($body);
2099 // Skip if it isn't a pure repeated messages
2100 // Does it start with a share?
2101 if (strpos($body, "[share") > 0)
2104 // Does it end with a share?
2105 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2108 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2109 // Skip if there is no shared message in there
2110 if ($body == $attributes)
2114 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2115 if ($matches[1] != "")
2116 $guid = $matches[1];
2118 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2119 if ($matches[1] != "")
2120 $guid = $matches[1];
2123 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2124 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2127 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2128 $ret["root_guid"] = $guid;
2134 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2135 if ($matches[1] != "")
2136 $profile = $matches[1];
2138 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2139 if ($matches[1] != "")
2140 $profile = $matches[1];
2144 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2145 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2149 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2150 if ($matches[1] != "")
2151 $link = $matches[1];
2153 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2154 if ($matches[1] != "")
2155 $link = $matches[1];
2157 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2158 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2163 public static function send_status($item, $owner, $contact, $public_batch = false) {
2165 $myaddr = self::my_handle($owner);
2167 $public = (($item["private"]) ? "false" : "true");
2169 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2171 // Detect a share element and do a reshare
2172 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2173 $message = array("root_diaspora_id" => $ret["root_handle"],
2174 "root_guid" => $ret["root_guid"],
2175 "guid" => $item["guid"],
2176 "diaspora_handle" => $myaddr,
2177 "public" => $public,
2178 "created_at" => $created,
2179 "provider_display_name" => $item["app"]);
2183 $title = $item["title"];
2184 $body = $item["body"];
2186 // convert to markdown
2187 $body = html_entity_decode(bb2diaspora($body));
2191 $body = "## ".html_entity_decode($title)."\n\n".$body;
2193 if ($item["attach"]) {
2194 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2196 $body .= "\n".t("Attachments:")."\n";
2197 foreach($matches as $mtch)
2198 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2202 $location = array();
2204 if ($item["location"] != "")
2205 $location["address"] = $item["location"];
2207 if ($item["coord"] != "") {
2208 $coord = explode(" ", $item["coord"]);
2209 $location["lat"] = $coord[0];
2210 $location["lng"] = $coord[1];
2213 $message = array("raw_message" => $body,
2214 "location" => $location,
2215 "guid" => $item["guid"],
2216 "diaspora_handle" => $myaddr,
2217 "public" => $public,
2218 "created_at" => $created,
2219 "provider_display_name" => $item["app"]);
2221 if (count($location) == 0)
2222 unset($message["location"]);
2224 $type = "status_message";
2227 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2230 private function construct_like($item, $owner) {
2232 $myaddr = self::my_handle($owner);
2234 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2235 dbesc($item["thr-parent"]));
2241 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2244 return(array("positive" => $positive,
2245 "guid" => $item["guid"],
2246 "target_type" => $target_type,
2247 "parent_guid" => $parent["guid"],
2248 "author_signature" => $authorsig,
2249 "diaspora_handle" => $myaddr));
2252 private function construct_comment($item, $owner) {
2254 $myaddr = self::my_handle($owner);
2256 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2257 intval($item["parent"]),
2258 intval($item["parent"])
2266 $text = html_entity_decode(bb2diaspora($item["body"]));
2268 return(array("guid" => $item["guid"],
2269 "parent_guid" => $parent["guid"],
2270 "author_signature" => "",
2272 "diaspora_handle" => $myaddr));
2275 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2277 if($item['verb'] === ACTIVITY_LIKE) {
2278 $message = self::construct_like($item, $owner);
2281 $message = self::construct_comment($item, $owner);
2288 $message["author_signature"] = self::signature($owner, $message);
2290 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2293 private function message_from_signatur($item, $signature) {
2295 // Split the signed text
2296 $signed_parts = explode(";", $signature['signed_text']);
2298 if ($item["deleted"])
2299 $message = array("parent_author_signature" => "",
2300 "target_guid" => $signed_parts[0],
2301 "target_type" => $signed_parts[1],
2302 "sender_handle" => $signature['signer'],
2303 "target_author_signature" => $signature['signature']);
2304 elseif ($item['verb'] === ACTIVITY_LIKE)
2305 $message = array("positive" => $signed_parts[0],
2306 "guid" => $signed_parts[1],
2307 "target_type" => $signed_parts[2],
2308 "parent_guid" => $signed_parts[3],
2309 "parent_author_signature" => "",
2310 "author_signature" => $signature['signature'],
2311 "diaspora_handle" => $signed_parts[4]);
2313 // Remove the comment guid
2314 $guid = array_shift($signed_parts);
2316 // Remove the parent guid
2317 $parent_guid = array_shift($signed_parts);
2319 // Remove the handle
2320 $handle = array_pop($signed_parts);
2322 // Glue the parts together
2323 $text = implode(";", $signed_parts);
2325 $message = array("guid" => $guid,
2326 "parent_guid" => $parent_guid,
2327 "parent_author_signature" => "",
2328 "author_signature" => $signature['signature'],
2329 "text" => implode(";", $signed_parts),
2330 "diaspora_handle" => $handle);
2335 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2337 if ($item["deleted"]) {
2338 $sql_sign_id = "retract_iid";
2339 $type = "relayable_retraction";
2340 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2341 $sql_sign_id = "iid";
2344 $sql_sign_id = "iid";
2348 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2350 // fetch the original signature
2352 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2353 intval($item["id"]));
2356 return self::send_followup($item, $owner, $contact, $public_batch);
2360 // Old way - is used by the internal Friendica functions
2361 /// @todo Change all signatur storing functions to the new format
2362 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2363 $message = self::message_from_signatur($item, $signature);
2365 $msg = json_decode($signature['signed_text'], true);
2368 foreach ($msg AS $field => $data) {
2369 if (!$item["deleted"]) {
2370 if ($field == "author")
2371 $field = "diaspora_handle";
2372 if ($field == "parent_type")
2373 $field = "target_type";
2376 $message[$field] = $data;
2380 if ($item["deleted"]) {
2381 $signed_text = $message["target_guid"].';'.$message["target_type"];
2382 $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2384 $message["parent_author_signature"] = self::signature($owner, $message);
2386 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2388 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2391 public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2393 $myaddr = self::my_handle($owner);
2395 // Check whether the retraction is for a top-level post or whether it's a relayable
2396 if ($item["uri"] !== $item["parent-uri"]) {
2397 $msg_type = "relayable_retraction";
2398 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2400 $msg_type = "signed_retraction";
2401 $target_type = "StatusMessage";
2404 $signed_text = $item["guid"].";".$target_type;
2406 $message = array("target_guid" => $item['guid'],
2407 "target_type" => $target_type,
2408 "sender_handle" => $myaddr,
2409 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2411 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2414 public static function send_mail($item, $owner, $contact) {
2416 $myaddr = self::my_handle($owner);
2418 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2419 intval($item["convid"]),
2420 intval($item["uid"])
2424 logger("conversation not found.");
2430 "guid" => $cnv["guid"],
2431 "subject" => $cnv["subject"],
2432 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2433 "diaspora_handle" => $cnv["creator"],
2434 "participant_handles" => $cnv["recips"]
2437 $body = bb2diaspora($item["body"]);
2438 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2440 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2441 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2444 "guid" => $item["guid"],
2445 "parent_guid" => $cnv["guid"],
2446 "parent_author_signature" => $sig,
2447 "author_signature" => $sig,
2449 "created_at" => $created,
2450 "diaspora_handle" => $myaddr,
2451 "conversation_guid" => $cnv["guid"]
2454 if ($item["reply"]) {
2458 $message = array("guid" => $cnv["guid"],
2459 "subject" => $cnv["subject"],
2460 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2462 "diaspora_handle" => $cnv["creator"],
2463 "participant_handles" => $cnv["recips"]);
2465 $type = "conversation";
2468 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);