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();
288 case "account_deletion":
289 return self::receive_account_deletion($importer, $fields);
292 return self::receive_comment($importer, $sender, $fields);
295 return self::receive_conversation($importer, $msg, $fields);
298 return self::receive_like($importer, $sender, $fields);
301 return self::receive_message($importer, $fields);
303 case "participation": // Not implemented
304 return self::receive_participation($importer, $fields);
306 case "photo": // Not implemented
307 return self::receive_photo($importer, $fields);
309 case "poll_participation": // Not implemented
310 return self::receive_poll_participation($importer, $fields);
313 return self::receive_profile($importer, $fields);
316 return self::receive_request($importer, $fields);
319 return self::receive_reshare($importer, $fields);
322 return self::receive_retraction($importer, $sender, $fields);
324 case "status_message":
325 return self::receive_status_message($importer, $fields);
328 logger("Unknown message type ".$type);
336 * @brief Checks if a posting is valid and fetches the data fields.
338 * This function does not only check the signature.
339 * It also does the conversion between the old and the new diaspora format.
341 * @param array $msg Array with the XML, the sender handle and the sender signature
342 * @param object $fields SimpleXML object that contains the posting when it is valid
344 * @return bool Is the posting valid?
346 private function valid_posting($msg, &$fields) {
348 $data = parse_xml_string($msg["message"], false);
350 if (!is_object($data))
353 $first_child = $data->getName();
355 // Is this the new or the old version?
356 if ($data->getName() == "XML") {
358 foreach ($data->post->children() as $child)
365 $type = $element->getName();
368 // All retractions are handled identically from now on.
369 // In the new version there will only be "retraction".
370 if (in_array($type, array("signed_retraction", "relayable_retraction")))
371 $type = "retraction";
373 $fields = new SimpleXMLElement("<".$type."/>");
377 foreach ($element->children() AS $fieldname => $entry) {
379 // Translation for the old XML structure
380 if ($fieldname == "diaspora_handle")
381 $fieldname = "author";
383 if ($fieldname == "participant_handles")
384 $fieldname = "participants";
386 if (in_array($type, array("like", "participation"))) {
387 if ($fieldname == "target_type")
388 $fieldname = "parent_type";
391 if ($fieldname == "sender_handle")
392 $fieldname = "author";
394 if ($fieldname == "recipient_handle")
395 $fieldname = "recipient";
397 if ($fieldname == "root_diaspora_id")
398 $fieldname = "root_author";
400 if ($type == "retraction") {
401 if ($fieldname == "post_guid")
402 $fieldname = "target_guid";
404 if ($fieldname == "type")
405 $fieldname = "target_type";
409 if ($fieldname == "author_signature")
410 $author_signature = base64_decode($entry);
411 elseif ($fieldname == "parent_author_signature")
412 $parent_author_signature = base64_decode($entry);
413 elseif ($fieldname != "target_author_signature") {
414 if ($signed_data != "") {
416 $signed_data_parent .= ";";
419 $signed_data .= $entry;
421 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
422 ($orig_type == "relayable_retraction"))
423 xml::copy($entry, $fields, $fieldname);
426 // This is something that shouldn't happen at all.
427 if (in_array($type, array("status_message", "reshare", "profile")))
428 if ($msg["author"] != $fields->author) {
429 logger("Message handle is not the same as envelope sender. Quitting this message.");
433 // Only some message types have signatures. So we quit here for the other types.
434 if (!in_array($type, array("comment", "message", "like")))
437 // No author_signature? This is a must, so we quit.
438 if (!isset($author_signature))
441 if (isset($parent_author_signature)) {
442 $key = self::key($msg["author"]);
444 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
448 $key = self::key($fields->author);
450 return rsa_verify($signed_data, $author_signature, $key, "sha256");
454 * @brief Fetches the public key for a given handle
456 * @param string $handle The handle
458 * @return string The public key
460 private function key($handle) {
461 logger("Fetching diaspora key for: ".$handle);
463 $r = self::person_by_handle($handle);
471 * @brief Fetches data for a given handle
473 * @param string $handle The handle
475 * @return array the queried data
477 private function person_by_handle($handle) {
479 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
480 dbesc(NETWORK_DIASPORA),
485 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
487 // update record occasionally so it doesn't get stale
488 $d = strtotime($person["updated"]." +00:00");
489 if ($d < strtotime("now - 14 days"))
493 if (!$person OR $update) {
494 logger("create or refresh", LOGGER_DEBUG);
495 $r = probe_url($handle, PROBE_DIASPORA);
497 // Note that Friendica contacts will return a "Diaspora person"
498 // if Diaspora connectivity is enabled on their server
499 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
500 self::add_fcontact($r, $update);
508 * @brief Updates the fcontact table
510 * @param array $arr The fcontact data
511 * @param bool $update Update or insert?
513 * @return string The id of the fcontact entry
515 private function add_fcontact($arr, $update = false) {
516 /// @todo Remove this function from include/network.php
519 $r = q("UPDATE `fcontact` SET
532 WHERE `url` = '%s' AND `network` = '%s'",
534 dbesc($arr["photo"]),
535 dbesc($arr["request"]),
538 dbesc($arr["batch"]),
539 dbesc($arr["notify"]),
541 dbesc($arr["confirm"]),
542 dbesc($arr["alias"]),
543 dbesc($arr["pubkey"]),
544 dbesc(datetime_convert()),
546 dbesc($arr["network"])
549 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
550 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
551 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
554 dbesc($arr["photo"]),
555 dbesc($arr["request"]),
558 dbesc($arr["batch"]),
559 dbesc($arr["notify"]),
561 dbesc($arr["confirm"]),
562 dbesc($arr["network"]),
563 dbesc($arr["alias"]),
564 dbesc($arr["pubkey"]),
565 dbesc(datetime_convert())
572 public static function handle_from_contact($contact_id) {
575 logger("contact id is ".$contact_id, LOGGER_DEBUG);
577 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
583 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
585 if($contact['addr'] != "")
586 $handle = $contact['addr'];
587 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
588 $baseurl_start = strpos($contact['url'],'://') + 3;
589 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
590 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
591 $handle = $contact['nick'].'@'.$baseurl;
598 private function contact_by_handle($uid, $handle) {
599 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
607 $handle_parts = explode("@", $handle);
608 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
609 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
620 private function post_allow($importer, $contact, $is_comment = false) {
622 // perhaps we were already sharing with this person. Now they're sharing with us.
623 // That makes us friends.
624 // Normally this should have handled by getting a request - but this could get lost
625 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
626 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
627 intval(CONTACT_IS_FRIEND),
628 intval($contact["id"]),
629 intval($importer["uid"])
631 $contact["rel"] = CONTACT_IS_FRIEND;
632 logger("defining user ".$contact["nick"]." as friend");
635 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
637 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
639 if($contact["rel"] == CONTACT_IS_FOLLOWER)
640 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
643 // Messages for the global users are always accepted
644 if ($importer["uid"] == 0)
650 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
651 $contact = self::contact_by_handle($importer["uid"], $handle);
653 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
657 if (!self::post_allow($importer, $contact, false)) {
658 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
664 private function message_exists($uid, $guid) {
665 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
671 logger("message ".$guid." already exists for user ".$uid);
678 private function fetch_guid($item) {
679 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
680 function ($match) use ($item){
681 return(self::fetch_guid_sub($match, $item));
685 private function fetch_guid_sub($match, $item) {
686 if (!self::store_by_guid($match[1], $item["author-link"]))
687 self::store_by_guid($match[1], $item["owner-link"]);
690 private function store_by_guid($guid, $server, $uid = 0) {
691 $serverparts = parse_url($server);
692 $server = $serverparts["scheme"]."://".$serverparts["host"];
694 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
696 $msg = self::message($guid, $server);
701 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
703 // Now call the dispatcher
704 return self::dispatch_public($msg);
707 private function message($guid, $server, $level = 0) {
712 // This will work for Diaspora and newer Friendica servers
713 $source_url = $server."/p/".$guid.".xml";
714 $x = fetch_url($source_url);
718 $source_xml = parse_xml_string($x, false);
720 if (!is_object($source_xml))
723 if ($source_xml->post->reshare) {
724 // Reshare of a reshare - old Diaspora version
725 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
726 } elseif ($source_xml->getName() == "reshare") {
727 // Reshare of a reshare - new Diaspora version
728 return self::message($source_xml->root_guid, $server, ++$level);
733 // Fetch the author - for the old and the new Diaspora version
734 if ($source_xml->post->status_message->diaspora_handle)
735 $author = (string)$source_xml->post->status_message->diaspora_handle;
736 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
737 $author = (string)$source_xml->author;
739 // If this isn't a "status_message" then quit
743 $msg = array("message" => $x, "author" => $author);
745 $msg["key"] = self::key($msg["author"]);
750 private function parent_item($uid, $guid, $author, $contact) {
751 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
752 `author-name`, `author-link`, `author-avatar`,
753 `owner-name`, `owner-link`, `owner-avatar`
754 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
755 intval($uid), dbesc($guid));
758 $result = self::store_by_guid($guid, $contact["url"], $uid);
761 $person = self::person_by_handle($author);
762 $result = self::store_by_guid($guid, $person["url"], $uid);
766 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
768 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
769 `author-name`, `author-link`, `author-avatar`,
770 `owner-name`, `owner-link`, `owner-avatar`
771 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
772 intval($uid), dbesc($guid));
777 logger("parent item not found: parent: ".$guid." item: ".$guid);
783 private function author_contact_by_url($contact, $person, $uid) {
785 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
786 dbesc(normalise_link($person["url"])), intval($uid));
789 $network = $r[0]["network"];
791 $cid = $contact["id"];
792 $network = NETWORK_DIASPORA;
795 return (array("cid" => $cid, "network" => $network));
798 public static function is_redmatrix($url) {
799 return(strstr($url, "/channel/"));
802 private function plink($addr, $guid) {
803 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
807 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
809 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
810 // So we try another way as well.
811 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
813 $r[0]["network"] = $s[0]["network"];
815 if ($r[0]["network"] == NETWORK_DFRN)
816 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
818 if (self::is_redmatrix($r[0]["url"]))
819 return $r[0]["url"]."/?f=&mid=".$guid;
821 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
824 private function receive_account_deletion($importer, $data) {
825 $author = notags(unxmlify($data->author));
827 $contact = self::contact_by_handle($importer["uid"], $author);
829 logger("cannot find contact for author: ".$author);
833 // We now remove the contact
834 contact_remove($contact["id"]);
838 private function receive_comment($importer, $sender, $data) {
839 $guid = notags(unxmlify($data->guid));
840 $parent_guid = notags(unxmlify($data->parent_guid));
841 $text = unxmlify($data->text);
842 $author = notags(unxmlify($data->author));
844 $contact = self::allowed_contact_by_handle($importer, $sender, true);
848 if (self::message_exists($importer["uid"], $guid))
851 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
855 $person = self::person_by_handle($author);
856 if (!is_array($person)) {
857 logger("unable to find author details");
861 // Fetch the contact id - if we know this contact
862 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
866 $datarray["uid"] = $importer["uid"];
867 $datarray["contact-id"] = $author_contact["cid"];
868 $datarray["network"] = $author_contact["network"];
870 $datarray["author-name"] = $person["name"];
871 $datarray["author-link"] = $person["url"];
872 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
874 $datarray["owner-name"] = $contact["name"];
875 $datarray["owner-link"] = $contact["url"];
876 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
878 $datarray["guid"] = $guid;
879 $datarray["uri"] = $author.":".$guid;
881 $datarray["type"] = "remote-comment";
882 $datarray["verb"] = ACTIVITY_POST;
883 $datarray["gravity"] = GRAVITY_COMMENT;
884 $datarray["parent-uri"] = $parent_item["uri"];
886 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
887 $datarray["object"] = json_encode($data);
889 $datarray["body"] = diaspora2bb($text);
891 self::fetch_guid($datarray);
893 $message_id = item_store($datarray);
895 // If we are the origin of the parent we store the original data and notify our followers
896 if($message_id AND $parent_item["origin"]) {
898 // Formerly we stored the signed text, the signature and the author in different fields.
899 // We now store the raw data so that we are more flexible.
900 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
902 dbesc(json_encode($data))
906 proc_run("php", "include/notifier.php", "comment-import", $message_id);
912 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg) {
913 $guid = notags(unxmlify($data->guid));
914 $subject = notags(unxmlify($data->subject));
915 $author = notags(unxmlify($data->author));
919 $msg_guid = notags(unxmlify($mesg->guid));
920 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
921 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
922 $msg_author_signature = notags(unxmlify($mesg->author_signature));
923 $msg_text = unxmlify($mesg->text);
924 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
926 // "diaspora_handle" is the element name from the old version
927 // "author" is the element name from the new version
929 $msg_author = notags(unxmlify($mesg->author));
930 elseif ($mesg->diaspora_handle)
931 $msg_author = notags(unxmlify($mesg->diaspora_handle));
935 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
937 if($msg_conversation_guid != $guid) {
938 logger("message conversation guid does not belong to the current conversation.");
942 $body = diaspora2bb($msg_text);
943 $message_uri = $msg_author.":".$msg_guid;
945 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
947 $author_signature = base64_decode($msg_author_signature);
949 if(strcasecmp($msg_author,$msg["author"]) == 0) {
953 $person = self::person_by_handle($msg_author);
955 if (is_array($person) && x($person, "pubkey"))
956 $key = $person["pubkey"];
958 logger("unable to find author details");
963 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
964 logger("verification failed.");
968 if($msg_parent_author_signature) {
969 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
971 $parent_author_signature = base64_decode($msg_parent_author_signature);
975 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
976 logger("owner verification failed.");
981 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
985 logger("duplicate message already delivered.", LOGGER_DEBUG);
989 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
990 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
991 intval($importer["uid"]),
993 intval($conversation["id"]),
994 dbesc($person["name"]),
995 dbesc($person["photo"]),
996 dbesc($person["url"]),
997 intval($contact["id"]),
1002 dbesc($message_uri),
1003 dbesc($author.":".$guid),
1004 dbesc($msg_created_at)
1007 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1008 dbesc(datetime_convert()),
1009 intval($conversation["id"])
1013 "type" => NOTIFY_MAIL,
1014 "notify_flags" => $importer["notify-flags"],
1015 "language" => $importer["language"],
1016 "to_name" => $importer["username"],
1017 "to_email" => $importer["email"],
1018 "uid" =>$importer["uid"],
1019 "item" => array("subject" => $subject, "body" => $body),
1020 "source_name" => $person["name"],
1021 "source_link" => $person["url"],
1022 "source_photo" => $person["thumb"],
1023 "verb" => ACTIVITY_POST,
1028 private function receive_conversation($importer, $msg, $data) {
1029 $guid = notags(unxmlify($data->guid));
1030 $subject = notags(unxmlify($data->subject));
1031 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1032 $author = notags(unxmlify($data->author));
1033 $participants = notags(unxmlify($data->participants));
1035 $messages = $data->message;
1037 if (!count($messages)) {
1038 logger("empty conversation");
1042 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1046 $conversation = null;
1048 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1049 intval($importer["uid"]),
1053 $conversation = $c[0];
1055 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1056 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1057 intval($importer["uid"]),
1060 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1061 dbesc(datetime_convert()),
1063 dbesc($participants)
1066 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1067 intval($importer["uid"]),
1072 $conversation = $c[0];
1074 if (!$conversation) {
1075 logger("unable to create conversation.");
1079 foreach($messages as $mesg)
1080 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg);
1085 private function construct_like_body($contact, $parent_item, $guid) {
1086 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1088 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1089 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1090 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1092 return sprintf($bodyverb, $ulink, $alink, $plink);
1095 private function construct_like_object($importer, $parent_item) {
1096 $objtype = ACTIVITY_OBJ_NOTE;
1097 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1098 $parent_body = $parent_item["body"];
1100 $xmldata = array("object" => array("type" => $objtype,
1102 "id" => $parent_item["uri"],
1105 "content" => $parent_body));
1107 return xml::from_array($xmldata, $xml, true);
1110 private function receive_like($importer, $sender, $data) {
1111 $positive = notags(unxmlify($data->positive));
1112 $guid = notags(unxmlify($data->guid));
1113 $parent_type = notags(unxmlify($data->parent_type));
1114 $parent_guid = notags(unxmlify($data->parent_guid));
1115 $author = notags(unxmlify($data->author));
1117 // likes on comments aren't supported by Diaspora - only on posts
1118 // But maybe this will be supported in the future, so we will accept it.
1119 if (!in_array($parent_type, array("Post", "Comment")))
1122 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1126 if (self::message_exists($importer["uid"], $guid))
1129 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1133 $person = self::person_by_handle($author);
1134 if (!is_array($person)) {
1135 logger("unable to find author details");
1139 // Fetch the contact id - if we know this contact
1140 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1142 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1143 // We would accept this anyhow.
1144 if ($positive === "true")
1145 $verb = ACTIVITY_LIKE;
1147 $verb = ACTIVITY_DISLIKE;
1149 $datarray = array();
1151 $datarray["uid"] = $importer["uid"];
1152 $datarray["contact-id"] = $author_contact["cid"];
1153 $datarray["network"] = $author_contact["network"];
1155 $datarray["author-name"] = $person["name"];
1156 $datarray["author-link"] = $person["url"];
1157 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1159 $datarray["owner-name"] = $contact["name"];
1160 $datarray["owner-link"] = $contact["url"];
1161 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1163 $datarray["guid"] = $guid;
1164 $datarray["uri"] = $author.":".$guid;
1166 $datarray["type"] = "activity";
1167 $datarray["verb"] = $verb;
1168 $datarray["gravity"] = GRAVITY_LIKE;
1169 $datarray["parent-uri"] = $parent_item["uri"];
1171 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1172 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1174 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1176 $message_id = item_store($datarray);
1178 // If we are the origin of the parent we store the original data and notify our followers
1179 if($message_id AND $parent_item["origin"]) {
1181 // Formerly we stored the signed text, the signature and the author in different fields.
1182 // We now store the raw data so that we are more flexible.
1183 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1184 intval($message_id),
1185 dbesc(json_encode($data))
1189 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1195 private function receive_message($importer, $data) {
1196 $guid = notags(unxmlify($data->guid));
1197 $parent_guid = notags(unxmlify($data->parent_guid));
1198 $text = unxmlify($data->text);
1199 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1200 $author = notags(unxmlify($data->author));
1201 $conversation_guid = notags(unxmlify($data->conversation_guid));
1203 $contact = self::allowed_contact_by_handle($importer, $author, true);
1207 $conversation = null;
1209 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1210 intval($importer["uid"]),
1211 dbesc($conversation_guid)
1214 $conversation = $c[0];
1216 logger("conversation not available.");
1222 $body = diaspora2bb($text);
1223 $message_uri = $author.":".$guid;
1225 $person = self::person_by_handle($author);
1227 logger("unable to find author details");
1231 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1232 dbesc($message_uri),
1233 intval($importer["uid"])
1236 logger("duplicate message already delivered.", LOGGER_DEBUG);
1240 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1241 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1242 intval($importer["uid"]),
1244 intval($conversation["id"]),
1245 dbesc($person["name"]),
1246 dbesc($person["photo"]),
1247 dbesc($person["url"]),
1248 intval($contact["id"]),
1249 dbesc($conversation["subject"]),
1253 dbesc($message_uri),
1254 dbesc($author.":".$parent_guid),
1258 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1259 dbesc(datetime_convert()),
1260 intval($conversation["id"])
1266 private function receive_participation($importer, $data) {
1267 // I'm not sure if we can fully support this message type
1271 private function receive_photo($importer, $data) {
1272 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1276 private function receive_poll_participation($importer, $data) {
1277 // We don't support polls by now
1281 private function receive_profile($importer, $data) {
1282 $author = notags(unxmlify($data->author));
1284 $contact = self::contact_by_handle($importer["uid"], $author);
1288 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1289 $image_url = unxmlify($data->image_url);
1290 $birthday = unxmlify($data->birthday);
1291 $location = diaspora2bb(unxmlify($data->location));
1292 $about = diaspora2bb(unxmlify($data->bio));
1293 $gender = unxmlify($data->gender);
1294 $searchable = (unxmlify($data->searchable) == "true");
1295 $nsfw = (unxmlify($data->nsfw) == "true");
1296 $tags = unxmlify($data->tag_string);
1298 $tags = explode("#", $tags);
1300 $keywords = array();
1301 foreach ($tags as $tag) {
1302 $tag = trim(strtolower($tag));
1307 $keywords = implode(", ", $keywords);
1309 $handle_parts = explode("@", $author);
1310 $nick = $handle_parts[0];
1313 $name = $handle_parts[0];
1315 if( preg_match("|^https?://|", $image_url) === 0)
1316 $image_url = "http://".$handle_parts[1].$image_url;
1318 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1320 // Generic birthday. We don't know the timezone. The year is irrelevant.
1322 $birthday = str_replace("1000", "1901", $birthday);
1324 if ($birthday != "")
1325 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1327 // this is to prevent multiple birthday notifications in a single year
1328 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1330 if(substr($birthday,5) === substr($contact["bd"],5))
1331 $birthday = $contact["bd"];
1333 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1334 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1338 dbesc(datetime_convert()),
1344 intval($contact["id"]),
1345 intval($importer["uid"])
1349 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1350 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1353 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1354 "photo" => $image_url, "name" => $name, "location" => $location,
1355 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1356 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1357 "hide" => !$searchable, "nsfw" => $nsfw);
1359 update_gcontact($gcontact);
1364 private function receive_request_make_friend($importer, $contact) {
1368 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1369 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1370 intval(CONTACT_IS_FRIEND),
1371 intval($contact["id"]),
1372 intval($importer["uid"])
1375 // send notification
1377 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1378 intval($importer["uid"])
1381 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1383 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1384 intval($importer["uid"])
1387 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1389 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1392 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1393 $arr["uid"] = $importer["uid"];
1394 $arr["contact-id"] = $self[0]["id"];
1396 $arr["type"] = 'wall';
1397 $arr["gravity"] = 0;
1399 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1400 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1401 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1402 $arr["verb"] = ACTIVITY_FRIEND;
1403 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1405 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1406 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1407 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1408 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1410 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1411 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1412 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1413 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1414 $arr["object"] .= "</link></object>\n";
1415 $arr["last-child"] = 1;
1417 $arr["allow_cid"] = $user[0]["allow_cid"];
1418 $arr["allow_gid"] = $user[0]["allow_gid"];
1419 $arr["deny_cid"] = $user[0]["deny_cid"];
1420 $arr["deny_gid"] = $user[0]["deny_gid"];
1422 $i = item_store($arr);
1424 proc_run("php", "include/notifier.php", "activity", $i);
1431 private function receive_request($importer, $data) {
1432 $author = unxmlify($data->author);
1433 $recipient = unxmlify($data->recipient);
1435 if (!$author || !$recipient)
1438 $contact = self::contact_by_handle($importer["uid"],$author);
1442 // perhaps we were already sharing with this person. Now they're sharing with us.
1443 // That makes us friends.
1445 self::receive_request_make_friend($importer, $contact);
1449 $ret = self::person_by_handle($author);
1451 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1452 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1456 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1458 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1459 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1460 intval($importer["uid"]),
1461 dbesc($ret["network"]),
1462 dbesc($ret["addr"]),
1465 dbesc(normalise_link($ret["url"])),
1467 dbesc($ret["name"]),
1468 dbesc($ret["nick"]),
1469 dbesc($ret["photo"]),
1470 dbesc($ret["pubkey"]),
1471 dbesc($ret["notify"]),
1472 dbesc($ret["poll"]),
1477 // find the contact record we just created
1479 $contact_record = self::contact_by_handle($importer["uid"],$author);
1481 if (!$contact_record) {
1482 logger("unable to locate newly created contact record.");
1486 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1487 intval($importer["uid"])
1490 if($g && intval($g[0]["def_gid"]))
1491 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1493 if($importer["page-flags"] == PAGE_NORMAL) {
1495 $hash = random_string().(string)time(); // Generate a confirm_key
1497 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1498 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1499 intval($importer["uid"]),
1500 intval($contact_record["id"]),
1503 dbesc(t("Sharing notification from Diaspora network")),
1505 dbesc(datetime_convert())
1509 // automatic friend approval
1511 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1513 // technically they are sharing with us (CONTACT_IS_SHARING),
1514 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1515 // we are going to change the relationship and make them a follower.
1517 if($importer["page-flags"] == PAGE_FREELOVE)
1518 $new_relation = CONTACT_IS_FRIEND;
1520 $new_relation = CONTACT_IS_FOLLOWER;
1522 $r = q("UPDATE `contact` SET `rel` = %d,
1530 intval($new_relation),
1531 dbesc(datetime_convert()),
1532 dbesc(datetime_convert()),
1533 intval($contact_record["id"])
1536 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1538 $ret = self::send_share($u[0], $contact_record);
1544 private function original_item($guid, $orig_author, $author) {
1546 // Do we already have this item?
1547 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1548 `author-name`, `author-link`, `author-avatar`
1549 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1553 logger("reshared message ".$guid." already exists on system.");
1555 // Maybe it is already a reshared item?
1556 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1557 if (self::is_reshare($r[0]["body"]))
1564 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1565 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1566 $item_id = self::store_by_guid($guid, $server);
1569 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1570 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1571 $item_id = self::store_by_guid($guid, $server);
1574 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1576 $server = "https://".substr($author, strpos($author, "@") + 1);
1577 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1578 $item_id = self::store_by_guid($guid, $server);
1581 $server = "http://".substr($author, strpos($author, "@") + 1);
1582 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1583 $item_id = self::store_by_guid($guid, $server);
1587 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1588 `author-name`, `author-link`, `author-avatar`
1589 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1600 private function receive_reshare($importer, $data) {
1601 $root_author = notags(unxmlify($data->root_author));
1602 $root_guid = notags(unxmlify($data->root_guid));
1603 $guid = notags(unxmlify($data->guid));
1604 $author = notags(unxmlify($data->author));
1605 $public = notags(unxmlify($data->public));
1606 $created_at = notags(unxmlify($data->created_at));
1608 $contact = self::allowed_contact_by_handle($importer, $author, false);
1612 if (self::message_exists($importer["uid"], $guid))
1615 $original_item = self::original_item($root_guid, $root_author, $author);
1616 if (!$original_item)
1619 $datarray = array();
1621 $datarray["uid"] = $importer["uid"];
1622 $datarray["contact-id"] = $contact["id"];
1623 $datarray["network"] = NETWORK_DIASPORA;
1625 $datarray["author-name"] = $contact["name"];
1626 $datarray["author-link"] = $contact["url"];
1627 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1629 $datarray["owner-name"] = $datarray["author-name"];
1630 $datarray["owner-link"] = $datarray["author-link"];
1631 $datarray["owner-avatar"] = $datarray["author-avatar"];
1633 $datarray["guid"] = $guid;
1634 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1636 $datarray["verb"] = ACTIVITY_POST;
1637 $datarray["gravity"] = GRAVITY_PARENT;
1639 $datarray["object"] = json_encode($data);
1641 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1642 $original_item["guid"], $original_item["created"], $original_item["uri"]);
1643 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1645 $datarray["tag"] = $original_item["tag"];
1646 $datarray["app"] = $original_item["app"];
1648 $datarray["plink"] = self::plink($author, $guid);
1649 $datarray["private"] = (($public == "false") ? 1 : 0);
1650 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1652 $datarray["object-type"] = $original_item["object-type"];
1654 self::fetch_guid($datarray);
1655 $message_id = item_store($datarray);
1660 private function item_retraction($importer, $contact, $data) {
1661 $target_type = notags(unxmlify($data->target_type));
1662 $target_guid = notags(unxmlify($data->target_guid));
1663 $author = notags(unxmlify($data->author));
1665 $person = self::person_by_handle($author);
1666 if (!is_array($person)) {
1667 logger("unable to find author detail for ".$author);
1671 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1672 dbesc($target_guid),
1673 intval($importer["uid"])
1678 // Only delete it if the author really fits
1679 if (!link_compare($r[0]["author-link"],$person["url"]))
1682 // Check if the sender is the thread owner
1683 $p = q("SELECT `author-link`, `origin` FROM `item` WHERE `id` = %d",
1684 intval($r[0]["parent"]));
1686 // Only delete it if the parent author really fits
1687 if (!link_compare($p[0]["author-link"], $contact["url"]))
1690 // 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
1691 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1692 dbesc(datetime_convert()),
1693 dbesc(datetime_convert()),
1696 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1698 // Now check if the retraction needs to be relayed by us
1699 if($p[0]["origin"]) {
1701 // Formerly we stored the signed text, the signature and the author in different fields.
1702 // We now store the raw data so that we are more flexible.
1703 q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1704 intval($r[0]["id"]),
1705 dbesc(json_encode($data))
1709 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1713 private function receive_retraction($importer, $sender, $data) {
1714 $target_type = notags(unxmlify($data->target_type));
1716 $contact = self::contact_by_handle($importer["uid"], $sender);
1718 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1722 switch ($target_type) {
1725 case "Post": // "Post" will be supported in a future version
1727 case "StatusMessage":
1728 return self::item_retraction($importer, $contact, $data);;
1731 /// @todo What should we do with an "unshare"?
1732 // Removing the contact isn't correct since we still can read the public items
1733 //contact_remove($contact["id"]);
1737 logger("Unknown target type ".$target_type);
1743 private function receive_status_message($importer, $data) {
1745 $raw_message = unxmlify($data->raw_message);
1746 $guid = notags(unxmlify($data->guid));
1747 $author = notags(unxmlify($data->author));
1748 $public = notags(unxmlify($data->public));
1749 $created_at = notags(unxmlify($data->created_at));
1750 $provider_display_name = notags(unxmlify($data->provider_display_name));
1752 /// @todo enable support for polls
1753 //if ($data->poll) {
1754 // foreach ($data->poll AS $poll)
1758 $contact = self::allowed_contact_by_handle($importer, $author, false);
1762 if (self::message_exists($importer["uid"], $guid))
1766 if ($data->location)
1767 foreach ($data->location->children() AS $fieldname => $data)
1768 $address[$fieldname] = notags(unxmlify($data));
1770 $body = diaspora2bb($raw_message);
1772 $datarray = array();
1775 foreach ($data->photo AS $photo)
1776 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1778 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1780 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1782 // Add OEmbed and other information to the body
1783 if (!self::is_redmatrix($contact["url"]))
1784 $body = add_page_info_to_body($body, false, true);
1787 $datarray["uid"] = $importer["uid"];
1788 $datarray["contact-id"] = $contact["id"];
1789 $datarray["network"] = NETWORK_DIASPORA;
1791 $datarray["author-name"] = $contact["name"];
1792 $datarray["author-link"] = $contact["url"];
1793 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1795 $datarray["owner-name"] = $datarray["author-name"];
1796 $datarray["owner-link"] = $datarray["author-link"];
1797 $datarray["owner-avatar"] = $datarray["author-avatar"];
1799 $datarray["guid"] = $guid;
1800 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1802 $datarray["verb"] = ACTIVITY_POST;
1803 $datarray["gravity"] = GRAVITY_PARENT;
1805 $datarray["object"] = json_encode($data);
1807 $datarray["body"] = $body;
1809 if ($provider_display_name != "")
1810 $datarray["app"] = $provider_display_name;
1812 $datarray["plink"] = self::plink($author, $guid);
1813 $datarray["private"] = (($public == "false") ? 1 : 0);
1814 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1816 if (isset($address["address"]))
1817 $datarray["location"] = $address["address"];
1819 if (isset($address["lat"]) AND isset($address["lng"]))
1820 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1822 self::fetch_guid($datarray);
1823 $message_id = item_store($datarray);
1825 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
1830 /******************************************************************************************
1831 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1832 ******************************************************************************************/
1834 private function my_handle($me) {
1835 if ($contact["addr"] != "")
1836 return $contact["addr"];
1838 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1839 // So - just in case - we build the the address here.
1840 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1843 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1845 logger("Message: ".$msg, LOGGER_DATA);
1847 $handle = self::my_handle($user);
1849 $b64url_data = base64url_encode($msg);
1851 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1853 $type = "application/xml";
1854 $encoding = "base64url";
1855 $alg = "RSA-SHA256";
1857 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1859 $signature = rsa_sign($signable_data,$prvkey);
1860 $sig = base64url_encode($signature);
1862 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1863 "me:env" => array("me:encoding" => "base64url",
1864 "me:alg" => "RSA-SHA256",
1866 "@attributes" => array("type" => "application/xml"),
1867 "me:sig" => $sig)));
1869 $namespaces = array("" => "https://joindiaspora.com/protocol",
1870 "me" => "http://salmon-protocol.org/ns/magic-env");
1872 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1874 logger("magic_env: ".$magic_env, LOGGER_DATA);
1878 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1880 logger("Message: ".$msg, LOGGER_DATA);
1882 // without a public key nothing will work
1885 logger("pubkey missing: contact id: ".$contact["id"]);
1889 $inner_aes_key = random_string(32);
1890 $b_inner_aes_key = base64_encode($inner_aes_key);
1891 $inner_iv = random_string(16);
1892 $b_inner_iv = base64_encode($inner_iv);
1894 $outer_aes_key = random_string(32);
1895 $b_outer_aes_key = base64_encode($outer_aes_key);
1896 $outer_iv = random_string(16);
1897 $b_outer_iv = base64_encode($outer_iv);
1899 $handle = self::my_handle($user);
1901 $padded_data = pkcs5_pad($msg,16);
1902 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1904 $b64_data = base64_encode($inner_encrypted);
1907 $b64url_data = base64url_encode($b64_data);
1908 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1910 $type = "application/xml";
1911 $encoding = "base64url";
1912 $alg = "RSA-SHA256";
1914 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1916 $signature = rsa_sign($signable_data,$prvkey);
1917 $sig = base64url_encode($signature);
1919 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1920 "aes_key" => $b_inner_aes_key,
1921 "author_id" => $handle));
1923 $decrypted_header = xml::from_array($xmldata, $xml, true);
1924 $decrypted_header = pkcs5_pad($decrypted_header,16);
1926 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1928 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1930 $encrypted_outer_key_bundle = "";
1931 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1933 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1935 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1937 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1938 "ciphertext" => base64_encode($ciphertext)));
1939 $cipher_json = base64_encode($encrypted_header_json_object);
1941 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
1942 "me:env" => array("me:encoding" => "base64url",
1943 "me:alg" => "RSA-SHA256",
1945 "@attributes" => array("type" => "application/xml"),
1946 "me:sig" => $sig)));
1948 $namespaces = array("" => "https://joindiaspora.com/protocol",
1949 "me" => "http://salmon-protocol.org/ns/magic-env");
1951 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1953 logger("magic_env: ".$magic_env, LOGGER_DATA);
1957 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1960 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1962 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1964 // The data that will be transmitted is double encoded via "urlencode", strange ...
1965 $slap = "xml=".urlencode(urlencode($magic_env));
1969 private function signature($owner, $message) {
1971 unset($sigmsg["author_signature"]);
1972 unset($sigmsg["parent_author_signature"]);
1974 $signed_text = implode(";", $sigmsg);
1976 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
1979 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
1983 $enabled = intval(get_config("system", "diaspora_enabled"));
1987 $logid = random_string(4);
1988 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
1990 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
1994 logger("transmit: ".$logid."-".$guid." ".$dest_url);
1996 if (!$queue_run && was_recently_delayed($contact["id"])) {
1999 if (!intval(get_config("system", "diaspora_test"))) {
2000 post_url($dest_url."/", $slap);
2001 $return_code = $a->get_curl_code();
2003 logger("test_mode");
2008 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2010 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2011 logger("queue message");
2013 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2014 intval($contact["id"]),
2015 dbesc(NETWORK_DIASPORA),
2017 intval($public_batch)
2020 logger("add_to_queue ignored - identical item already in queue");
2022 // queue message for redelivery
2023 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2027 return(($return_code) ? $return_code : (-1));
2031 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "") {
2033 $data = array("XML" => array("post" => array($type => $message)));
2035 $msg = xml::from_array($data, $xml);
2037 logger('message: '.$msg, LOGGER_DATA);
2038 logger('send guid '.$guid, LOGGER_DEBUG);
2040 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2042 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2044 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2046 return $return_code;
2049 public static function send_share($owner,$contact) {
2051 $message = array("sender_handle" => self::my_handle($owner),
2052 "recipient_handle" => $contact["addr"]);
2054 return self::build_and_transmit($owner, $contact, "request", $message);
2057 public static function send_unshare($owner,$contact) {
2059 $message = array("post_guid" => $owner["guid"],
2060 "diaspora_handle" => self::my_handle($owner),
2061 "type" => "Person");
2063 return self::build_and_transmit($owner, $contact, "retraction", $message);
2066 private function is_reshare($body) {
2067 $body = trim($body);
2069 // Skip if it isn't a pure repeated messages
2070 // Does it start with a share?
2071 if (strpos($body, "[share") > 0)
2074 // Does it end with a share?
2075 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2078 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2079 // Skip if there is no shared message in there
2080 if ($body == $attributes)
2084 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2085 if ($matches[1] != "")
2086 $guid = $matches[1];
2088 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2089 if ($matches[1] != "")
2090 $guid = $matches[1];
2093 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2094 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2097 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2098 $ret["root_guid"] = $guid;
2104 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2105 if ($matches[1] != "")
2106 $profile = $matches[1];
2108 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2109 if ($matches[1] != "")
2110 $profile = $matches[1];
2114 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2115 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2119 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2120 if ($matches[1] != "")
2121 $link = $matches[1];
2123 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2124 if ($matches[1] != "")
2125 $link = $matches[1];
2127 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2128 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2133 public static function send_status($item, $owner, $contact, $public_batch = false) {
2135 $myaddr = self::my_handle($owner);
2137 $public = (($item["private"]) ? "false" : "true");
2139 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2141 // Detect a share element and do a reshare
2142 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2143 $message = array("root_diaspora_id" => $ret["root_handle"],
2144 "root_guid" => $ret["root_guid"],
2145 "guid" => $item["guid"],
2146 "diaspora_handle" => $myaddr,
2147 "public" => $public,
2148 "created_at" => $created,
2149 "provider_display_name" => $item["app"]);
2153 $title = $item["title"];
2154 $body = $item["body"];
2156 // convert to markdown
2157 $body = html_entity_decode(bb2diaspora($body));
2161 $body = "## ".html_entity_decode($title)."\n\n".$body;
2163 if ($item["attach"]) {
2164 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2166 $body .= "\n".t("Attachments:")."\n";
2167 foreach($matches as $mtch)
2168 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2172 $location = array();
2174 if ($item["location"] != "")
2175 $location["address"] = $item["location"];
2177 if ($item["coord"] != "") {
2178 $coord = explode(" ", $item["coord"]);
2179 $location["lat"] = $coord[0];
2180 $location["lng"] = $coord[1];
2183 $message = array("raw_message" => $body,
2184 "location" => $location,
2185 "guid" => $item["guid"],
2186 "diaspora_handle" => $myaddr,
2187 "public" => $public,
2188 "created_at" => $created,
2189 "provider_display_name" => $item["app"]);
2191 if (count($location) == 0)
2192 unset($message["location"]);
2194 $type = "status_message";
2197 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2200 private function construct_like($item, $owner) {
2202 $myaddr = self::my_handle($owner);
2204 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2205 dbesc($item["thr-parent"]));
2211 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2214 return(array("positive" => $positive,
2215 "guid" => $item["guid"],
2216 "target_type" => $target_type,
2217 "parent_guid" => $parent["guid"],
2218 "author_signature" => $authorsig,
2219 "diaspora_handle" => $myaddr));
2222 private function construct_comment($item, $owner) {
2224 $myaddr = self::my_handle($owner);
2226 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2227 intval($item["parent"]),
2228 intval($item["parent"])
2236 $text = html_entity_decode(bb2diaspora($item["body"]));
2238 return(array("guid" => $item["guid"],
2239 "parent_guid" => $parent["guid"],
2240 "author_signature" => "",
2242 "diaspora_handle" => $myaddr));
2245 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2247 if($item['verb'] === ACTIVITY_LIKE) {
2248 $message = self::construct_like($item, $owner);
2251 $message = self::construct_comment($item, $owner);
2258 $message["author_signature"] = self::signature($owner, $message);
2260 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2263 private function message_from_signatur($item, $signature) {
2265 // Split the signed text
2266 $signed_parts = explode(";", $signature['signed_text']);
2268 if ($item["deleted"])
2269 $message = array("parent_author_signature" => "",
2270 "target_guid" => $signed_parts[0],
2271 "target_type" => $signed_parts[1],
2272 "sender_handle" => $signature['signer'],
2273 "target_author_signature" => $signature['signature']);
2274 elseif ($item['verb'] === ACTIVITY_LIKE)
2275 $message = array("positive" => $signed_parts[0],
2276 "guid" => $signed_parts[1],
2277 "target_type" => $signed_parts[2],
2278 "parent_guid" => $signed_parts[3],
2279 "parent_author_signature" => "",
2280 "author_signature" => $signature['signature'],
2281 "diaspora_handle" => $signed_parts[4]);
2283 // Remove the comment guid
2284 $guid = array_shift($signed_parts);
2286 // Remove the parent guid
2287 $parent_guid = array_shift($signed_parts);
2289 // Remove the handle
2290 $handle = array_pop($signed_parts);
2292 // Glue the parts together
2293 $text = implode(";", $signed_parts);
2295 $message = array("guid" => $guid,
2296 "parent_guid" => $parent_guid,
2297 "parent_author_signature" => "",
2298 "author_signature" => $signature['signature'],
2299 "text" => implode(";", $signed_parts),
2300 "diaspora_handle" => $handle);
2305 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2307 if ($item["deleted"]) {
2308 $sql_sign_id = "retract_iid";
2309 $type = "relayable_retraction";
2310 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2311 $sql_sign_id = "iid";
2314 $sql_sign_id = "iid";
2318 // fetch the original signature
2320 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2321 intval($item["id"]));
2324 return self::send_followup($item, $owner, $contact, $public_batch);
2328 // Old way - is used by the internal Friendica functions
2329 /// @todo Change all signatur storing functions to the new format
2330 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2331 $message = self::message_from_signatur($item, $signature);
2333 $message = json_decode($signature['signed_text']);
2335 if ($item["deleted"]) {
2336 $signed_text = $message["target_guid"].';'.$message["target_type"];
2337 $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2339 $message["parent_author_signature"] = self::signature($owner, $message);
2341 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2344 public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2346 $myaddr = self::my_handle($owner);
2348 // Check whether the retraction is for a top-level post or whether it's a relayable
2349 if ($item["uri"] !== $item["parent-uri"]) {
2350 $msg_type = "relayable_retraction";
2351 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2353 $msg_type = "signed_retraction";
2354 $target_type = "StatusMessage";
2357 $signed_text = $item["guid"].";".$target_type;
2359 $message = array("target_guid" => $item['guid'],
2360 "target_type" => $target_type,
2361 "sender_handle" => $myaddr,
2362 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2364 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2367 public static function send_mail($item, $owner, $contact) {
2369 $myaddr = self::my_handle($owner);
2371 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2372 intval($item["convid"]),
2373 intval($item["uid"])
2377 logger("conversation not found.");
2383 "guid" => $cnv["guid"],
2384 "subject" => $cnv["subject"],
2385 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2386 "diaspora_handle" => $cnv["creator"],
2387 "participant_handles" => $cnv["recips"]
2390 $body = bb2diaspora($item["body"]);
2391 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2393 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2394 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2397 "guid" => $item["guid"],
2398 "parent_guid" => $cnv["guid"],
2399 "parent_author_signature" => $sig,
2400 "author_signature" => $sig,
2402 "created_at" => $created,
2403 "diaspora_handle" => $myaddr,
2404 "conversation_guid" => $cnv["guid"]
2407 if ($item["reply"]) {
2411 $message = array("guid" => $cnv["guid"],
2412 "subject" => $cnv["subject"],
2413 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2415 "diaspora_handle" => $cnv["creator"],
2416 "participant_handles" => $cnv["recips"]);
2418 $type = "conversation";
2421 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);