3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
7 require_once("include/items.php");
8 require_once("include/bb2diaspora.php");
9 require_once("include/Scrape.php");
10 require_once("include/Contact.php");
11 require_once("include/Photo.php");
12 require_once("include/socgraph.php");
13 require_once("include/group.php");
14 require_once("include/xml.php");
15 require_once("include/datetime.php");
18 * @brief This class contain functions to create and send Diaspora XML files
23 public static function relay_list() {
25 $serverdata = get_config("system", "relay_server");
26 if ($serverdata == "")
31 $servers = explode(",", $serverdata);
33 foreach($servers AS $server) {
34 $server = trim($server);
35 $batch = $server."/receive/public";
37 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
40 $addr = "relay@".str_replace("http://", "", normalise_link($server));
42 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
43 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
48 dbesc(normalise_link($server)),
50 dbesc(NETWORK_DIASPORA),
51 intval(CONTACT_IS_FOLLOWER),
52 dbesc(datetime_convert()),
53 dbesc(datetime_convert()),
54 dbesc(datetime_convert())
57 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
59 $relay[] = $relais[0];
61 $relay[] = $relais[0];
67 function repair_signature($signature, $handle = "", $level = 1) {
72 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
73 $signature = base64_decode($signature);
74 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
76 // Do a recursive call to be able to fix even multiple levels
78 $signature = self::repair_signature($signature, $handle, ++$level);
85 * @brief: Decodes incoming Diaspora message
87 * @param array $importer from user table
88 * @param string $xml urldecoded Diaspora salmon
91 * 'message' -> decoded Diaspora XML message
92 * 'author' -> author diaspora handle
93 * 'key' -> author public key (converted to pkcs#8)
95 function decode($importer, $xml) {
98 $basedom = parse_xml_string($xml);
100 if (!is_object($basedom))
103 $children = $basedom->children('https://joindiaspora.com/protocol');
105 if($children->header) {
107 $author_link = str_replace('acct:','',$children->header->author_id);
110 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
112 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
113 $ciphertext = base64_decode($encrypted_header->ciphertext);
115 $outer_key_bundle = '';
116 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
118 $j_outer_key_bundle = json_decode($outer_key_bundle);
120 $outer_iv = base64_decode($j_outer_key_bundle->iv);
121 $outer_key = base64_decode($j_outer_key_bundle->key);
123 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
126 $decrypted = pkcs5_unpad($decrypted);
129 * $decrypted now contains something like
132 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
133 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
134 * <author_id>galaxor@diaspora.priateship.org</author_id>
135 * </decrypted_header>
138 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
139 $idom = parse_xml_string($decrypted,false);
141 $inner_iv = base64_decode($idom->iv);
142 $inner_aes_key = base64_decode($idom->aes_key);
144 $author_link = str_replace('acct:','',$idom->author_id);
147 $dom = $basedom->children(NAMESPACE_SALMON_ME);
149 // figure out where in the DOM tree our data is hiding
151 if($dom->provenance->data)
152 $base = $dom->provenance;
153 elseif($dom->env->data)
159 logger('unable to locate salmon data in xml');
160 http_status_exit(400);
164 // Stash the signature away for now. We have to find their key or it won't be good for anything.
165 $signature = base64url_decode($base->sig);
169 // strip whitespace so our data element will return to one big base64 blob
170 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
173 // stash away some other stuff for later
175 $type = $base->data[0]->attributes()->type[0];
176 $keyhash = $base->sig[0]->attributes()->keyhash[0];
177 $encoding = $base->encoding;
181 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
185 $data = base64url_decode($data);
189 $inner_decrypted = $data;
192 // Decode the encrypted blob
194 $inner_encrypted = base64_decode($data);
195 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
196 $inner_decrypted = pkcs5_unpad($inner_decrypted);
200 logger('Could not retrieve author URI.');
201 http_status_exit(400);
203 // Once we have the author URI, go to the web and try to find their public key
204 // (first this will look it up locally if it is in the fcontact cache)
205 // This will also convert diaspora public key from pkcs#1 to pkcs#8
207 logger('Fetching key for '.$author_link);
208 $key = self::key($author_link);
211 logger('Could not retrieve author key.');
212 http_status_exit(400);
215 $verify = rsa_verify($signed_data,$signature,$key);
218 logger('Message did not verify. Discarding.');
219 http_status_exit(400);
222 logger('Message verified.');
224 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
230 * @brief Dispatches public messages and find the fitting receivers
232 * @param array $msg The post that will be dispatched
234 * @return bool Was the message accepted?
236 public static function dispatch_public($msg) {
238 $enabled = intval(get_config("system", "diaspora_enabled"));
240 logger("diaspora is disabled");
244 // Use a dummy importer to import the data for the public copy
245 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
246 $item_id = self::dispatch($importer,$msg);
248 // Now distribute it to the followers
249 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
250 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
251 AND NOT `account_expired` AND NOT `account_removed`",
252 dbesc(NETWORK_DIASPORA),
253 dbesc($msg["author"])
257 logger("delivering to: ".$rr["username"]);
258 self::dispatch($rr,$msg);
261 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
267 * @brief Dispatches the different message types to the different functions
269 * @param array $importer Array of the importer user
270 * @param array $msg The post that will be dispatched
272 * @return bool Was the message accepted?
274 public static function dispatch($importer, $msg) {
276 // The sender is the handle of the contact that sent the message.
277 // This will often be different with relayed messages (for example "like" and "comment")
278 $sender = $msg["author"];
280 if (!diaspora::valid_posting($msg, $fields)) {
281 logger("Invalid posting");
285 $type = $fields->getName();
287 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
290 case "account_deletion":
291 return self::receive_account_deletion($importer, $fields);
294 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
297 return self::receive_conversation($importer, $msg, $fields);
300 return self::receive_like($importer, $sender, $fields);
303 return self::receive_message($importer, $fields);
305 case "participation": // Not implemented
306 return self::receive_participation($importer, $fields);
308 case "photo": // Not implemented
309 return self::receive_photo($importer, $fields);
311 case "poll_participation": // Not implemented
312 return self::receive_poll_participation($importer, $fields);
315 return self::receive_profile($importer, $fields);
318 return self::receive_request($importer, $fields);
321 return self::receive_reshare($importer, $fields, $msg["message"]);
324 return self::receive_retraction($importer, $sender, $fields);
326 case "status_message":
327 return self::receive_status_message($importer, $fields, $msg["message"]);
330 logger("Unknown message type ".$type);
338 * @brief Checks if a posting is valid and fetches the data fields.
340 * This function does not only check the signature.
341 * It also does the conversion between the old and the new diaspora format.
343 * @param array $msg Array with the XML, the sender handle and the sender signature
344 * @param object $fields SimpleXML object that contains the posting when it is valid
346 * @return bool Is the posting valid?
348 private function valid_posting($msg, &$fields) {
350 $data = parse_xml_string($msg["message"], false);
352 if (!is_object($data))
355 $first_child = $data->getName();
357 // Is this the new or the old version?
358 if ($data->getName() == "XML") {
360 foreach ($data->post->children() as $child)
367 $type = $element->getName();
370 // All retractions are handled identically from now on.
371 // In the new version there will only be "retraction".
372 if (in_array($type, array("signed_retraction", "relayable_retraction")))
373 $type = "retraction";
375 $fields = new SimpleXMLElement("<".$type."/>");
379 foreach ($element->children() AS $fieldname => $entry) {
381 // Translation for the old XML structure
382 if ($fieldname == "diaspora_handle")
383 $fieldname = "author";
385 if ($fieldname == "participant_handles")
386 $fieldname = "participants";
388 if (in_array($type, array("like", "participation"))) {
389 if ($fieldname == "target_type")
390 $fieldname = "parent_type";
393 if ($fieldname == "sender_handle")
394 $fieldname = "author";
396 if ($fieldname == "recipient_handle")
397 $fieldname = "recipient";
399 if ($fieldname == "root_diaspora_id")
400 $fieldname = "root_author";
402 if ($type == "retraction") {
403 if ($fieldname == "post_guid")
404 $fieldname = "target_guid";
406 if ($fieldname == "type")
407 $fieldname = "target_type";
411 if ($fieldname == "author_signature")
412 $author_signature = base64_decode($entry);
413 elseif ($fieldname == "parent_author_signature")
414 $parent_author_signature = base64_decode($entry);
415 elseif ($fieldname != "target_author_signature") {
416 if ($signed_data != "") {
418 $signed_data_parent .= ";";
421 $signed_data .= $entry;
423 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
424 ($orig_type == "relayable_retraction"))
425 xml::copy($entry, $fields, $fieldname);
428 // This is something that shouldn't happen at all.
429 if (in_array($type, array("status_message", "reshare", "profile")))
430 if ($msg["author"] != $fields->author) {
431 logger("Message handle is not the same as envelope sender. Quitting this message.");
435 // Only some message types have signatures. So we quit here for the other types.
436 if (!in_array($type, array("comment", "message", "like")))
439 // No author_signature? This is a must, so we quit.
440 if (!isset($author_signature))
443 if (isset($parent_author_signature)) {
444 $key = self::key($msg["author"]);
446 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
450 $key = self::key($fields->author);
452 return rsa_verify($signed_data, $author_signature, $key, "sha256");
456 * @brief Fetches the public key for a given handle
458 * @param string $handle The handle
460 * @return string The public key
462 private function key($handle) {
463 $handle = strval($handle);
465 logger("Fetching diaspora key for: ".$handle);
467 $r = self::person_by_handle($handle);
475 * @brief Fetches data for a given handle
477 * @param string $handle The handle
479 * @return array the queried data
481 private function person_by_handle($handle) {
483 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
484 dbesc(NETWORK_DIASPORA),
489 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
491 // update record occasionally so it doesn't get stale
492 $d = strtotime($person["updated"]." +00:00");
493 if ($d < strtotime("now - 14 days"))
497 if (!$person OR $update) {
498 logger("create or refresh", LOGGER_DEBUG);
499 $r = probe_url($handle, PROBE_DIASPORA);
501 // Note that Friendica contacts will return a "Diaspora person"
502 // if Diaspora connectivity is enabled on their server
503 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
504 self::add_fcontact($r, $update);
512 * @brief Updates the fcontact table
514 * @param array $arr The fcontact data
515 * @param bool $update Update or insert?
517 * @return string The id of the fcontact entry
519 private function add_fcontact($arr, $update = false) {
522 $r = q("UPDATE `fcontact` SET
535 WHERE `url` = '%s' AND `network` = '%s'",
537 dbesc($arr["photo"]),
538 dbesc($arr["request"]),
541 dbesc($arr["batch"]),
542 dbesc($arr["notify"]),
544 dbesc($arr["confirm"]),
545 dbesc($arr["alias"]),
546 dbesc($arr["pubkey"]),
547 dbesc(datetime_convert()),
549 dbesc($arr["network"])
552 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
553 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
554 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
557 dbesc($arr["photo"]),
558 dbesc($arr["request"]),
561 dbesc($arr["batch"]),
562 dbesc($arr["notify"]),
564 dbesc($arr["confirm"]),
565 dbesc($arr["network"]),
566 dbesc($arr["alias"]),
567 dbesc($arr["pubkey"]),
568 dbesc(datetime_convert())
575 public static function handle_from_contact($contact_id) {
578 logger("contact id is ".$contact_id, LOGGER_DEBUG);
580 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
586 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
588 if($contact['addr'] != "")
589 $handle = $contact['addr'];
590 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
591 $baseurl_start = strpos($contact['url'],'://') + 3;
592 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
593 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
594 $handle = $contact['nick'].'@'.$baseurl;
601 private function contact_by_handle($uid, $handle) {
602 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
610 $handle_parts = explode("@", $handle);
611 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
612 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
623 private function post_allow($importer, $contact, $is_comment = false) {
625 // perhaps we were already sharing with this person. Now they're sharing with us.
626 // That makes us friends.
627 // Normally this should have handled by getting a request - but this could get lost
628 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
629 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
630 intval(CONTACT_IS_FRIEND),
631 intval($contact["id"]),
632 intval($importer["uid"])
634 $contact["rel"] = CONTACT_IS_FRIEND;
635 logger("defining user ".$contact["nick"]." as friend");
638 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
640 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
642 if($contact["rel"] == CONTACT_IS_FOLLOWER)
643 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
646 // Messages for the global users are always accepted
647 if ($importer["uid"] == 0)
653 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
654 $contact = self::contact_by_handle($importer["uid"], $handle);
656 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
660 if (!self::post_allow($importer, $contact, $is_comment)) {
661 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
667 private function message_exists($uid, $guid) {
668 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
674 logger("message ".$guid." already exists for user ".$uid);
681 private function fetch_guid($item) {
682 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
683 function ($match) use ($item){
684 return(self::fetch_guid_sub($match, $item));
688 private function fetch_guid_sub($match, $item) {
689 if (!self::store_by_guid($match[1], $item["author-link"]))
690 self::store_by_guid($match[1], $item["owner-link"]);
693 private function store_by_guid($guid, $server, $uid = 0) {
694 $serverparts = parse_url($server);
695 $server = $serverparts["scheme"]."://".$serverparts["host"];
697 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
699 $msg = self::message($guid, $server);
704 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
706 // Now call the dispatcher
707 return self::dispatch_public($msg);
710 private function message($guid, $server, $level = 0) {
715 // This will work for Diaspora and newer Friendica servers
716 $source_url = $server."/p/".$guid.".xml";
717 $x = fetch_url($source_url);
721 $source_xml = parse_xml_string($x, false);
723 if (!is_object($source_xml))
726 if ($source_xml->post->reshare) {
727 // Reshare of a reshare - old Diaspora version
728 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
729 } elseif ($source_xml->getName() == "reshare") {
730 // Reshare of a reshare - new Diaspora version
731 return self::message($source_xml->root_guid, $server, ++$level);
736 // Fetch the author - for the old and the new Diaspora version
737 if ($source_xml->post->status_message->diaspora_handle)
738 $author = (string)$source_xml->post->status_message->diaspora_handle;
739 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
740 $author = (string)$source_xml->author;
742 // If this isn't a "status_message" then quit
746 $msg = array("message" => $x, "author" => $author);
748 $msg["key"] = self::key($msg["author"]);
753 private function parent_item($uid, $guid, $author, $contact) {
754 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
755 `author-name`, `author-link`, `author-avatar`,
756 `owner-name`, `owner-link`, `owner-avatar`
757 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
758 intval($uid), dbesc($guid));
761 $result = self::store_by_guid($guid, $contact["url"], $uid);
764 $person = self::person_by_handle($author);
765 $result = self::store_by_guid($guid, $person["url"], $uid);
769 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
771 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
772 `author-name`, `author-link`, `author-avatar`,
773 `owner-name`, `owner-link`, `owner-avatar`
774 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
775 intval($uid), dbesc($guid));
780 logger("parent item not found: parent: ".$guid." - user: ".$uid);
783 logger("parent item found: parent: ".$guid." - user: ".$uid);
788 private function author_contact_by_url($contact, $person, $uid) {
790 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
791 dbesc(normalise_link($person["url"])), intval($uid));
794 $network = $r[0]["network"];
796 $cid = $contact["id"];
797 $network = NETWORK_DIASPORA;
800 return (array("cid" => $cid, "network" => $network));
803 public static function is_redmatrix($url) {
804 return(strstr($url, "/channel/"));
807 private function plink($addr, $guid) {
808 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
812 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
814 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
815 // So we try another way as well.
816 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
818 $r[0]["network"] = $s[0]["network"];
820 if ($r[0]["network"] == NETWORK_DFRN)
821 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
823 if (self::is_redmatrix($r[0]["url"]))
824 return $r[0]["url"]."/?f=&mid=".$guid;
826 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
829 private function receive_account_deletion($importer, $data) {
830 $author = notags(unxmlify($data->author));
832 $contact = self::contact_by_handle($importer["uid"], $author);
834 logger("cannot find contact for author: ".$author);
838 // We now remove the contact
839 contact_remove($contact["id"]);
843 private function receive_comment($importer, $sender, $data, $xml) {
844 $guid = notags(unxmlify($data->guid));
845 $parent_guid = notags(unxmlify($data->parent_guid));
846 $text = unxmlify($data->text);
847 $author = notags(unxmlify($data->author));
849 $contact = self::allowed_contact_by_handle($importer, $sender, true);
853 if (self::message_exists($importer["uid"], $guid))
856 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
860 $person = self::person_by_handle($author);
861 if (!is_array($person)) {
862 logger("unable to find author details");
866 // Fetch the contact id - if we know this contact
867 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
871 $datarray["uid"] = $importer["uid"];
872 $datarray["contact-id"] = $author_contact["cid"];
873 $datarray["network"] = $author_contact["network"];
875 $datarray["author-name"] = $person["name"];
876 $datarray["author-link"] = $person["url"];
877 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
879 $datarray["owner-name"] = $contact["name"];
880 $datarray["owner-link"] = $contact["url"];
881 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
883 $datarray["guid"] = $guid;
884 $datarray["uri"] = $author.":".$guid;
886 $datarray["type"] = "remote-comment";
887 $datarray["verb"] = ACTIVITY_POST;
888 $datarray["gravity"] = GRAVITY_COMMENT;
889 $datarray["parent-uri"] = $parent_item["uri"];
891 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
892 $datarray["object"] = $xml;
894 $datarray["body"] = diaspora2bb($text);
896 self::fetch_guid($datarray);
898 $message_id = item_store($datarray);
901 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
903 // If we are the origin of the parent we store the original data and notify our followers
904 if($message_id AND $parent_item["origin"]) {
906 // Formerly we stored the signed text, the signature and the author in different fields.
907 // We now store the raw data so that we are more flexible.
908 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
910 dbesc(json_encode($data))
914 proc_run("php", "include/notifier.php", "comment-import", $message_id);
920 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
921 $guid = notags(unxmlify($data->guid));
922 $subject = notags(unxmlify($data->subject));
923 $author = notags(unxmlify($data->author));
927 $msg_guid = notags(unxmlify($mesg->guid));
928 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
929 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
930 $msg_author_signature = notags(unxmlify($mesg->author_signature));
931 $msg_text = unxmlify($mesg->text);
932 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
934 // "diaspora_handle" is the element name from the old version
935 // "author" is the element name from the new version
937 $msg_author = notags(unxmlify($mesg->author));
938 elseif ($mesg->diaspora_handle)
939 $msg_author = notags(unxmlify($mesg->diaspora_handle));
943 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
945 if($msg_conversation_guid != $guid) {
946 logger("message conversation guid does not belong to the current conversation.");
950 $body = diaspora2bb($msg_text);
951 $message_uri = $msg_author.":".$msg_guid;
953 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
955 $author_signature = base64_decode($msg_author_signature);
957 if(strcasecmp($msg_author,$msg["author"]) == 0) {
961 $person = self::person_by_handle($msg_author);
963 if (is_array($person) && x($person, "pubkey"))
964 $key = $person["pubkey"];
966 logger("unable to find author details");
971 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
972 logger("verification failed.");
976 if($msg_parent_author_signature) {
977 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
979 $parent_author_signature = base64_decode($msg_parent_author_signature);
983 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
984 logger("owner verification failed.");
989 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
993 logger("duplicate message already delivered.", LOGGER_DEBUG);
997 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
998 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
999 intval($importer["uid"]),
1001 intval($conversation["id"]),
1002 dbesc($person["name"]),
1003 dbesc($person["photo"]),
1004 dbesc($person["url"]),
1005 intval($contact["id"]),
1010 dbesc($message_uri),
1011 dbesc($author.":".$guid),
1012 dbesc($msg_created_at)
1015 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1016 dbesc(datetime_convert()),
1017 intval($conversation["id"])
1021 "type" => NOTIFY_MAIL,
1022 "notify_flags" => $importer["notify-flags"],
1023 "language" => $importer["language"],
1024 "to_name" => $importer["username"],
1025 "to_email" => $importer["email"],
1026 "uid" =>$importer["uid"],
1027 "item" => array("subject" => $subject, "body" => $body),
1028 "source_name" => $person["name"],
1029 "source_link" => $person["url"],
1030 "source_photo" => $person["thumb"],
1031 "verb" => ACTIVITY_POST,
1036 private function receive_conversation($importer, $msg, $data) {
1037 $guid = notags(unxmlify($data->guid));
1038 $subject = notags(unxmlify($data->subject));
1039 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1040 $author = notags(unxmlify($data->author));
1041 $participants = notags(unxmlify($data->participants));
1043 $messages = $data->message;
1045 if (!count($messages)) {
1046 logger("empty conversation");
1050 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1054 $conversation = null;
1056 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1057 intval($importer["uid"]),
1061 $conversation = $c[0];
1063 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1064 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1065 intval($importer["uid"]),
1068 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1069 dbesc(datetime_convert()),
1071 dbesc($participants)
1074 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1075 intval($importer["uid"]),
1080 $conversation = $c[0];
1082 if (!$conversation) {
1083 logger("unable to create conversation.");
1087 foreach($messages as $mesg)
1088 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1093 private function construct_like_body($contact, $parent_item, $guid) {
1094 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1096 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1097 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1098 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1100 return sprintf($bodyverb, $ulink, $alink, $plink);
1103 private function construct_like_object($importer, $parent_item) {
1104 $objtype = ACTIVITY_OBJ_NOTE;
1105 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1106 $parent_body = $parent_item["body"];
1108 $xmldata = array("object" => array("type" => $objtype,
1110 "id" => $parent_item["uri"],
1113 "content" => $parent_body));
1115 return xml::from_array($xmldata, $xml, true);
1118 private function receive_like($importer, $sender, $data) {
1119 $positive = notags(unxmlify($data->positive));
1120 $guid = notags(unxmlify($data->guid));
1121 $parent_type = notags(unxmlify($data->parent_type));
1122 $parent_guid = notags(unxmlify($data->parent_guid));
1123 $author = notags(unxmlify($data->author));
1125 // likes on comments aren't supported by Diaspora - only on posts
1126 // But maybe this will be supported in the future, so we will accept it.
1127 if (!in_array($parent_type, array("Post", "Comment")))
1130 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1134 if (self::message_exists($importer["uid"], $guid))
1137 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1141 $person = self::person_by_handle($author);
1142 if (!is_array($person)) {
1143 logger("unable to find author details");
1147 // Fetch the contact id - if we know this contact
1148 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1150 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1151 // We would accept this anyhow.
1152 if ($positive === "true")
1153 $verb = ACTIVITY_LIKE;
1155 $verb = ACTIVITY_DISLIKE;
1157 $datarray = array();
1159 $datarray["uid"] = $importer["uid"];
1160 $datarray["contact-id"] = $author_contact["cid"];
1161 $datarray["network"] = $author_contact["network"];
1163 $datarray["author-name"] = $person["name"];
1164 $datarray["author-link"] = $person["url"];
1165 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1167 $datarray["owner-name"] = $contact["name"];
1168 $datarray["owner-link"] = $contact["url"];
1169 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1171 $datarray["guid"] = $guid;
1172 $datarray["uri"] = $author.":".$guid;
1174 $datarray["type"] = "activity";
1175 $datarray["verb"] = $verb;
1176 $datarray["gravity"] = GRAVITY_LIKE;
1177 $datarray["parent-uri"] = $parent_item["uri"];
1179 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1180 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1182 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1184 $message_id = item_store($datarray);
1187 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1189 // If we are the origin of the parent we store the original data and notify our followers
1190 if($message_id AND $parent_item["origin"]) {
1192 // Formerly we stored the signed text, the signature and the author in different fields.
1193 // We now store the raw data so that we are more flexible.
1194 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1195 intval($message_id),
1196 dbesc(json_encode($data))
1200 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1206 private function receive_message($importer, $data) {
1207 $guid = notags(unxmlify($data->guid));
1208 $parent_guid = notags(unxmlify($data->parent_guid));
1209 $text = unxmlify($data->text);
1210 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1211 $author = notags(unxmlify($data->author));
1212 $conversation_guid = notags(unxmlify($data->conversation_guid));
1214 $contact = self::allowed_contact_by_handle($importer, $author, true);
1218 $conversation = null;
1220 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1221 intval($importer["uid"]),
1222 dbesc($conversation_guid)
1225 $conversation = $c[0];
1227 logger("conversation not available.");
1233 $body = diaspora2bb($text);
1234 $message_uri = $author.":".$guid;
1236 $person = self::person_by_handle($author);
1238 logger("unable to find author details");
1242 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1243 dbesc($message_uri),
1244 intval($importer["uid"])
1247 logger("duplicate message already delivered.", LOGGER_DEBUG);
1251 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1252 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1253 intval($importer["uid"]),
1255 intval($conversation["id"]),
1256 dbesc($person["name"]),
1257 dbesc($person["photo"]),
1258 dbesc($person["url"]),
1259 intval($contact["id"]),
1260 dbesc($conversation["subject"]),
1264 dbesc($message_uri),
1265 dbesc($author.":".$parent_guid),
1269 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1270 dbesc(datetime_convert()),
1271 intval($conversation["id"])
1277 private function receive_participation($importer, $data) {
1278 // I'm not sure if we can fully support this message type
1282 private function receive_photo($importer, $data) {
1283 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1287 private function receive_poll_participation($importer, $data) {
1288 // We don't support polls by now
1292 private function receive_profile($importer, $data) {
1293 $author = notags(unxmlify($data->author));
1295 $contact = self::contact_by_handle($importer["uid"], $author);
1299 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1300 $image_url = unxmlify($data->image_url);
1301 $birthday = unxmlify($data->birthday);
1302 $location = diaspora2bb(unxmlify($data->location));
1303 $about = diaspora2bb(unxmlify($data->bio));
1304 $gender = unxmlify($data->gender);
1305 $searchable = (unxmlify($data->searchable) == "true");
1306 $nsfw = (unxmlify($data->nsfw) == "true");
1307 $tags = unxmlify($data->tag_string);
1309 $tags = explode("#", $tags);
1311 $keywords = array();
1312 foreach ($tags as $tag) {
1313 $tag = trim(strtolower($tag));
1318 $keywords = implode(", ", $keywords);
1320 $handle_parts = explode("@", $author);
1321 $nick = $handle_parts[0];
1324 $name = $handle_parts[0];
1326 if( preg_match("|^https?://|", $image_url) === 0)
1327 $image_url = "http://".$handle_parts[1].$image_url;
1329 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1331 // Generic birthday. We don't know the timezone. The year is irrelevant.
1333 $birthday = str_replace("1000", "1901", $birthday);
1335 if ($birthday != "")
1336 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1338 // this is to prevent multiple birthday notifications in a single year
1339 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1341 if(substr($birthday,5) === substr($contact["bd"],5))
1342 $birthday = $contact["bd"];
1344 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1345 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1349 dbesc(datetime_convert()),
1355 intval($contact["id"]),
1356 intval($importer["uid"])
1360 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1361 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1364 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1365 "photo" => $image_url, "name" => $name, "location" => $location,
1366 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1367 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1368 "hide" => !$searchable, "nsfw" => $nsfw);
1370 update_gcontact($gcontact);
1372 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1377 private function receive_request_make_friend($importer, $contact) {
1381 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1382 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1383 intval(CONTACT_IS_FRIEND),
1384 intval($contact["id"]),
1385 intval($importer["uid"])
1388 // send notification
1390 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1391 intval($importer["uid"])
1394 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1396 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1397 intval($importer["uid"])
1400 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1402 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1405 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1406 $arr["uid"] = $importer["uid"];
1407 $arr["contact-id"] = $self[0]["id"];
1409 $arr["type"] = 'wall';
1410 $arr["gravity"] = 0;
1412 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1413 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1414 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1415 $arr["verb"] = ACTIVITY_FRIEND;
1416 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1418 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1419 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1420 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1421 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1423 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1424 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1425 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1426 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1427 $arr["object"] .= "</link></object>\n";
1428 $arr["last-child"] = 1;
1430 $arr["allow_cid"] = $user[0]["allow_cid"];
1431 $arr["allow_gid"] = $user[0]["allow_gid"];
1432 $arr["deny_cid"] = $user[0]["deny_cid"];
1433 $arr["deny_gid"] = $user[0]["deny_gid"];
1435 $i = item_store($arr);
1437 proc_run("php", "include/notifier.php", "activity", $i);
1444 private function receive_request($importer, $data) {
1445 $author = unxmlify($data->author);
1446 $recipient = unxmlify($data->recipient);
1448 if (!$author || !$recipient)
1451 $contact = self::contact_by_handle($importer["uid"],$author);
1455 // perhaps we were already sharing with this person. Now they're sharing with us.
1456 // That makes us friends.
1458 self::receive_request_make_friend($importer, $contact);
1462 $ret = self::person_by_handle($author);
1464 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1465 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1469 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1471 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1472 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1473 intval($importer["uid"]),
1474 dbesc($ret["network"]),
1475 dbesc($ret["addr"]),
1478 dbesc(normalise_link($ret["url"])),
1480 dbesc($ret["name"]),
1481 dbesc($ret["nick"]),
1482 dbesc($ret["photo"]),
1483 dbesc($ret["pubkey"]),
1484 dbesc($ret["notify"]),
1485 dbesc($ret["poll"]),
1490 // find the contact record we just created
1492 $contact_record = self::contact_by_handle($importer["uid"],$author);
1494 if (!$contact_record) {
1495 logger("unable to locate newly created contact record.");
1499 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1500 intval($importer["uid"])
1503 if($g && intval($g[0]["def_gid"]))
1504 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1506 if($importer["page-flags"] == PAGE_NORMAL) {
1508 $hash = random_string().(string)time(); // Generate a confirm_key
1510 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1511 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1512 intval($importer["uid"]),
1513 intval($contact_record["id"]),
1516 dbesc(t("Sharing notification from Diaspora network")),
1518 dbesc(datetime_convert())
1522 // automatic friend approval
1524 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1526 // technically they are sharing with us (CONTACT_IS_SHARING),
1527 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1528 // we are going to change the relationship and make them a follower.
1530 if($importer["page-flags"] == PAGE_FREELOVE)
1531 $new_relation = CONTACT_IS_FRIEND;
1533 $new_relation = CONTACT_IS_FOLLOWER;
1535 $r = q("UPDATE `contact` SET `rel` = %d,
1543 intval($new_relation),
1544 dbesc(datetime_convert()),
1545 dbesc(datetime_convert()),
1546 intval($contact_record["id"])
1549 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1551 $ret = self::send_share($u[0], $contact_record);
1557 private function original_item($guid, $orig_author, $author) {
1559 // Do we already have this item?
1560 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1561 `author-name`, `author-link`, `author-avatar`
1562 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1566 logger("reshared message ".$guid." already exists on system.");
1568 // Maybe it is already a reshared item?
1569 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1570 if (self::is_reshare($r[0]["body"]))
1577 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1578 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1579 $item_id = self::store_by_guid($guid, $server);
1582 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1583 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1584 $item_id = self::store_by_guid($guid, $server);
1587 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1589 $server = "https://".substr($author, strpos($author, "@") + 1);
1590 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1591 $item_id = self::store_by_guid($guid, $server);
1594 $server = "http://".substr($author, strpos($author, "@") + 1);
1595 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1596 $item_id = self::store_by_guid($guid, $server);
1600 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1601 `author-name`, `author-link`, `author-avatar`
1602 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1613 private function receive_reshare($importer, $data, $xml) {
1614 $root_author = notags(unxmlify($data->root_author));
1615 $root_guid = notags(unxmlify($data->root_guid));
1616 $guid = notags(unxmlify($data->guid));
1617 $author = notags(unxmlify($data->author));
1618 $public = notags(unxmlify($data->public));
1619 $created_at = notags(unxmlify($data->created_at));
1621 $contact = self::allowed_contact_by_handle($importer, $author, false);
1625 if (self::message_exists($importer["uid"], $guid))
1628 $original_item = self::original_item($root_guid, $root_author, $author);
1629 if (!$original_item)
1632 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1634 $datarray = array();
1636 $datarray["uid"] = $importer["uid"];
1637 $datarray["contact-id"] = $contact["id"];
1638 $datarray["network"] = NETWORK_DIASPORA;
1640 $datarray["author-name"] = $contact["name"];
1641 $datarray["author-link"] = $contact["url"];
1642 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1644 $datarray["owner-name"] = $datarray["author-name"];
1645 $datarray["owner-link"] = $datarray["author-link"];
1646 $datarray["owner-avatar"] = $datarray["author-avatar"];
1648 $datarray["guid"] = $guid;
1649 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1651 $datarray["verb"] = ACTIVITY_POST;
1652 $datarray["gravity"] = GRAVITY_PARENT;
1654 $datarray["object"] = $xml;
1656 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1657 $original_item["guid"], $original_item["created"], $orig_url);
1658 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1660 $datarray["tag"] = $original_item["tag"];
1661 $datarray["app"] = $original_item["app"];
1663 $datarray["plink"] = self::plink($author, $guid);
1664 $datarray["private"] = (($public == "false") ? 1 : 0);
1665 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1667 $datarray["object-type"] = $original_item["object-type"];
1669 self::fetch_guid($datarray);
1670 $message_id = item_store($datarray);
1673 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1678 private function item_retraction($importer, $contact, $data) {
1679 $target_type = notags(unxmlify($data->target_type));
1680 $target_guid = notags(unxmlify($data->target_guid));
1681 $author = notags(unxmlify($data->author));
1683 $person = self::person_by_handle($author);
1684 if (!is_array($person)) {
1685 logger("unable to find author detail for ".$author);
1689 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1690 dbesc($target_guid),
1691 intval($importer["uid"])
1696 // Only delete it if the author really fits
1697 if (!link_compare($r[0]["author-link"], $person["url"])) {
1698 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
1702 // Check if the sender is the thread owner
1703 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
1704 intval($r[0]["parent"]));
1706 // Only delete it if the parent author really fits
1707 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
1708 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
1712 // 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
1713 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1714 dbesc(datetime_convert()),
1715 dbesc(datetime_convert()),
1718 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1720 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
1722 // Now check if the retraction needs to be relayed by us
1723 if($p[0]["origin"]) {
1725 // Formerly we stored the signed text, the signature and the author in different fields.
1726 // We now store the raw data so that we are more flexible.
1727 q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1728 intval($r[0]["id"]),
1729 dbesc(json_encode($data))
1731 $s = q("select * from sign where retract_iid = %d", intval($r[0]["id"]));
1732 logger("Stored signatur for item ".$r[0]["id"]." - ".print_r($s, true), LOGGER_DEBUG);
1735 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1739 private function receive_retraction($importer, $sender, $data) {
1740 $target_type = notags(unxmlify($data->target_type));
1742 $contact = self::contact_by_handle($importer["uid"], $sender);
1744 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1748 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
1750 switch ($target_type) {
1753 case "Post": // "Post" will be supported in a future version
1755 case "StatusMessage":
1756 return self::item_retraction($importer, $contact, $data);;
1759 /// @todo What should we do with an "unshare"?
1760 // Removing the contact isn't correct since we still can read the public items
1761 //contact_remove($contact["id"]);
1765 logger("Unknown target type ".$target_type);
1771 private function receive_status_message($importer, $data, $xml) {
1773 $raw_message = unxmlify($data->raw_message);
1774 $guid = notags(unxmlify($data->guid));
1775 $author = notags(unxmlify($data->author));
1776 $public = notags(unxmlify($data->public));
1777 $created_at = notags(unxmlify($data->created_at));
1778 $provider_display_name = notags(unxmlify($data->provider_display_name));
1780 /// @todo enable support for polls
1781 //if ($data->poll) {
1782 // foreach ($data->poll AS $poll)
1786 $contact = self::allowed_contact_by_handle($importer, $author, false);
1790 if (self::message_exists($importer["uid"], $guid))
1794 if ($data->location)
1795 foreach ($data->location->children() AS $fieldname => $data)
1796 $address[$fieldname] = notags(unxmlify($data));
1798 $body = diaspora2bb($raw_message);
1800 $datarray = array();
1803 foreach ($data->photo AS $photo)
1804 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1806 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1808 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1810 // Add OEmbed and other information to the body
1811 if (!self::is_redmatrix($contact["url"]))
1812 $body = add_page_info_to_body($body, false, true);
1815 $datarray["uid"] = $importer["uid"];
1816 $datarray["contact-id"] = $contact["id"];
1817 $datarray["network"] = NETWORK_DIASPORA;
1819 $datarray["author-name"] = $contact["name"];
1820 $datarray["author-link"] = $contact["url"];
1821 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1823 $datarray["owner-name"] = $datarray["author-name"];
1824 $datarray["owner-link"] = $datarray["author-link"];
1825 $datarray["owner-avatar"] = $datarray["author-avatar"];
1827 $datarray["guid"] = $guid;
1828 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1830 $datarray["verb"] = ACTIVITY_POST;
1831 $datarray["gravity"] = GRAVITY_PARENT;
1833 $datarray["object"] = $xml;
1835 $datarray["body"] = $body;
1837 if ($provider_display_name != "")
1838 $datarray["app"] = $provider_display_name;
1840 $datarray["plink"] = self::plink($author, $guid);
1841 $datarray["private"] = (($public == "false") ? 1 : 0);
1842 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1844 if (isset($address["address"]))
1845 $datarray["location"] = $address["address"];
1847 if (isset($address["lat"]) AND isset($address["lng"]))
1848 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1850 self::fetch_guid($datarray);
1851 $message_id = item_store($datarray);
1854 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1859 /******************************************************************************************
1860 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1861 ******************************************************************************************/
1863 private function my_handle($me) {
1864 if ($contact["addr"] != "")
1865 return $contact["addr"];
1867 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1868 // So - just in case - we build the the address here.
1869 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1872 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1874 logger("Message: ".$msg, LOGGER_DATA);
1876 $handle = self::my_handle($user);
1878 $b64url_data = base64url_encode($msg);
1880 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1882 $type = "application/xml";
1883 $encoding = "base64url";
1884 $alg = "RSA-SHA256";
1886 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1888 $signature = rsa_sign($signable_data,$prvkey);
1889 $sig = base64url_encode($signature);
1891 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1892 "me:env" => array("me:encoding" => "base64url",
1893 "me:alg" => "RSA-SHA256",
1895 "@attributes" => array("type" => "application/xml"),
1896 "me:sig" => $sig)));
1898 $namespaces = array("" => "https://joindiaspora.com/protocol",
1899 "me" => "http://salmon-protocol.org/ns/magic-env");
1901 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1903 logger("magic_env: ".$magic_env, LOGGER_DATA);
1907 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1909 logger("Message: ".$msg, LOGGER_DATA);
1911 // without a public key nothing will work
1914 logger("pubkey missing: contact id: ".$contact["id"]);
1918 $inner_aes_key = random_string(32);
1919 $b_inner_aes_key = base64_encode($inner_aes_key);
1920 $inner_iv = random_string(16);
1921 $b_inner_iv = base64_encode($inner_iv);
1923 $outer_aes_key = random_string(32);
1924 $b_outer_aes_key = base64_encode($outer_aes_key);
1925 $outer_iv = random_string(16);
1926 $b_outer_iv = base64_encode($outer_iv);
1928 $handle = self::my_handle($user);
1930 $padded_data = pkcs5_pad($msg,16);
1931 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1933 $b64_data = base64_encode($inner_encrypted);
1936 $b64url_data = base64url_encode($b64_data);
1937 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1939 $type = "application/xml";
1940 $encoding = "base64url";
1941 $alg = "RSA-SHA256";
1943 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1945 $signature = rsa_sign($signable_data,$prvkey);
1946 $sig = base64url_encode($signature);
1948 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1949 "aes_key" => $b_inner_aes_key,
1950 "author_id" => $handle));
1952 $decrypted_header = xml::from_array($xmldata, $xml, true);
1953 $decrypted_header = pkcs5_pad($decrypted_header,16);
1955 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1957 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1959 $encrypted_outer_key_bundle = "";
1960 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1962 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1964 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1966 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1967 "ciphertext" => base64_encode($ciphertext)));
1968 $cipher_json = base64_encode($encrypted_header_json_object);
1970 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
1971 "me:env" => array("me:encoding" => "base64url",
1972 "me:alg" => "RSA-SHA256",
1974 "@attributes" => array("type" => "application/xml"),
1975 "me:sig" => $sig)));
1977 $namespaces = array("" => "https://joindiaspora.com/protocol",
1978 "me" => "http://salmon-protocol.org/ns/magic-env");
1980 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1982 logger("magic_env: ".$magic_env, LOGGER_DATA);
1986 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1989 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1991 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1993 // The data that will be transmitted is double encoded via "urlencode", strange ...
1994 $slap = "xml=".urlencode(urlencode($magic_env));
1998 private function signature($owner, $message) {
2000 unset($sigmsg["author_signature"]);
2001 unset($sigmsg["parent_author_signature"]);
2003 $signed_text = implode(";", $sigmsg);
2005 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2008 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2012 $enabled = intval(get_config("system", "diaspora_enabled"));
2016 $logid = random_string(4);
2017 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2019 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2023 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2025 if (!$queue_run && was_recently_delayed($contact["id"])) {
2028 if (!intval(get_config("system", "diaspora_test"))) {
2029 post_url($dest_url."/", $slap);
2030 $return_code = $a->get_curl_code();
2032 logger("test_mode");
2037 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2039 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2040 logger("queue message");
2042 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2043 intval($contact["id"]),
2044 dbesc(NETWORK_DIASPORA),
2046 intval($public_batch)
2049 logger("add_to_queue ignored - identical item already in queue");
2051 // queue message for redelivery
2052 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2056 return(($return_code) ? $return_code : (-1));
2060 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2062 $data = array("XML" => array("post" => array($type => $message)));
2064 $msg = xml::from_array($data, $xml);
2066 logger('message: '.$msg, LOGGER_DATA);
2067 logger('send guid '.$guid, LOGGER_DEBUG);
2069 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2072 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2075 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2077 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2079 return $return_code;
2082 public static function send_share($owner,$contact) {
2084 $message = array("sender_handle" => self::my_handle($owner),
2085 "recipient_handle" => $contact["addr"]);
2087 return self::build_and_transmit($owner, $contact, "request", $message);
2090 public static function send_unshare($owner,$contact) {
2092 $message = array("post_guid" => $owner["guid"],
2093 "diaspora_handle" => self::my_handle($owner),
2094 "type" => "Person");
2096 return self::build_and_transmit($owner, $contact, "retraction", $message);
2099 public static function is_reshare($body) {
2100 $body = trim($body);
2102 // Skip if it isn't a pure repeated messages
2103 // Does it start with a share?
2104 if (strpos($body, "[share") > 0)
2107 // Does it end with a share?
2108 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2111 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2112 // Skip if there is no shared message in there
2113 if ($body == $attributes)
2117 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2118 if ($matches[1] != "")
2119 $guid = $matches[1];
2121 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2122 if ($matches[1] != "")
2123 $guid = $matches[1];
2126 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2127 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2130 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2131 $ret["root_guid"] = $guid;
2137 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2138 if ($matches[1] != "")
2139 $profile = $matches[1];
2141 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2142 if ($matches[1] != "")
2143 $profile = $matches[1];
2147 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2148 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2152 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2153 if ($matches[1] != "")
2154 $link = $matches[1];
2156 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2157 if ($matches[1] != "")
2158 $link = $matches[1];
2160 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2161 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2166 public static function send_status($item, $owner, $contact, $public_batch = false) {
2168 $myaddr = self::my_handle($owner);
2170 $public = (($item["private"]) ? "false" : "true");
2172 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2174 // Detect a share element and do a reshare
2175 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2176 $message = array("root_diaspora_id" => $ret["root_handle"],
2177 "root_guid" => $ret["root_guid"],
2178 "guid" => $item["guid"],
2179 "diaspora_handle" => $myaddr,
2180 "public" => $public,
2181 "created_at" => $created,
2182 "provider_display_name" => $item["app"]);
2186 $title = $item["title"];
2187 $body = $item["body"];
2189 // convert to markdown
2190 $body = html_entity_decode(bb2diaspora($body));
2194 $body = "## ".html_entity_decode($title)."\n\n".$body;
2196 if ($item["attach"]) {
2197 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2199 $body .= "\n".t("Attachments:")."\n";
2200 foreach($matches as $mtch)
2201 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2205 $location = array();
2207 if ($item["location"] != "")
2208 $location["address"] = $item["location"];
2210 if ($item["coord"] != "") {
2211 $coord = explode(" ", $item["coord"]);
2212 $location["lat"] = $coord[0];
2213 $location["lng"] = $coord[1];
2216 $message = array("raw_message" => $body,
2217 "location" => $location,
2218 "guid" => $item["guid"],
2219 "diaspora_handle" => $myaddr,
2220 "public" => $public,
2221 "created_at" => $created,
2222 "provider_display_name" => $item["app"]);
2224 if (count($location) == 0)
2225 unset($message["location"]);
2227 $type = "status_message";
2230 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2233 private function construct_like($item, $owner) {
2235 $myaddr = self::my_handle($owner);
2237 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2238 dbesc($item["thr-parent"]));
2244 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2247 return(array("positive" => $positive,
2248 "guid" => $item["guid"],
2249 "target_type" => $target_type,
2250 "parent_guid" => $parent["guid"],
2251 "author_signature" => $authorsig,
2252 "diaspora_handle" => $myaddr));
2255 private function construct_comment($item, $owner) {
2257 $myaddr = self::my_handle($owner);
2259 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2260 intval($item["parent"]),
2261 intval($item["parent"])
2269 $text = html_entity_decode(bb2diaspora($item["body"]));
2271 return(array("guid" => $item["guid"],
2272 "parent_guid" => $parent["guid"],
2273 "author_signature" => "",
2275 "diaspora_handle" => $myaddr));
2278 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2280 if($item['verb'] === ACTIVITY_LIKE) {
2281 $message = self::construct_like($item, $owner);
2284 $message = self::construct_comment($item, $owner);
2291 $message["author_signature"] = self::signature($owner, $message);
2293 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2296 private function message_from_signatur($item, $signature) {
2298 // Split the signed text
2299 $signed_parts = explode(";", $signature['signed_text']);
2301 if ($item["deleted"])
2302 $message = array("parent_author_signature" => "",
2303 "target_guid" => $signed_parts[0],
2304 "target_type" => $signed_parts[1],
2305 "sender_handle" => $signature['signer'],
2306 "target_author_signature" => $signature['signature']);
2307 elseif ($item['verb'] === ACTIVITY_LIKE)
2308 $message = array("positive" => $signed_parts[0],
2309 "guid" => $signed_parts[1],
2310 "target_type" => $signed_parts[2],
2311 "parent_guid" => $signed_parts[3],
2312 "parent_author_signature" => "",
2313 "author_signature" => $signature['signature'],
2314 "diaspora_handle" => $signed_parts[4]);
2316 // Remove the comment guid
2317 $guid = array_shift($signed_parts);
2319 // Remove the parent guid
2320 $parent_guid = array_shift($signed_parts);
2322 // Remove the handle
2323 $handle = array_pop($signed_parts);
2325 // Glue the parts together
2326 $text = implode(";", $signed_parts);
2328 $message = array("guid" => $guid,
2329 "parent_guid" => $parent_guid,
2330 "parent_author_signature" => "",
2331 "author_signature" => $signature['signature'],
2332 "text" => implode(";", $signed_parts),
2333 "diaspora_handle" => $handle);
2338 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2340 if ($item["deleted"]) {
2341 $sql_sign_id = "retract_iid";
2342 $type = "relayable_retraction";
2343 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2344 $sql_sign_id = "iid";
2347 $sql_sign_id = "iid";
2351 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2353 // fetch the original signature
2355 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2356 intval($item["id"]));
2359 return self::send_followup($item, $owner, $contact, $public_batch);
2363 // Old way - is used by the internal Friendica functions
2364 /// @todo Change all signatur storing functions to the new format
2365 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2366 $message = self::message_from_signatur($item, $signature);
2368 $msg = json_decode($signature['signed_text'], true);
2371 foreach ($msg AS $field => $data) {
2372 if (!$item["deleted"]) {
2373 if ($field == "author")
2374 $field = "diaspora_handle";
2375 if ($field == "parent_type")
2376 $field = "target_type";
2379 $message[$field] = $data;
2383 if ($item["deleted"]) {
2384 $signed_text = $message["target_guid"].';'.$message["target_type"];
2385 $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2387 $message["parent_author_signature"] = self::signature($owner, $message);
2389 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2391 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2394 public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2396 $myaddr = self::my_handle($owner);
2398 // Check whether the retraction is for a top-level post or whether it's a relayable
2399 if ($item["uri"] !== $item["parent-uri"]) {
2400 $msg_type = "relayable_retraction";
2401 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2403 $msg_type = "signed_retraction";
2404 $target_type = "StatusMessage";
2407 $signed_text = $item["guid"].";".$target_type;
2409 $message = array("target_guid" => $item['guid'],
2410 "target_type" => $target_type,
2411 "sender_handle" => $myaddr,
2412 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2414 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2417 public static function send_mail($item, $owner, $contact) {
2419 $myaddr = self::my_handle($owner);
2421 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2422 intval($item["convid"]),
2423 intval($item["uid"])
2427 logger("conversation not found.");
2433 "guid" => $cnv["guid"],
2434 "subject" => $cnv["subject"],
2435 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2436 "diaspora_handle" => $cnv["creator"],
2437 "participant_handles" => $cnv["recips"]
2440 $body = bb2diaspora($item["body"]);
2441 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2443 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2444 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2447 "guid" => $item["guid"],
2448 "parent_guid" => $cnv["guid"],
2449 "parent_author_signature" => $sig,
2450 "author_signature" => $sig,
2452 "created_at" => $created,
2453 "diaspora_handle" => $myaddr,
2454 "conversation_guid" => $cnv["guid"]
2457 if ($item["reply"]) {
2461 $message = array("guid" => $cnv["guid"],
2462 "subject" => $cnv["subject"],
2463 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2465 "diaspora_handle" => $cnv["creator"],
2466 "participant_handles" => $cnv["recips"]);
2468 $type = "conversation";
2471 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2474 public static function send_profile($uid) {
2479 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2480 AND `uid` = %d AND `rel` != %d",
2481 dbesc(NETWORK_DIASPORA),
2483 intval(CONTACT_IS_SHARING)
2488 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2490 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2491 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2492 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
2501 $handle = $profile["addr"];
2502 $first = ((strpos($profile['name'],' ')
2503 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
2504 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
2505 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
2506 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
2507 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
2508 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
2510 if ($searchable === 'true') {
2511 $dob = '1000-00-00';
2513 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
2514 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
2516 $about = $profile['about'];
2517 $about = strip_tags(bbcode($about));
2519 $location = formatted_location($profile);
2521 if ($profile['pub_keywords']) {
2522 $kw = str_replace(',',' ',$profile['pub_keywords']);
2523 $kw = str_replace(' ',' ',$kw);
2524 $arr = explode(' ',$profile['pub_keywords']);
2526 for($x = 0; $x < 5; $x ++) {
2528 $tags .= '#'. trim($arr[$x]) .' ';
2532 $tags = trim($tags);
2535 $message = array("diaspora_handle" => $handle,
2536 "first_name" => $first,
2537 "last_name" => $last,
2538 "image_url" => $large,
2539 "image_url_medium" => $medium,
2540 "image_url_small" => $small,
2542 "gender" => $profile['gender'],
2544 "location" => $location,
2545 "searchable" => $searchable,
2546 "tag_string" => $tags);
2548 foreach($recips as $recip)
2549 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);