3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
13 * - send status retraction
14 * - send comment retraction on own post
15 * - send comment retraction on diaspora post
16 * - send like retraction on own post
17 * - send like retraction on diaspora post
22 * - receive connect request
23 * - receive profile data
25 * - receive comment retraction
26 * - receive like retraction
29 * - relay comment retraction from diaspora
30 * - relay comment retraction from friendica
31 * - relay like retraction from diaspora
32 * - relay like retraction from friendica
35 * - receive account deletion
42 require_once("include/items.php");
43 require_once("include/bb2diaspora.php");
44 require_once("include/Scrape.php");
45 require_once("include/Contact.php");
46 require_once("include/Photo.php");
47 require_once("include/socgraph.php");
48 require_once("include/group.php");
49 require_once("include/xml.php");
50 require_once("include/datetime.php");
51 require_once("include/queue_fn.php");
54 * @brief This class contain functions to create and send Diaspora XML files
59 public static function relay_list() {
61 $serverdata = get_config("system", "relay_server");
62 if ($serverdata == "")
67 $servers = explode(",", $serverdata);
69 foreach($servers AS $server) {
70 $server = trim($server);
71 $batch = $server."/receive/public";
73 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
76 $addr = "relay@".str_replace("http://", "", normalise_link($server));
78 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
79 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
84 dbesc(normalise_link($server)),
86 dbesc(NETWORK_DIASPORA),
87 intval(CONTACT_IS_FOLLOWER),
88 dbesc(datetime_convert()),
89 dbesc(datetime_convert()),
90 dbesc(datetime_convert())
93 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
95 $relay[] = $relais[0];
97 $relay[] = $relais[0];
103 function repair_signature($signature, $handle = "", $level = 1) {
105 if ($signature == "")
108 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
109 $signature = base64_decode($signature);
110 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
112 // Do a recursive call to be able to fix even multiple levels
114 $signature = self::repair_signature($signature, $handle, ++$level);
121 * @brief: Decodes incoming Diaspora message
123 * @param array $importer from user table
124 * @param string $xml urldecoded Diaspora salmon
127 * 'message' -> decoded Diaspora XML message
128 * 'author' -> author diaspora handle
129 * 'key' -> author public key (converted to pkcs#8)
131 function decode($importer, $xml) {
134 $basedom = parse_xml_string($xml);
136 if (!is_object($basedom))
139 $children = $basedom->children('https://joindiaspora.com/protocol');
141 if($children->header) {
143 $author_link = str_replace('acct:','',$children->header->author_id);
146 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
148 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
149 $ciphertext = base64_decode($encrypted_header->ciphertext);
151 $outer_key_bundle = '';
152 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
154 $j_outer_key_bundle = json_decode($outer_key_bundle);
156 $outer_iv = base64_decode($j_outer_key_bundle->iv);
157 $outer_key = base64_decode($j_outer_key_bundle->key);
159 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
162 $decrypted = pkcs5_unpad($decrypted);
165 * $decrypted now contains something like
168 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
169 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
170 * <author_id>galaxor@diaspora.priateship.org</author_id>
171 * </decrypted_header>
174 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
175 $idom = parse_xml_string($decrypted,false);
177 $inner_iv = base64_decode($idom->iv);
178 $inner_aes_key = base64_decode($idom->aes_key);
180 $author_link = str_replace('acct:','',$idom->author_id);
183 $dom = $basedom->children(NAMESPACE_SALMON_ME);
185 // figure out where in the DOM tree our data is hiding
187 if($dom->provenance->data)
188 $base = $dom->provenance;
189 elseif($dom->env->data)
195 logger('unable to locate salmon data in xml');
196 http_status_exit(400);
200 // Stash the signature away for now. We have to find their key or it won't be good for anything.
201 $signature = base64url_decode($base->sig);
205 // strip whitespace so our data element will return to one big base64 blob
206 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
209 // stash away some other stuff for later
211 $type = $base->data[0]->attributes()->type[0];
212 $keyhash = $base->sig[0]->attributes()->keyhash[0];
213 $encoding = $base->encoding;
217 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
221 $data = base64url_decode($data);
225 $inner_decrypted = $data;
228 // Decode the encrypted blob
230 $inner_encrypted = base64_decode($data);
231 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
232 $inner_decrypted = pkcs5_unpad($inner_decrypted);
236 logger('Could not retrieve author URI.');
237 http_status_exit(400);
239 // Once we have the author URI, go to the web and try to find their public key
240 // (first this will look it up locally if it is in the fcontact cache)
241 // This will also convert diaspora public key from pkcs#1 to pkcs#8
243 logger('Fetching key for '.$author_link);
244 $key = self::key($author_link);
247 logger('Could not retrieve author key.');
248 http_status_exit(400);
251 $verify = rsa_verify($signed_data,$signature,$key);
254 logger('Message did not verify. Discarding.');
255 http_status_exit(400);
258 logger('Message verified.');
260 return array('message' => (string)$inner_decrypted,
261 'author' => unxmlify($author_link),
262 'key' => (string)$key);
268 * @brief Dispatches public messages and find the fitting receivers
270 * @param array $msg The post that will be dispatched
272 * @return bool Was the message accepted?
274 public static function dispatch_public($msg) {
276 $enabled = intval(get_config("system", "diaspora_enabled"));
278 logger("diaspora is disabled");
282 // Use a dummy importer to import the data for the public copy
283 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
284 $item_id = self::dispatch($importer,$msg);
286 // Now distribute it to the followers
287 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
288 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
289 AND NOT `account_expired` AND NOT `account_removed`",
290 dbesc(NETWORK_DIASPORA),
291 dbesc($msg["author"])
295 logger("delivering to: ".$rr["username"]);
296 self::dispatch($rr,$msg);
299 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
305 * @brief Dispatches the different message types to the different functions
307 * @param array $importer Array of the importer user
308 * @param array $msg The post that will be dispatched
310 * @return bool Was the message accepted?
312 public static function dispatch($importer, $msg) {
314 // The sender is the handle of the contact that sent the message.
315 // This will often be different with relayed messages (for example "like" and "comment")
316 $sender = $msg["author"];
318 if (!diaspora::valid_posting($msg, $fields)) {
319 logger("Invalid posting");
323 $type = $fields->getName();
325 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
328 case "account_deletion":
329 return self::receive_account_deletion($importer, $fields);
332 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
335 return self::receive_conversation($importer, $msg, $fields);
338 return self::receive_like($importer, $sender, $fields);
341 return self::receive_message($importer, $fields);
343 case "participation": // Not implemented
344 return self::receive_participation($importer, $fields);
346 case "photo": // Not implemented
347 return self::receive_photo($importer, $fields);
349 case "poll_participation": // Not implemented
350 return self::receive_poll_participation($importer, $fields);
353 return self::receive_profile($importer, $fields);
356 return self::receive_request($importer, $fields);
359 return self::receive_reshare($importer, $fields, $msg["message"]);
362 return self::receive_retraction($importer, $sender, $fields);
364 case "status_message":
365 return self::receive_status_message($importer, $fields, $msg["message"]);
368 logger("Unknown message type ".$type);
376 * @brief Checks if a posting is valid and fetches the data fields.
378 * This function does not only check the signature.
379 * It also does the conversion between the old and the new diaspora format.
381 * @param array $msg Array with the XML, the sender handle and the sender signature
382 * @param object $fields SimpleXML object that contains the posting when it is valid
384 * @return bool Is the posting valid?
386 private function valid_posting($msg, &$fields) {
388 $data = parse_xml_string($msg["message"], false);
390 if (!is_object($data))
393 $first_child = $data->getName();
395 // Is this the new or the old version?
396 if ($data->getName() == "XML") {
398 foreach ($data->post->children() as $child)
405 $type = $element->getName();
408 // All retractions are handled identically from now on.
409 // In the new version there will only be "retraction".
410 if (in_array($type, array("signed_retraction", "relayable_retraction")))
411 $type = "retraction";
413 $fields = new SimpleXMLElement("<".$type."/>");
417 foreach ($element->children() AS $fieldname => $entry) {
419 // Translation for the old XML structure
420 if ($fieldname == "diaspora_handle")
421 $fieldname = "author";
423 if ($fieldname == "participant_handles")
424 $fieldname = "participants";
426 if (in_array($type, array("like", "participation"))) {
427 if ($fieldname == "target_type")
428 $fieldname = "parent_type";
431 if ($fieldname == "sender_handle")
432 $fieldname = "author";
434 if ($fieldname == "recipient_handle")
435 $fieldname = "recipient";
437 if ($fieldname == "root_diaspora_id")
438 $fieldname = "root_author";
440 if ($type == "retraction") {
441 if ($fieldname == "post_guid")
442 $fieldname = "target_guid";
444 if ($fieldname == "type")
445 $fieldname = "target_type";
449 if ($fieldname == "author_signature")
450 $author_signature = base64_decode($entry);
451 elseif ($fieldname == "parent_author_signature")
452 $parent_author_signature = base64_decode($entry);
453 elseif ($fieldname != "target_author_signature") {
454 if ($signed_data != "") {
456 $signed_data_parent .= ";";
459 $signed_data .= $entry;
461 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
462 ($orig_type == "relayable_retraction"))
463 xml::copy($entry, $fields, $fieldname);
466 // This is something that shouldn't happen at all.
467 if (in_array($type, array("status_message", "reshare", "profile")))
468 if ($msg["author"] != $fields->author) {
469 logger("Message handle is not the same as envelope sender. Quitting this message.");
473 // Only some message types have signatures. So we quit here for the other types.
474 if (!in_array($type, array("comment", "message", "like")))
477 // No author_signature? This is a must, so we quit.
478 if (!isset($author_signature))
481 if (isset($parent_author_signature)) {
482 $key = self::key($msg["author"]);
484 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
488 $key = self::key($fields->author);
490 return rsa_verify($signed_data, $author_signature, $key, "sha256");
494 * @brief Fetches the public key for a given handle
496 * @param string $handle The handle
498 * @return string The public key
500 private function key($handle) {
501 $handle = strval($handle);
503 logger("Fetching diaspora key for: ".$handle);
505 $r = self::person_by_handle($handle);
513 * @brief Fetches data for a given handle
515 * @param string $handle The handle
517 * @return array the queried data
519 private function person_by_handle($handle) {
521 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
522 dbesc(NETWORK_DIASPORA),
527 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
529 // update record occasionally so it doesn't get stale
530 $d = strtotime($person["updated"]." +00:00");
531 if ($d < strtotime("now - 14 days"))
535 if (!$person OR $update) {
536 logger("create or refresh", LOGGER_DEBUG);
537 $r = probe_url($handle, PROBE_DIASPORA);
539 // Note that Friendica contacts will return a "Diaspora person"
540 // if Diaspora connectivity is enabled on their server
541 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
542 self::add_fcontact($r, $update);
550 * @brief Updates the fcontact table
552 * @param array $arr The fcontact data
553 * @param bool $update Update or insert?
555 * @return string The id of the fcontact entry
557 private function add_fcontact($arr, $update = false) {
560 $r = q("UPDATE `fcontact` SET
573 WHERE `url` = '%s' AND `network` = '%s'",
575 dbesc($arr["photo"]),
576 dbesc($arr["request"]),
579 dbesc($arr["batch"]),
580 dbesc($arr["notify"]),
582 dbesc($arr["confirm"]),
583 dbesc($arr["alias"]),
584 dbesc($arr["pubkey"]),
585 dbesc(datetime_convert()),
587 dbesc($arr["network"])
590 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
591 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
592 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
595 dbesc($arr["photo"]),
596 dbesc($arr["request"]),
599 dbesc($arr["batch"]),
600 dbesc($arr["notify"]),
602 dbesc($arr["confirm"]),
603 dbesc($arr["network"]),
604 dbesc($arr["alias"]),
605 dbesc($arr["pubkey"]),
606 dbesc(datetime_convert())
613 public static function handle_from_contact($contact_id) {
616 logger("contact id is ".$contact_id, LOGGER_DEBUG);
618 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
624 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
626 if($contact['addr'] != "")
627 $handle = $contact['addr'];
628 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
629 $baseurl_start = strpos($contact['url'],'://') + 3;
630 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
631 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
632 $handle = $contact['nick'].'@'.$baseurl;
639 private function contact_by_handle($uid, $handle) {
640 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
648 $handle_parts = explode("@", $handle);
649 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
650 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
661 private function post_allow($importer, $contact, $is_comment = false) {
663 // perhaps we were already sharing with this person. Now they're sharing with us.
664 // That makes us friends.
665 // Normally this should have handled by getting a request - but this could get lost
666 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
667 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
668 intval(CONTACT_IS_FRIEND),
669 intval($contact["id"]),
670 intval($importer["uid"])
672 $contact["rel"] = CONTACT_IS_FRIEND;
673 logger("defining user ".$contact["nick"]." as friend");
676 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
678 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
680 if($contact["rel"] == CONTACT_IS_FOLLOWER)
681 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
684 // Messages for the global users are always accepted
685 if ($importer["uid"] == 0)
691 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
692 $contact = self::contact_by_handle($importer["uid"], $handle);
694 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
698 if (!self::post_allow($importer, $contact, $is_comment)) {
699 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
705 private function message_exists($uid, $guid) {
706 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
712 logger("message ".$guid." already exists for user ".$uid);
719 private function fetch_guid($item) {
720 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
721 function ($match) use ($item){
722 return(self::fetch_guid_sub($match, $item));
726 private function fetch_guid_sub($match, $item) {
727 if (!self::store_by_guid($match[1], $item["author-link"]))
728 self::store_by_guid($match[1], $item["owner-link"]);
731 private function store_by_guid($guid, $server, $uid = 0) {
732 $serverparts = parse_url($server);
733 $server = $serverparts["scheme"]."://".$serverparts["host"];
735 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
737 $msg = self::message($guid, $server);
742 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
744 // Now call the dispatcher
745 return self::dispatch_public($msg);
748 private function message($guid, $server, $level = 0) {
753 // This will work for Diaspora and newer Friendica servers
754 $source_url = $server."/p/".$guid.".xml";
755 $x = fetch_url($source_url);
759 $source_xml = parse_xml_string($x, false);
761 if (!is_object($source_xml))
764 if ($source_xml->post->reshare) {
765 // Reshare of a reshare - old Diaspora version
766 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
767 } elseif ($source_xml->getName() == "reshare") {
768 // Reshare of a reshare - new Diaspora version
769 return self::message($source_xml->root_guid, $server, ++$level);
774 // Fetch the author - for the old and the new Diaspora version
775 if ($source_xml->post->status_message->diaspora_handle)
776 $author = (string)$source_xml->post->status_message->diaspora_handle;
777 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
778 $author = (string)$source_xml->author;
780 // If this isn't a "status_message" then quit
784 $msg = array("message" => $x, "author" => $author);
786 $msg["key"] = self::key($msg["author"]);
791 private function parent_item($uid, $guid, $author, $contact) {
792 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
793 `author-name`, `author-link`, `author-avatar`,
794 `owner-name`, `owner-link`, `owner-avatar`
795 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
796 intval($uid), dbesc($guid));
799 $result = self::store_by_guid($guid, $contact["url"], $uid);
802 $person = self::person_by_handle($author);
803 $result = self::store_by_guid($guid, $person["url"], $uid);
807 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
809 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
810 `author-name`, `author-link`, `author-avatar`,
811 `owner-name`, `owner-link`, `owner-avatar`
812 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
813 intval($uid), dbesc($guid));
818 logger("parent item not found: parent: ".$guid." - user: ".$uid);
821 logger("parent item found: parent: ".$guid." - user: ".$uid);
826 private function author_contact_by_url($contact, $person, $uid) {
828 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
829 dbesc(normalise_link($person["url"])), intval($uid));
832 $network = $r[0]["network"];
834 $cid = $contact["id"];
835 $network = NETWORK_DIASPORA;
838 return (array("cid" => $cid, "network" => $network));
841 public static function is_redmatrix($url) {
842 return(strstr($url, "/channel/"));
845 private function plink($addr, $guid) {
846 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
850 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
852 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
853 // So we try another way as well.
854 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
856 $r[0]["network"] = $s[0]["network"];
858 if ($r[0]["network"] == NETWORK_DFRN)
859 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
861 if (self::is_redmatrix($r[0]["url"]))
862 return $r[0]["url"]."/?f=&mid=".$guid;
864 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
867 private function receive_account_deletion($importer, $data) {
868 $author = notags(unxmlify($data->author));
870 $contact = self::contact_by_handle($importer["uid"], $author);
872 logger("cannot find contact for author: ".$author);
876 // We now remove the contact
877 contact_remove($contact["id"]);
881 private function receive_comment($importer, $sender, $data, $xml) {
882 $guid = notags(unxmlify($data->guid));
883 $parent_guid = notags(unxmlify($data->parent_guid));
884 $text = unxmlify($data->text);
885 $author = notags(unxmlify($data->author));
887 $contact = self::allowed_contact_by_handle($importer, $sender, true);
891 if (self::message_exists($importer["uid"], $guid))
894 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
898 $person = self::person_by_handle($author);
899 if (!is_array($person)) {
900 logger("unable to find author details");
904 // Fetch the contact id - if we know this contact
905 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
909 $datarray["uid"] = $importer["uid"];
910 $datarray["contact-id"] = $author_contact["cid"];
911 $datarray["network"] = $author_contact["network"];
913 $datarray["author-name"] = $person["name"];
914 $datarray["author-link"] = $person["url"];
915 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
917 $datarray["owner-name"] = $contact["name"];
918 $datarray["owner-link"] = $contact["url"];
919 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
921 $datarray["guid"] = $guid;
922 $datarray["uri"] = $author.":".$guid;
924 $datarray["type"] = "remote-comment";
925 $datarray["verb"] = ACTIVITY_POST;
926 $datarray["gravity"] = GRAVITY_COMMENT;
927 $datarray["parent-uri"] = $parent_item["uri"];
929 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
930 $datarray["object"] = $xml;
932 $datarray["body"] = diaspora2bb($text);
934 self::fetch_guid($datarray);
936 $message_id = item_store($datarray);
939 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
941 // If we are the origin of the parent we store the original data and notify our followers
942 if($message_id AND $parent_item["origin"]) {
944 // Formerly we stored the signed text, the signature and the author in different fields.
945 // We now store the raw data so that we are more flexible.
946 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
948 dbesc(json_encode($data))
952 proc_run("php", "include/notifier.php", "comment-import", $message_id);
958 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
959 $guid = notags(unxmlify($data->guid));
960 $subject = notags(unxmlify($data->subject));
961 $author = notags(unxmlify($data->author));
965 $msg_guid = notags(unxmlify($mesg->guid));
966 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
967 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
968 $msg_author_signature = notags(unxmlify($mesg->author_signature));
969 $msg_text = unxmlify($mesg->text);
970 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
972 // "diaspora_handle" is the element name from the old version
973 // "author" is the element name from the new version
975 $msg_author = notags(unxmlify($mesg->author));
976 elseif ($mesg->diaspora_handle)
977 $msg_author = notags(unxmlify($mesg->diaspora_handle));
981 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
983 if($msg_conversation_guid != $guid) {
984 logger("message conversation guid does not belong to the current conversation.");
988 $body = diaspora2bb($msg_text);
989 $message_uri = $msg_author.":".$msg_guid;
991 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
993 $author_signature = base64_decode($msg_author_signature);
995 if(strcasecmp($msg_author,$msg["author"]) == 0) {
999 $person = self::person_by_handle($msg_author);
1001 if (is_array($person) && x($person, "pubkey"))
1002 $key = $person["pubkey"];
1004 logger("unable to find author details");
1009 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1010 logger("verification failed.");
1014 if($msg_parent_author_signature) {
1015 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1017 $parent_author_signature = base64_decode($msg_parent_author_signature);
1021 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1022 logger("owner verification failed.");
1027 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1031 logger("duplicate message already delivered.", LOGGER_DEBUG);
1035 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1036 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1037 intval($importer["uid"]),
1039 intval($conversation["id"]),
1040 dbesc($person["name"]),
1041 dbesc($person["photo"]),
1042 dbesc($person["url"]),
1043 intval($contact["id"]),
1048 dbesc($message_uri),
1049 dbesc($author.":".$guid),
1050 dbesc($msg_created_at)
1053 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1054 dbesc(datetime_convert()),
1055 intval($conversation["id"])
1059 "type" => NOTIFY_MAIL,
1060 "notify_flags" => $importer["notify-flags"],
1061 "language" => $importer["language"],
1062 "to_name" => $importer["username"],
1063 "to_email" => $importer["email"],
1064 "uid" =>$importer["uid"],
1065 "item" => array("subject" => $subject, "body" => $body),
1066 "source_name" => $person["name"],
1067 "source_link" => $person["url"],
1068 "source_photo" => $person["thumb"],
1069 "verb" => ACTIVITY_POST,
1074 private function receive_conversation($importer, $msg, $data) {
1075 $guid = notags(unxmlify($data->guid));
1076 $subject = notags(unxmlify($data->subject));
1077 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1078 $author = notags(unxmlify($data->author));
1079 $participants = notags(unxmlify($data->participants));
1081 $messages = $data->message;
1083 if (!count($messages)) {
1084 logger("empty conversation");
1088 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1092 $conversation = null;
1094 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1095 intval($importer["uid"]),
1099 $conversation = $c[0];
1101 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1102 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1103 intval($importer["uid"]),
1106 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1107 dbesc(datetime_convert()),
1109 dbesc($participants)
1112 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1113 intval($importer["uid"]),
1118 $conversation = $c[0];
1120 if (!$conversation) {
1121 logger("unable to create conversation.");
1125 foreach($messages as $mesg)
1126 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1131 private function construct_like_body($contact, $parent_item, $guid) {
1132 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1134 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1135 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1136 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1138 return sprintf($bodyverb, $ulink, $alink, $plink);
1141 private function construct_like_object($importer, $parent_item) {
1142 $objtype = ACTIVITY_OBJ_NOTE;
1143 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1144 $parent_body = $parent_item["body"];
1146 $xmldata = array("object" => array("type" => $objtype,
1148 "id" => $parent_item["uri"],
1151 "content" => $parent_body));
1153 return xml::from_array($xmldata, $xml, true);
1156 private function receive_like($importer, $sender, $data) {
1157 $positive = notags(unxmlify($data->positive));
1158 $guid = notags(unxmlify($data->guid));
1159 $parent_type = notags(unxmlify($data->parent_type));
1160 $parent_guid = notags(unxmlify($data->parent_guid));
1161 $author = notags(unxmlify($data->author));
1163 // likes on comments aren't supported by Diaspora - only on posts
1164 // But maybe this will be supported in the future, so we will accept it.
1165 if (!in_array($parent_type, array("Post", "Comment")))
1168 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1172 if (self::message_exists($importer["uid"], $guid))
1175 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1179 $person = self::person_by_handle($author);
1180 if (!is_array($person)) {
1181 logger("unable to find author details");
1185 // Fetch the contact id - if we know this contact
1186 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1188 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1189 // We would accept this anyhow.
1190 if ($positive === "true")
1191 $verb = ACTIVITY_LIKE;
1193 $verb = ACTIVITY_DISLIKE;
1195 $datarray = array();
1197 $datarray["uid"] = $importer["uid"];
1198 $datarray["contact-id"] = $author_contact["cid"];
1199 $datarray["network"] = $author_contact["network"];
1201 $datarray["author-name"] = $person["name"];
1202 $datarray["author-link"] = $person["url"];
1203 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1205 $datarray["owner-name"] = $contact["name"];
1206 $datarray["owner-link"] = $contact["url"];
1207 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1209 $datarray["guid"] = $guid;
1210 $datarray["uri"] = $author.":".$guid;
1212 $datarray["type"] = "activity";
1213 $datarray["verb"] = $verb;
1214 $datarray["gravity"] = GRAVITY_LIKE;
1215 $datarray["parent-uri"] = $parent_item["uri"];
1217 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1218 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1220 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1222 $message_id = item_store($datarray);
1225 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1227 // If we are the origin of the parent we store the original data and notify our followers
1228 if($message_id AND $parent_item["origin"]) {
1230 // Formerly we stored the signed text, the signature and the author in different fields.
1231 // We now store the raw data so that we are more flexible.
1232 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1233 intval($message_id),
1234 dbesc(json_encode($data))
1238 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1244 private function receive_message($importer, $data) {
1245 $guid = notags(unxmlify($data->guid));
1246 $parent_guid = notags(unxmlify($data->parent_guid));
1247 $text = unxmlify($data->text);
1248 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1249 $author = notags(unxmlify($data->author));
1250 $conversation_guid = notags(unxmlify($data->conversation_guid));
1252 $contact = self::allowed_contact_by_handle($importer, $author, true);
1256 $conversation = null;
1258 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1259 intval($importer["uid"]),
1260 dbesc($conversation_guid)
1263 $conversation = $c[0];
1265 logger("conversation not available.");
1271 $body = diaspora2bb($text);
1272 $message_uri = $author.":".$guid;
1274 $person = self::person_by_handle($author);
1276 logger("unable to find author details");
1280 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1281 dbesc($message_uri),
1282 intval($importer["uid"])
1285 logger("duplicate message already delivered.", LOGGER_DEBUG);
1289 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1290 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1291 intval($importer["uid"]),
1293 intval($conversation["id"]),
1294 dbesc($person["name"]),
1295 dbesc($person["photo"]),
1296 dbesc($person["url"]),
1297 intval($contact["id"]),
1298 dbesc($conversation["subject"]),
1302 dbesc($message_uri),
1303 dbesc($author.":".$parent_guid),
1307 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1308 dbesc(datetime_convert()),
1309 intval($conversation["id"])
1315 private function receive_participation($importer, $data) {
1316 // I'm not sure if we can fully support this message type
1320 private function receive_photo($importer, $data) {
1321 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1325 private function receive_poll_participation($importer, $data) {
1326 // We don't support polls by now
1330 private function receive_profile($importer, $data) {
1331 $author = notags(unxmlify($data->author));
1333 $contact = self::contact_by_handle($importer["uid"], $author);
1337 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1338 $image_url = unxmlify($data->image_url);
1339 $birthday = unxmlify($data->birthday);
1340 $location = diaspora2bb(unxmlify($data->location));
1341 $about = diaspora2bb(unxmlify($data->bio));
1342 $gender = unxmlify($data->gender);
1343 $searchable = (unxmlify($data->searchable) == "true");
1344 $nsfw = (unxmlify($data->nsfw) == "true");
1345 $tags = unxmlify($data->tag_string);
1347 $tags = explode("#", $tags);
1349 $keywords = array();
1350 foreach ($tags as $tag) {
1351 $tag = trim(strtolower($tag));
1356 $keywords = implode(", ", $keywords);
1358 $handle_parts = explode("@", $author);
1359 $nick = $handle_parts[0];
1362 $name = $handle_parts[0];
1364 if( preg_match("|^https?://|", $image_url) === 0)
1365 $image_url = "http://".$handle_parts[1].$image_url;
1367 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1369 // Generic birthday. We don't know the timezone. The year is irrelevant.
1371 $birthday = str_replace("1000", "1901", $birthday);
1373 if ($birthday != "")
1374 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1376 // this is to prevent multiple birthday notifications in a single year
1377 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1379 if(substr($birthday,5) === substr($contact["bd"],5))
1380 $birthday = $contact["bd"];
1382 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1383 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1387 dbesc(datetime_convert()),
1393 intval($contact["id"]),
1394 intval($importer["uid"])
1398 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1399 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1402 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1403 "photo" => $image_url, "name" => $name, "location" => $location,
1404 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1405 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1406 "hide" => !$searchable, "nsfw" => $nsfw);
1408 update_gcontact($gcontact);
1410 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1415 private function receive_request_make_friend($importer, $contact) {
1419 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1420 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1421 intval(CONTACT_IS_FRIEND),
1422 intval($contact["id"]),
1423 intval($importer["uid"])
1426 // send notification
1428 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1429 intval($importer["uid"])
1432 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1434 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1435 intval($importer["uid"])
1438 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1440 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1443 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1444 $arr["uid"] = $importer["uid"];
1445 $arr["contact-id"] = $self[0]["id"];
1447 $arr["type"] = 'wall';
1448 $arr["gravity"] = 0;
1450 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1451 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1452 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1453 $arr["verb"] = ACTIVITY_FRIEND;
1454 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1456 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1457 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1458 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1459 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1461 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1462 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1463 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1464 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1465 $arr["object"] .= "</link></object>\n";
1466 $arr["last-child"] = 1;
1468 $arr["allow_cid"] = $user[0]["allow_cid"];
1469 $arr["allow_gid"] = $user[0]["allow_gid"];
1470 $arr["deny_cid"] = $user[0]["deny_cid"];
1471 $arr["deny_gid"] = $user[0]["deny_gid"];
1473 $i = item_store($arr);
1475 proc_run("php", "include/notifier.php", "activity", $i);
1482 private function receive_request($importer, $data) {
1483 $author = unxmlify($data->author);
1484 $recipient = unxmlify($data->recipient);
1486 if (!$author || !$recipient)
1489 $contact = self::contact_by_handle($importer["uid"],$author);
1493 // perhaps we were already sharing with this person. Now they're sharing with us.
1494 // That makes us friends.
1496 self::receive_request_make_friend($importer, $contact);
1500 $ret = self::person_by_handle($author);
1502 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1503 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1507 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1509 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1510 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1511 intval($importer["uid"]),
1512 dbesc($ret["network"]),
1513 dbesc($ret["addr"]),
1516 dbesc(normalise_link($ret["url"])),
1518 dbesc($ret["name"]),
1519 dbesc($ret["nick"]),
1520 dbesc($ret["photo"]),
1521 dbesc($ret["pubkey"]),
1522 dbesc($ret["notify"]),
1523 dbesc($ret["poll"]),
1528 // find the contact record we just created
1530 $contact_record = self::contact_by_handle($importer["uid"],$author);
1532 if (!$contact_record) {
1533 logger("unable to locate newly created contact record.");
1537 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1538 intval($importer["uid"])
1541 if($g && intval($g[0]["def_gid"]))
1542 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1544 if($importer["page-flags"] == PAGE_NORMAL) {
1546 $hash = random_string().(string)time(); // Generate a confirm_key
1548 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1549 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1550 intval($importer["uid"]),
1551 intval($contact_record["id"]),
1554 dbesc(t("Sharing notification from Diaspora network")),
1556 dbesc(datetime_convert())
1560 // automatic friend approval
1562 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1564 // technically they are sharing with us (CONTACT_IS_SHARING),
1565 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1566 // we are going to change the relationship and make them a follower.
1568 if($importer["page-flags"] == PAGE_FREELOVE)
1569 $new_relation = CONTACT_IS_FRIEND;
1571 $new_relation = CONTACT_IS_FOLLOWER;
1573 $r = q("UPDATE `contact` SET `rel` = %d,
1581 intval($new_relation),
1582 dbesc(datetime_convert()),
1583 dbesc(datetime_convert()),
1584 intval($contact_record["id"])
1587 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1589 $ret = self::send_share($u[0], $contact_record);
1595 private function original_item($guid, $orig_author, $author) {
1597 // Do we already have this item?
1598 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1599 `author-name`, `author-link`, `author-avatar`
1600 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1604 logger("reshared message ".$guid." already exists on system.");
1606 // Maybe it is already a reshared item?
1607 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1608 if (self::is_reshare($r[0]["body"], false))
1615 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1616 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1617 $item_id = self::store_by_guid($guid, $server);
1620 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1621 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1622 $item_id = self::store_by_guid($guid, $server);
1625 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1627 $server = "https://".substr($author, strpos($author, "@") + 1);
1628 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1629 $item_id = self::store_by_guid($guid, $server);
1632 $server = "http://".substr($author, strpos($author, "@") + 1);
1633 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1634 $item_id = self::store_by_guid($guid, $server);
1638 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1639 `author-name`, `author-link`, `author-avatar`
1640 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1651 private function receive_reshare($importer, $data, $xml) {
1652 $root_author = notags(unxmlify($data->root_author));
1653 $root_guid = notags(unxmlify($data->root_guid));
1654 $guid = notags(unxmlify($data->guid));
1655 $author = notags(unxmlify($data->author));
1656 $public = notags(unxmlify($data->public));
1657 $created_at = notags(unxmlify($data->created_at));
1659 $contact = self::allowed_contact_by_handle($importer, $author, false);
1663 if (self::message_exists($importer["uid"], $guid))
1666 $original_item = self::original_item($root_guid, $root_author, $author);
1667 if (!$original_item)
1670 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1672 $datarray = array();
1674 $datarray["uid"] = $importer["uid"];
1675 $datarray["contact-id"] = $contact["id"];
1676 $datarray["network"] = NETWORK_DIASPORA;
1678 $datarray["author-name"] = $contact["name"];
1679 $datarray["author-link"] = $contact["url"];
1680 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1682 $datarray["owner-name"] = $datarray["author-name"];
1683 $datarray["owner-link"] = $datarray["author-link"];
1684 $datarray["owner-avatar"] = $datarray["author-avatar"];
1686 $datarray["guid"] = $guid;
1687 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1689 $datarray["verb"] = ACTIVITY_POST;
1690 $datarray["gravity"] = GRAVITY_PARENT;
1692 $datarray["object"] = $xml;
1694 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1695 $original_item["guid"], $original_item["created"], $orig_url);
1696 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1698 $datarray["tag"] = $original_item["tag"];
1699 $datarray["app"] = $original_item["app"];
1701 $datarray["plink"] = self::plink($author, $guid);
1702 $datarray["private"] = (($public == "false") ? 1 : 0);
1703 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1705 $datarray["object-type"] = $original_item["object-type"];
1707 self::fetch_guid($datarray);
1708 $message_id = item_store($datarray);
1711 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1716 private function item_retraction($importer, $contact, $data) {
1717 $target_type = notags(unxmlify($data->target_type));
1718 $target_guid = notags(unxmlify($data->target_guid));
1719 $author = notags(unxmlify($data->author));
1721 $person = self::person_by_handle($author);
1722 if (!is_array($person)) {
1723 logger("unable to find author detail for ".$author);
1727 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1728 dbesc($target_guid),
1729 intval($importer["uid"])
1734 // Only delete it if the author really fits
1735 if (!link_compare($r[0]["author-link"], $person["url"])) {
1736 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
1740 // Check if the sender is the thread owner
1741 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
1742 intval($r[0]["parent"]));
1744 // Only delete it if the parent author really fits
1745 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
1746 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
1750 // 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
1751 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1752 dbesc(datetime_convert()),
1753 dbesc(datetime_convert()),
1756 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1758 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
1760 // Now check if the retraction needs to be relayed by us
1761 if($p[0]["origin"]) {
1763 // Formerly we stored the signed text, the signature and the author in different fields.
1764 // We now store the raw data so that we are more flexible.
1765 q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1766 intval($r[0]["id"]),
1767 dbesc(json_encode($data))
1769 $s = q("select * from sign where retract_iid = %d", intval($r[0]["id"]));
1770 logger("Stored signatur for item ".$r[0]["id"]." - ".print_r($s, true), LOGGER_DEBUG);
1773 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1777 private function receive_retraction($importer, $sender, $data) {
1778 $target_type = notags(unxmlify($data->target_type));
1780 $contact = self::contact_by_handle($importer["uid"], $sender);
1782 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1786 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
1788 switch ($target_type) {
1791 case "Post": // "Post" will be supported in a future version
1793 case "StatusMessage":
1794 return self::item_retraction($importer, $contact, $data);;
1797 /// @todo What should we do with an "unshare"?
1798 // Removing the contact isn't correct since we still can read the public items
1799 //contact_remove($contact["id"]);
1803 logger("Unknown target type ".$target_type);
1809 private function receive_status_message($importer, $data, $xml) {
1811 $raw_message = unxmlify($data->raw_message);
1812 $guid = notags(unxmlify($data->guid));
1813 $author = notags(unxmlify($data->author));
1814 $public = notags(unxmlify($data->public));
1815 $created_at = notags(unxmlify($data->created_at));
1816 $provider_display_name = notags(unxmlify($data->provider_display_name));
1818 /// @todo enable support for polls
1819 //if ($data->poll) {
1820 // foreach ($data->poll AS $poll)
1824 $contact = self::allowed_contact_by_handle($importer, $author, false);
1828 if (self::message_exists($importer["uid"], $guid))
1832 if ($data->location)
1833 foreach ($data->location->children() AS $fieldname => $data)
1834 $address[$fieldname] = notags(unxmlify($data));
1836 $body = diaspora2bb($raw_message);
1838 $datarray = array();
1841 foreach ($data->photo AS $photo)
1842 $body = "[img]".unxmlify($photo->remote_photo_path).
1843 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
1845 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1847 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1849 // Add OEmbed and other information to the body
1850 if (!self::is_redmatrix($contact["url"]))
1851 $body = add_page_info_to_body($body, false, true);
1854 $datarray["uid"] = $importer["uid"];
1855 $datarray["contact-id"] = $contact["id"];
1856 $datarray["network"] = NETWORK_DIASPORA;
1858 $datarray["author-name"] = $contact["name"];
1859 $datarray["author-link"] = $contact["url"];
1860 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1862 $datarray["owner-name"] = $datarray["author-name"];
1863 $datarray["owner-link"] = $datarray["author-link"];
1864 $datarray["owner-avatar"] = $datarray["author-avatar"];
1866 $datarray["guid"] = $guid;
1867 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1869 $datarray["verb"] = ACTIVITY_POST;
1870 $datarray["gravity"] = GRAVITY_PARENT;
1872 $datarray["object"] = $xml;
1874 $datarray["body"] = $body;
1876 if ($provider_display_name != "")
1877 $datarray["app"] = $provider_display_name;
1879 $datarray["plink"] = self::plink($author, $guid);
1880 $datarray["private"] = (($public == "false") ? 1 : 0);
1881 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1883 if (isset($address["address"]))
1884 $datarray["location"] = $address["address"];
1886 if (isset($address["lat"]) AND isset($address["lng"]))
1887 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1889 self::fetch_guid($datarray);
1890 $message_id = item_store($datarray);
1893 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1898 /******************************************************************************************
1899 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1900 ******************************************************************************************/
1902 private function my_handle($me) {
1903 if ($contact["addr"] != "")
1904 return $contact["addr"];
1906 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1907 // So - just in case - we build the the address here.
1908 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1911 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1913 logger("Message: ".$msg, LOGGER_DATA);
1915 $handle = self::my_handle($user);
1917 $b64url_data = base64url_encode($msg);
1919 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1921 $type = "application/xml";
1922 $encoding = "base64url";
1923 $alg = "RSA-SHA256";
1925 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1927 $signature = rsa_sign($signable_data,$prvkey);
1928 $sig = base64url_encode($signature);
1930 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1931 "me:env" => array("me:encoding" => "base64url",
1932 "me:alg" => "RSA-SHA256",
1934 "@attributes" => array("type" => "application/xml"),
1935 "me:sig" => $sig)));
1937 $namespaces = array("" => "https://joindiaspora.com/protocol",
1938 "me" => "http://salmon-protocol.org/ns/magic-env");
1940 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1942 logger("magic_env: ".$magic_env, LOGGER_DATA);
1946 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1948 logger("Message: ".$msg, LOGGER_DATA);
1950 // without a public key nothing will work
1953 logger("pubkey missing: contact id: ".$contact["id"]);
1957 $inner_aes_key = random_string(32);
1958 $b_inner_aes_key = base64_encode($inner_aes_key);
1959 $inner_iv = random_string(16);
1960 $b_inner_iv = base64_encode($inner_iv);
1962 $outer_aes_key = random_string(32);
1963 $b_outer_aes_key = base64_encode($outer_aes_key);
1964 $outer_iv = random_string(16);
1965 $b_outer_iv = base64_encode($outer_iv);
1967 $handle = self::my_handle($user);
1969 $padded_data = pkcs5_pad($msg,16);
1970 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1972 $b64_data = base64_encode($inner_encrypted);
1975 $b64url_data = base64url_encode($b64_data);
1976 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1978 $type = "application/xml";
1979 $encoding = "base64url";
1980 $alg = "RSA-SHA256";
1982 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1984 $signature = rsa_sign($signable_data,$prvkey);
1985 $sig = base64url_encode($signature);
1987 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1988 "aes_key" => $b_inner_aes_key,
1989 "author_id" => $handle));
1991 $decrypted_header = xml::from_array($xmldata, $xml, true);
1992 $decrypted_header = pkcs5_pad($decrypted_header,16);
1994 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1996 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1998 $encrypted_outer_key_bundle = "";
1999 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2001 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2003 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2005 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2006 "ciphertext" => base64_encode($ciphertext)));
2007 $cipher_json = base64_encode($encrypted_header_json_object);
2009 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2010 "me:env" => array("me:encoding" => "base64url",
2011 "me:alg" => "RSA-SHA256",
2013 "@attributes" => array("type" => "application/xml"),
2014 "me:sig" => $sig)));
2016 $namespaces = array("" => "https://joindiaspora.com/protocol",
2017 "me" => "http://salmon-protocol.org/ns/magic-env");
2019 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2021 logger("magic_env: ".$magic_env, LOGGER_DATA);
2025 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2028 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2030 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2032 // The data that will be transmitted is double encoded via "urlencode", strange ...
2033 $slap = "xml=".urlencode(urlencode($magic_env));
2037 private function signature($owner, $message) {
2039 unset($sigmsg["author_signature"]);
2040 unset($sigmsg["parent_author_signature"]);
2042 $signed_text = implode(";", $sigmsg);
2044 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2047 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2051 $enabled = intval(get_config("system", "diaspora_enabled"));
2055 $logid = random_string(4);
2056 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2058 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2062 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2064 if (!$queue_run && was_recently_delayed($contact["id"])) {
2067 if (!intval(get_config("system", "diaspora_test"))) {
2068 post_url($dest_url."/", $slap);
2069 $return_code = $a->get_curl_code();
2071 logger("test_mode");
2076 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2078 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2079 logger("queue message");
2081 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2082 intval($contact["id"]),
2083 dbesc(NETWORK_DIASPORA),
2085 intval($public_batch)
2088 logger("add_to_queue ignored - identical item already in queue");
2090 // queue message for redelivery
2091 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2095 return(($return_code) ? $return_code : (-1));
2099 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2101 $data = array("XML" => array("post" => array($type => $message)));
2103 $msg = xml::from_array($data, $xml);
2105 logger('message: '.$msg, LOGGER_DATA);
2106 logger('send guid '.$guid, LOGGER_DEBUG);
2108 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2111 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2114 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2116 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2118 return $return_code;
2121 public static function send_share($owner,$contact) {
2123 $message = array("sender_handle" => self::my_handle($owner),
2124 "recipient_handle" => $contact["addr"]);
2126 return self::build_and_transmit($owner, $contact, "request", $message);
2129 public static function send_unshare($owner,$contact) {
2131 $message = array("post_guid" => $owner["guid"],
2132 "diaspora_handle" => self::my_handle($owner),
2133 "type" => "Person");
2135 return self::build_and_transmit($owner, $contact, "retraction", $message);
2138 public static function is_reshare($body, $complete = true) {
2139 $body = trim($body);
2141 // Skip if it isn't a pure repeated messages
2142 // Does it start with a share?
2143 if (strpos($body, "[share") > 0)
2146 // Does it end with a share?
2147 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2150 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2151 // Skip if there is no shared message in there
2152 if ($body == $attributes)
2155 // If we don't do the complete check we quit here
2160 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2161 if ($matches[1] != "")
2162 $guid = $matches[1];
2164 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2165 if ($matches[1] != "")
2166 $guid = $matches[1];
2169 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2170 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2173 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2174 $ret["root_guid"] = $guid;
2180 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2181 if ($matches[1] != "")
2182 $profile = $matches[1];
2184 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2185 if ($matches[1] != "")
2186 $profile = $matches[1];
2190 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2191 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2195 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2196 if ($matches[1] != "")
2197 $link = $matches[1];
2199 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2200 if ($matches[1] != "")
2201 $link = $matches[1];
2203 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2204 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2209 public static function send_status($item, $owner, $contact, $public_batch = false) {
2211 $myaddr = self::my_handle($owner);
2213 $public = (($item["private"]) ? "false" : "true");
2215 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2217 // Detect a share element and do a reshare
2218 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2219 $message = array("root_diaspora_id" => $ret["root_handle"],
2220 "root_guid" => $ret["root_guid"],
2221 "guid" => $item["guid"],
2222 "diaspora_handle" => $myaddr,
2223 "public" => $public,
2224 "created_at" => $created,
2225 "provider_display_name" => $item["app"]);
2229 $title = $item["title"];
2230 $body = $item["body"];
2232 // convert to markdown
2233 $body = html_entity_decode(bb2diaspora($body));
2237 $body = "## ".html_entity_decode($title)."\n\n".$body;
2239 if ($item["attach"]) {
2240 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2242 $body .= "\n".t("Attachments:")."\n";
2243 foreach($matches as $mtch)
2244 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2248 $location = array();
2250 if ($item["location"] != "")
2251 $location["address"] = $item["location"];
2253 if ($item["coord"] != "") {
2254 $coord = explode(" ", $item["coord"]);
2255 $location["lat"] = $coord[0];
2256 $location["lng"] = $coord[1];
2259 $message = array("raw_message" => $body,
2260 "location" => $location,
2261 "guid" => $item["guid"],
2262 "diaspora_handle" => $myaddr,
2263 "public" => $public,
2264 "created_at" => $created,
2265 "provider_display_name" => $item["app"]);
2267 if (count($location) == 0)
2268 unset($message["location"]);
2270 $type = "status_message";
2273 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2276 private function construct_like($item, $owner) {
2278 $myaddr = self::my_handle($owner);
2280 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2281 dbesc($item["thr-parent"]));
2287 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2290 return(array("positive" => $positive,
2291 "guid" => $item["guid"],
2292 "target_type" => $target_type,
2293 "parent_guid" => $parent["guid"],
2294 "author_signature" => $authorsig,
2295 "diaspora_handle" => $myaddr));
2298 private function construct_comment($item, $owner) {
2300 $myaddr = self::my_handle($owner);
2302 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2303 intval($item["parent"]),
2304 intval($item["parent"])
2312 $text = html_entity_decode(bb2diaspora($item["body"]));
2314 return(array("guid" => $item["guid"],
2315 "parent_guid" => $parent["guid"],
2316 "author_signature" => "",
2318 "diaspora_handle" => $myaddr));
2321 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2323 if($item['verb'] === ACTIVITY_LIKE) {
2324 $message = self::construct_like($item, $owner);
2327 $message = self::construct_comment($item, $owner);
2334 $message["author_signature"] = self::signature($owner, $message);
2336 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2339 private function message_from_signatur($item, $signature) {
2341 // Split the signed text
2342 $signed_parts = explode(";", $signature['signed_text']);
2344 if ($item["deleted"])
2345 $message = array("parent_author_signature" => "",
2346 "target_guid" => $signed_parts[0],
2347 "target_type" => $signed_parts[1],
2348 "sender_handle" => $signature['signer'],
2349 "target_author_signature" => $signature['signature']);
2350 elseif ($item['verb'] === ACTIVITY_LIKE)
2351 $message = array("positive" => $signed_parts[0],
2352 "guid" => $signed_parts[1],
2353 "target_type" => $signed_parts[2],
2354 "parent_guid" => $signed_parts[3],
2355 "parent_author_signature" => "",
2356 "author_signature" => $signature['signature'],
2357 "diaspora_handle" => $signed_parts[4]);
2359 // Remove the comment guid
2360 $guid = array_shift($signed_parts);
2362 // Remove the parent guid
2363 $parent_guid = array_shift($signed_parts);
2365 // Remove the handle
2366 $handle = array_pop($signed_parts);
2368 // Glue the parts together
2369 $text = implode(";", $signed_parts);
2371 $message = array("guid" => $guid,
2372 "parent_guid" => $parent_guid,
2373 "parent_author_signature" => "",
2374 "author_signature" => $signature['signature'],
2375 "text" => implode(";", $signed_parts),
2376 "diaspora_handle" => $handle);
2381 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2383 if ($item["deleted"]) {
2384 $sql_sign_id = "retract_iid";
2385 $type = "relayable_retraction";
2386 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2387 $sql_sign_id = "iid";
2390 $sql_sign_id = "iid";
2394 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2396 // fetch the original signature
2398 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2399 intval($item["id"]));
2402 if ($item["deleted"])
2403 return self::send_retraction($item, $owner, $contact, $public_batch);
2405 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2411 // Old way - is used by the internal Friendica functions
2412 /// @todo Change all signatur storing functions to the new format
2413 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2414 $message = self::message_from_signatur($item, $signature);
2416 $msg = json_decode($signature['signed_text'], true);
2419 if (is_array($msg)) {
2420 foreach ($msg AS $field => $data) {
2421 if (!$item["deleted"]) {
2422 if ($field == "author")
2423 $field = "diaspora_handle";
2424 if ($field == "parent_type")
2425 $field = "target_type";
2428 $message[$field] = $data;
2431 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2434 if ($item["deleted"]) {
2435 $signed_text = $message["target_guid"].';'.$message["target_type"];
2436 $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2438 $message["parent_author_signature"] = self::signature($owner, $message);
2440 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2442 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2445 public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2447 /// @todo Fetch handle from every contact (via gcontact)
2448 $itemaddr = self::handle_from_contact($item["contact-id"]);
2450 $myaddr = self::my_handle($owner);
2452 // Check whether the retraction is for a top-level post or whether it's a relayable
2453 if ($item["uri"] !== $item["parent-uri"]) {
2454 $msg_type = "relayable_retraction";
2455 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2457 $msg_type = "signed_retraction";
2458 $target_type = "StatusMessage";
2461 $signed_text = $item["guid"].";".$target_type;
2463 $message = array("target_guid" => $item['guid'],
2464 "target_type" => $target_type,
2465 "sender_handle" => $itemaddr,
2466 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2468 if ($itemaddr != $myaddr) {
2469 $message["parent_author_signature"] = $message["target_author_signature"];
2470 unset($message["target_author_signature"]);
2473 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2475 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2478 public static function send_mail($item, $owner, $contact) {
2480 $myaddr = self::my_handle($owner);
2482 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2483 intval($item["convid"]),
2484 intval($item["uid"])
2488 logger("conversation not found.");
2494 "guid" => $cnv["guid"],
2495 "subject" => $cnv["subject"],
2496 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2497 "diaspora_handle" => $cnv["creator"],
2498 "participant_handles" => $cnv["recips"]
2501 $body = bb2diaspora($item["body"]);
2502 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2504 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2505 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2508 "guid" => $item["guid"],
2509 "parent_guid" => $cnv["guid"],
2510 "parent_author_signature" => $sig,
2511 "author_signature" => $sig,
2513 "created_at" => $created,
2514 "diaspora_handle" => $myaddr,
2515 "conversation_guid" => $cnv["guid"]
2518 if ($item["reply"]) {
2522 $message = array("guid" => $cnv["guid"],
2523 "subject" => $cnv["subject"],
2524 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2526 "diaspora_handle" => $cnv["creator"],
2527 "participant_handles" => $cnv["recips"]);
2529 $type = "conversation";
2532 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2535 public static function send_profile($uid) {
2540 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2541 AND `uid` = %d AND `rel` != %d",
2542 dbesc(NETWORK_DIASPORA),
2544 intval(CONTACT_IS_SHARING)
2549 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2551 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2552 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2553 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
2562 $handle = $profile["addr"];
2563 $first = ((strpos($profile['name'],' ')
2564 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
2565 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
2566 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
2567 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
2568 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
2569 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
2571 if ($searchable === 'true') {
2572 $dob = '1000-00-00';
2574 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
2575 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
2577 $about = $profile['about'];
2578 $about = strip_tags(bbcode($about));
2580 $location = formatted_location($profile);
2582 if ($profile['pub_keywords']) {
2583 $kw = str_replace(',',' ',$profile['pub_keywords']);
2584 $kw = str_replace(' ',' ',$kw);
2585 $arr = explode(' ',$profile['pub_keywords']);
2587 for($x = 0; $x < 5; $x ++) {
2589 $tags .= '#'. trim($arr[$x]) .' ';
2593 $tags = trim($tags);
2596 $message = array("diaspora_handle" => $handle,
2597 "first_name" => $first,
2598 "last_name" => $last,
2599 "image_url" => $large,
2600 "image_url_medium" => $medium,
2601 "image_url_small" => $small,
2603 "gender" => $profile['gender'],
2605 "location" => $location,
2606 "searchable" => $searchable,
2607 "tag_string" => $tags);
2609 foreach($recips as $recip)
2610 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);