3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
17 * - receive connect request
18 * - receive profile data
26 * - receive account deletion
29 * - send status retraction
30 * - send comment retraction
31 * - send like retraction
32 * - relay comment retraction
33 * - relay like retraction
37 require_once("include/items.php");
38 require_once("include/bb2diaspora.php");
39 require_once("include/Scrape.php");
40 require_once("include/Contact.php");
41 require_once("include/Photo.php");
42 require_once("include/socgraph.php");
43 require_once("include/group.php");
44 require_once("include/xml.php");
45 require_once("include/datetime.php");
46 require_once("include/queue_fn.php");
49 * @brief This class contain functions to create and send Diaspora XML files
54 public static function relay_list() {
56 $serverdata = get_config("system", "relay_server");
57 if ($serverdata == "")
62 $servers = explode(",", $serverdata);
64 foreach($servers AS $server) {
65 $server = trim($server);
66 $batch = $server."/receive/public";
68 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
71 $addr = "relay@".str_replace("http://", "", normalise_link($server));
73 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
74 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
79 dbesc(normalise_link($server)),
81 dbesc(NETWORK_DIASPORA),
82 intval(CONTACT_IS_FOLLOWER),
83 dbesc(datetime_convert()),
84 dbesc(datetime_convert()),
85 dbesc(datetime_convert())
88 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
90 $relay[] = $relais[0];
92 $relay[] = $relais[0];
98 function repair_signature($signature, $handle = "", $level = 1) {
100 if ($signature == "")
103 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
104 $signature = base64_decode($signature);
105 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
107 // Do a recursive call to be able to fix even multiple levels
109 $signature = self::repair_signature($signature, $handle, ++$level);
116 * @brief: Decodes incoming Diaspora message
118 * @param array $importer from user table
119 * @param string $xml urldecoded Diaspora salmon
122 * 'message' -> decoded Diaspora XML message
123 * 'author' -> author diaspora handle
124 * 'key' -> author public key (converted to pkcs#8)
126 function decode($importer, $xml) {
129 $basedom = parse_xml_string($xml);
131 if (!is_object($basedom))
134 $children = $basedom->children('https://joindiaspora.com/protocol');
136 if($children->header) {
138 $author_link = str_replace('acct:','',$children->header->author_id);
141 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
143 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
144 $ciphertext = base64_decode($encrypted_header->ciphertext);
146 $outer_key_bundle = '';
147 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
149 $j_outer_key_bundle = json_decode($outer_key_bundle);
151 $outer_iv = base64_decode($j_outer_key_bundle->iv);
152 $outer_key = base64_decode($j_outer_key_bundle->key);
154 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
157 $decrypted = pkcs5_unpad($decrypted);
160 * $decrypted now contains something like
163 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
164 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
165 * <author_id>galaxor@diaspora.priateship.org</author_id>
166 * </decrypted_header>
169 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
170 $idom = parse_xml_string($decrypted,false);
172 $inner_iv = base64_decode($idom->iv);
173 $inner_aes_key = base64_decode($idom->aes_key);
175 $author_link = str_replace('acct:','',$idom->author_id);
178 $dom = $basedom->children(NAMESPACE_SALMON_ME);
180 // figure out where in the DOM tree our data is hiding
182 if($dom->provenance->data)
183 $base = $dom->provenance;
184 elseif($dom->env->data)
190 logger('unable to locate salmon data in xml');
191 http_status_exit(400);
195 // Stash the signature away for now. We have to find their key or it won't be good for anything.
196 $signature = base64url_decode($base->sig);
200 // strip whitespace so our data element will return to one big base64 blob
201 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
204 // stash away some other stuff for later
206 $type = $base->data[0]->attributes()->type[0];
207 $keyhash = $base->sig[0]->attributes()->keyhash[0];
208 $encoding = $base->encoding;
212 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
216 $data = base64url_decode($data);
220 $inner_decrypted = $data;
223 // Decode the encrypted blob
225 $inner_encrypted = base64_decode($data);
226 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
227 $inner_decrypted = pkcs5_unpad($inner_decrypted);
231 logger('Could not retrieve author URI.');
232 http_status_exit(400);
234 // Once we have the author URI, go to the web and try to find their public key
235 // (first this will look it up locally if it is in the fcontact cache)
236 // This will also convert diaspora public key from pkcs#1 to pkcs#8
238 logger('Fetching key for '.$author_link);
239 $key = self::key($author_link);
242 logger('Could not retrieve author key.');
243 http_status_exit(400);
246 $verify = rsa_verify($signed_data,$signature,$key);
249 logger('Message did not verify. Discarding.');
250 http_status_exit(400);
253 logger('Message verified.');
255 return array('message' => (string)$inner_decrypted,
256 'author' => unxmlify($author_link),
257 'key' => (string)$key);
263 * @brief Dispatches public messages and find the fitting receivers
265 * @param array $msg The post that will be dispatched
267 * @return bool Was the message accepted?
269 public static function dispatch_public($msg) {
271 $enabled = intval(get_config("system", "diaspora_enabled"));
273 logger("diaspora is disabled");
277 // Use a dummy importer to import the data for the public copy
278 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
279 $item_id = self::dispatch($importer,$msg);
281 // Now distribute it to the followers
282 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
283 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
284 AND NOT `account_expired` AND NOT `account_removed`",
285 dbesc(NETWORK_DIASPORA),
286 dbesc($msg["author"])
290 logger("delivering to: ".$rr["username"]);
291 self::dispatch($rr,$msg);
294 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
300 * @brief Dispatches the different message types to the different functions
302 * @param array $importer Array of the importer user
303 * @param array $msg The post that will be dispatched
305 * @return bool Was the message accepted?
307 public static function dispatch($importer, $msg) {
309 // The sender is the handle of the contact that sent the message.
310 // This will often be different with relayed messages (for example "like" and "comment")
311 $sender = $msg["author"];
313 if (!diaspora::valid_posting($msg, $fields)) {
314 logger("Invalid posting");
318 $type = $fields->getName();
320 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
323 case "account_deletion":
324 return self::receive_account_deletion($importer, $fields);
327 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
330 return self::receive_conversation($importer, $msg, $fields);
333 return self::receive_like($importer, $sender, $fields);
336 return self::receive_message($importer, $fields);
338 case "participation": // Not implemented
339 return self::receive_participation($importer, $fields);
341 case "photo": // Not implemented
342 return self::receive_photo($importer, $fields);
344 case "poll_participation": // Not implemented
345 return self::receive_poll_participation($importer, $fields);
348 return self::receive_profile($importer, $fields);
351 return self::receive_request($importer, $fields);
354 return self::receive_reshare($importer, $fields, $msg["message"]);
357 return self::receive_retraction($importer, $sender, $fields);
359 case "status_message":
360 return self::receive_status_message($importer, $fields, $msg["message"]);
363 logger("Unknown message type ".$type);
371 * @brief Checks if a posting is valid and fetches the data fields.
373 * This function does not only check the signature.
374 * It also does the conversion between the old and the new diaspora format.
376 * @param array $msg Array with the XML, the sender handle and the sender signature
377 * @param object $fields SimpleXML object that contains the posting when it is valid
379 * @return bool Is the posting valid?
381 private function valid_posting($msg, &$fields) {
383 $data = parse_xml_string($msg["message"], false);
385 if (!is_object($data))
388 $first_child = $data->getName();
390 // Is this the new or the old version?
391 if ($data->getName() == "XML") {
393 foreach ($data->post->children() as $child)
400 $type = $element->getName();
403 // All retractions are handled identically from now on.
404 // In the new version there will only be "retraction".
405 if (in_array($type, array("signed_retraction", "relayable_retraction")))
406 $type = "retraction";
408 $fields = new SimpleXMLElement("<".$type."/>");
412 foreach ($element->children() AS $fieldname => $entry) {
414 // Translation for the old XML structure
415 if ($fieldname == "diaspora_handle")
416 $fieldname = "author";
418 if ($fieldname == "participant_handles")
419 $fieldname = "participants";
421 if (in_array($type, array("like", "participation"))) {
422 if ($fieldname == "target_type")
423 $fieldname = "parent_type";
426 if ($fieldname == "sender_handle")
427 $fieldname = "author";
429 if ($fieldname == "recipient_handle")
430 $fieldname = "recipient";
432 if ($fieldname == "root_diaspora_id")
433 $fieldname = "root_author";
435 if ($type == "retraction") {
436 if ($fieldname == "post_guid")
437 $fieldname = "target_guid";
439 if ($fieldname == "type")
440 $fieldname = "target_type";
444 if ($fieldname == "author_signature")
445 $author_signature = base64_decode($entry);
446 elseif ($fieldname == "parent_author_signature")
447 $parent_author_signature = base64_decode($entry);
448 elseif ($fieldname != "target_author_signature") {
449 if ($signed_data != "") {
451 $signed_data_parent .= ";";
454 $signed_data .= $entry;
456 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
457 ($orig_type == "relayable_retraction"))
458 xml::copy($entry, $fields, $fieldname);
461 // This is something that shouldn't happen at all.
462 if (in_array($type, array("status_message", "reshare", "profile")))
463 if ($msg["author"] != $fields->author) {
464 logger("Message handle is not the same as envelope sender. Quitting this message.");
468 // Only some message types have signatures. So we quit here for the other types.
469 if (!in_array($type, array("comment", "message", "like")))
472 // No author_signature? This is a must, so we quit.
473 if (!isset($author_signature))
476 if (isset($parent_author_signature)) {
477 $key = self::key($msg["author"]);
479 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
483 $key = self::key($fields->author);
485 return rsa_verify($signed_data, $author_signature, $key, "sha256");
489 * @brief Fetches the public key for a given handle
491 * @param string $handle The handle
493 * @return string The public key
495 private function key($handle) {
496 $handle = strval($handle);
498 logger("Fetching diaspora key for: ".$handle);
500 $r = self::person_by_handle($handle);
508 * @brief Fetches data for a given handle
510 * @param string $handle The handle
512 * @return array the queried data
514 private function person_by_handle($handle) {
516 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
517 dbesc(NETWORK_DIASPORA),
522 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
524 // update record occasionally so it doesn't get stale
525 $d = strtotime($person["updated"]." +00:00");
526 if ($d < strtotime("now - 14 days"))
530 if (!$person OR $update) {
531 logger("create or refresh", LOGGER_DEBUG);
532 $r = probe_url($handle, PROBE_DIASPORA);
534 // Note that Friendica contacts will return a "Diaspora person"
535 // if Diaspora connectivity is enabled on their server
536 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
537 self::add_fcontact($r, $update);
545 * @brief Updates the fcontact table
547 * @param array $arr The fcontact data
548 * @param bool $update Update or insert?
550 * @return string The id of the fcontact entry
552 private function add_fcontact($arr, $update = false) {
555 $r = q("UPDATE `fcontact` SET
568 WHERE `url` = '%s' AND `network` = '%s'",
570 dbesc($arr["photo"]),
571 dbesc($arr["request"]),
574 dbesc($arr["batch"]),
575 dbesc($arr["notify"]),
577 dbesc($arr["confirm"]),
578 dbesc($arr["alias"]),
579 dbesc($arr["pubkey"]),
580 dbesc(datetime_convert()),
582 dbesc($arr["network"])
585 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
586 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
587 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
590 dbesc($arr["photo"]),
591 dbesc($arr["request"]),
594 dbesc($arr["batch"]),
595 dbesc($arr["notify"]),
597 dbesc($arr["confirm"]),
598 dbesc($arr["network"]),
599 dbesc($arr["alias"]),
600 dbesc($arr["pubkey"]),
601 dbesc(datetime_convert())
608 public static function handle_from_contact($contact_id) {
611 logger("contact id is ".$contact_id, LOGGER_DEBUG);
613 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
619 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
621 if($contact['addr'] != "")
622 $handle = $contact['addr'];
623 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
624 $baseurl_start = strpos($contact['url'],'://') + 3;
625 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
626 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
627 $handle = $contact['nick'].'@'.$baseurl;
634 private function contact_by_handle($uid, $handle) {
635 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
643 $handle_parts = explode("@", $handle);
644 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
645 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
656 private function post_allow($importer, $contact, $is_comment = false) {
658 // perhaps we were already sharing with this person. Now they're sharing with us.
659 // That makes us friends.
660 // Normally this should have handled by getting a request - but this could get lost
661 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
662 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
663 intval(CONTACT_IS_FRIEND),
664 intval($contact["id"]),
665 intval($importer["uid"])
667 $contact["rel"] = CONTACT_IS_FRIEND;
668 logger("defining user ".$contact["nick"]." as friend");
671 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
673 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
675 if($contact["rel"] == CONTACT_IS_FOLLOWER)
676 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
679 // Messages for the global users are always accepted
680 if ($importer["uid"] == 0)
686 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
687 $contact = self::contact_by_handle($importer["uid"], $handle);
689 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
693 if (!self::post_allow($importer, $contact, $is_comment)) {
694 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
700 private function message_exists($uid, $guid) {
701 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
707 logger("message ".$guid." already exists for user ".$uid);
714 private function fetch_guid($item) {
715 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
716 function ($match) use ($item){
717 return(self::fetch_guid_sub($match, $item));
721 private function fetch_guid_sub($match, $item) {
722 if (!self::store_by_guid($match[1], $item["author-link"]))
723 self::store_by_guid($match[1], $item["owner-link"]);
726 private function store_by_guid($guid, $server, $uid = 0) {
727 $serverparts = parse_url($server);
728 $server = $serverparts["scheme"]."://".$serverparts["host"];
730 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
732 $msg = self::message($guid, $server);
737 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
739 // Now call the dispatcher
740 return self::dispatch_public($msg);
743 private function message($guid, $server, $level = 0) {
748 // This will work for Diaspora and newer Friendica servers
749 $source_url = $server."/p/".$guid.".xml";
750 $x = fetch_url($source_url);
754 $source_xml = parse_xml_string($x, false);
756 if (!is_object($source_xml))
759 if ($source_xml->post->reshare) {
760 // Reshare of a reshare - old Diaspora version
761 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
762 } elseif ($source_xml->getName() == "reshare") {
763 // Reshare of a reshare - new Diaspora version
764 return self::message($source_xml->root_guid, $server, ++$level);
769 // Fetch the author - for the old and the new Diaspora version
770 if ($source_xml->post->status_message->diaspora_handle)
771 $author = (string)$source_xml->post->status_message->diaspora_handle;
772 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
773 $author = (string)$source_xml->author;
775 // If this isn't a "status_message" then quit
779 $msg = array("message" => $x, "author" => $author);
781 $msg["key"] = self::key($msg["author"]);
786 private function parent_item($uid, $guid, $author, $contact) {
787 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
788 `author-name`, `author-link`, `author-avatar`,
789 `owner-name`, `owner-link`, `owner-avatar`
790 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
791 intval($uid), dbesc($guid));
794 $result = self::store_by_guid($guid, $contact["url"], $uid);
797 $person = self::person_by_handle($author);
798 $result = self::store_by_guid($guid, $person["url"], $uid);
802 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
804 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
805 `author-name`, `author-link`, `author-avatar`,
806 `owner-name`, `owner-link`, `owner-avatar`
807 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
808 intval($uid), dbesc($guid));
813 logger("parent item not found: parent: ".$guid." - user: ".$uid);
816 logger("parent item found: parent: ".$guid." - user: ".$uid);
821 private function author_contact_by_url($contact, $person, $uid) {
823 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
824 dbesc(normalise_link($person["url"])), intval($uid));
827 $network = $r[0]["network"];
829 $cid = $contact["id"];
830 $network = NETWORK_DIASPORA;
833 return (array("cid" => $cid, "network" => $network));
836 public static function is_redmatrix($url) {
837 return(strstr($url, "/channel/"));
840 private function plink($addr, $guid) {
841 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
845 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
847 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
848 // So we try another way as well.
849 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
851 $r[0]["network"] = $s[0]["network"];
853 if ($r[0]["network"] == NETWORK_DFRN)
854 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
856 if (self::is_redmatrix($r[0]["url"]))
857 return $r[0]["url"]."/?f=&mid=".$guid;
859 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
862 private function receive_account_deletion($importer, $data) {
863 $author = notags(unxmlify($data->author));
865 $contact = self::contact_by_handle($importer["uid"], $author);
867 logger("cannot find contact for author: ".$author);
871 // We now remove the contact
872 contact_remove($contact["id"]);
876 private function receive_comment($importer, $sender, $data, $xml) {
877 $guid = notags(unxmlify($data->guid));
878 $parent_guid = notags(unxmlify($data->parent_guid));
879 $text = unxmlify($data->text);
880 $author = notags(unxmlify($data->author));
882 $contact = self::allowed_contact_by_handle($importer, $sender, true);
886 if (self::message_exists($importer["uid"], $guid))
889 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
893 $person = self::person_by_handle($author);
894 if (!is_array($person)) {
895 logger("unable to find author details");
899 // Fetch the contact id - if we know this contact
900 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
904 $datarray["uid"] = $importer["uid"];
905 $datarray["contact-id"] = $author_contact["cid"];
906 $datarray["network"] = $author_contact["network"];
908 $datarray["author-name"] = $person["name"];
909 $datarray["author-link"] = $person["url"];
910 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
912 $datarray["owner-name"] = $contact["name"];
913 $datarray["owner-link"] = $contact["url"];
914 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
916 $datarray["guid"] = $guid;
917 $datarray["uri"] = $author.":".$guid;
919 $datarray["type"] = "remote-comment";
920 $datarray["verb"] = ACTIVITY_POST;
921 $datarray["gravity"] = GRAVITY_COMMENT;
922 $datarray["parent-uri"] = $parent_item["uri"];
924 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
925 $datarray["object"] = $xml;
927 $datarray["body"] = diaspora2bb($text);
929 self::fetch_guid($datarray);
931 $message_id = item_store($datarray);
934 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
936 // If we are the origin of the parent we store the original data and notify our followers
937 if($message_id AND $parent_item["origin"]) {
939 // Formerly we stored the signed text, the signature and the author in different fields.
940 // We now store the raw data so that we are more flexible.
941 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
943 dbesc(json_encode($data))
947 proc_run("php", "include/notifier.php", "comment-import", $message_id);
953 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
954 $guid = notags(unxmlify($data->guid));
955 $subject = notags(unxmlify($data->subject));
956 $author = notags(unxmlify($data->author));
960 $msg_guid = notags(unxmlify($mesg->guid));
961 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
962 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
963 $msg_author_signature = notags(unxmlify($mesg->author_signature));
964 $msg_text = unxmlify($mesg->text);
965 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
967 // "diaspora_handle" is the element name from the old version
968 // "author" is the element name from the new version
970 $msg_author = notags(unxmlify($mesg->author));
971 elseif ($mesg->diaspora_handle)
972 $msg_author = notags(unxmlify($mesg->diaspora_handle));
976 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
978 if($msg_conversation_guid != $guid) {
979 logger("message conversation guid does not belong to the current conversation.");
983 $body = diaspora2bb($msg_text);
984 $message_uri = $msg_author.":".$msg_guid;
986 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
988 $author_signature = base64_decode($msg_author_signature);
990 if(strcasecmp($msg_author,$msg["author"]) == 0) {
994 $person = self::person_by_handle($msg_author);
996 if (is_array($person) && x($person, "pubkey"))
997 $key = $person["pubkey"];
999 logger("unable to find author details");
1004 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1005 logger("verification failed.");
1009 if($msg_parent_author_signature) {
1010 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1012 $parent_author_signature = base64_decode($msg_parent_author_signature);
1016 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1017 logger("owner verification failed.");
1022 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1026 logger("duplicate message already delivered.", LOGGER_DEBUG);
1030 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1031 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1032 intval($importer["uid"]),
1034 intval($conversation["id"]),
1035 dbesc($person["name"]),
1036 dbesc($person["photo"]),
1037 dbesc($person["url"]),
1038 intval($contact["id"]),
1043 dbesc($message_uri),
1044 dbesc($author.":".$guid),
1045 dbesc($msg_created_at)
1048 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1049 dbesc(datetime_convert()),
1050 intval($conversation["id"])
1054 "type" => NOTIFY_MAIL,
1055 "notify_flags" => $importer["notify-flags"],
1056 "language" => $importer["language"],
1057 "to_name" => $importer["username"],
1058 "to_email" => $importer["email"],
1059 "uid" =>$importer["uid"],
1060 "item" => array("subject" => $subject, "body" => $body),
1061 "source_name" => $person["name"],
1062 "source_link" => $person["url"],
1063 "source_photo" => $person["thumb"],
1064 "verb" => ACTIVITY_POST,
1069 private function receive_conversation($importer, $msg, $data) {
1070 $guid = notags(unxmlify($data->guid));
1071 $subject = notags(unxmlify($data->subject));
1072 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1073 $author = notags(unxmlify($data->author));
1074 $participants = notags(unxmlify($data->participants));
1076 $messages = $data->message;
1078 if (!count($messages)) {
1079 logger("empty conversation");
1083 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1087 $conversation = null;
1089 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1090 intval($importer["uid"]),
1094 $conversation = $c[0];
1096 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1097 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1098 intval($importer["uid"]),
1101 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1102 dbesc(datetime_convert()),
1104 dbesc($participants)
1107 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1108 intval($importer["uid"]),
1113 $conversation = $c[0];
1115 if (!$conversation) {
1116 logger("unable to create conversation.");
1120 foreach($messages as $mesg)
1121 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1126 private function construct_like_body($contact, $parent_item, $guid) {
1127 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1129 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1130 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1131 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1133 return sprintf($bodyverb, $ulink, $alink, $plink);
1136 private function construct_like_object($importer, $parent_item) {
1137 $objtype = ACTIVITY_OBJ_NOTE;
1138 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1139 $parent_body = $parent_item["body"];
1141 $xmldata = array("object" => array("type" => $objtype,
1143 "id" => $parent_item["uri"],
1146 "content" => $parent_body));
1148 return xml::from_array($xmldata, $xml, true);
1151 private function receive_like($importer, $sender, $data) {
1152 $positive = notags(unxmlify($data->positive));
1153 $guid = notags(unxmlify($data->guid));
1154 $parent_type = notags(unxmlify($data->parent_type));
1155 $parent_guid = notags(unxmlify($data->parent_guid));
1156 $author = notags(unxmlify($data->author));
1158 // likes on comments aren't supported by Diaspora - only on posts
1159 // But maybe this will be supported in the future, so we will accept it.
1160 if (!in_array($parent_type, array("Post", "Comment")))
1163 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1167 if (self::message_exists($importer["uid"], $guid))
1170 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1174 $person = self::person_by_handle($author);
1175 if (!is_array($person)) {
1176 logger("unable to find author details");
1180 // Fetch the contact id - if we know this contact
1181 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1183 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1184 // We would accept this anyhow.
1185 if ($positive === "true")
1186 $verb = ACTIVITY_LIKE;
1188 $verb = ACTIVITY_DISLIKE;
1190 $datarray = array();
1192 $datarray["uid"] = $importer["uid"];
1193 $datarray["contact-id"] = $author_contact["cid"];
1194 $datarray["network"] = $author_contact["network"];
1196 $datarray["author-name"] = $person["name"];
1197 $datarray["author-link"] = $person["url"];
1198 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1200 $datarray["owner-name"] = $contact["name"];
1201 $datarray["owner-link"] = $contact["url"];
1202 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1204 $datarray["guid"] = $guid;
1205 $datarray["uri"] = $author.":".$guid;
1207 $datarray["type"] = "activity";
1208 $datarray["verb"] = $verb;
1209 $datarray["gravity"] = GRAVITY_LIKE;
1210 $datarray["parent-uri"] = $parent_item["uri"];
1212 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1213 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1215 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1217 $message_id = item_store($datarray);
1220 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1222 // If we are the origin of the parent we store the original data and notify our followers
1223 if($message_id AND $parent_item["origin"]) {
1225 // Formerly we stored the signed text, the signature and the author in different fields.
1226 // We now store the raw data so that we are more flexible.
1227 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1228 intval($message_id),
1229 dbesc(json_encode($data))
1233 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1239 private function receive_message($importer, $data) {
1240 $guid = notags(unxmlify($data->guid));
1241 $parent_guid = notags(unxmlify($data->parent_guid));
1242 $text = unxmlify($data->text);
1243 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1244 $author = notags(unxmlify($data->author));
1245 $conversation_guid = notags(unxmlify($data->conversation_guid));
1247 $contact = self::allowed_contact_by_handle($importer, $author, true);
1251 $conversation = null;
1253 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1254 intval($importer["uid"]),
1255 dbesc($conversation_guid)
1258 $conversation = $c[0];
1260 logger("conversation not available.");
1266 $body = diaspora2bb($text);
1267 $message_uri = $author.":".$guid;
1269 $person = self::person_by_handle($author);
1271 logger("unable to find author details");
1275 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1276 dbesc($message_uri),
1277 intval($importer["uid"])
1280 logger("duplicate message already delivered.", LOGGER_DEBUG);
1284 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1285 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1286 intval($importer["uid"]),
1288 intval($conversation["id"]),
1289 dbesc($person["name"]),
1290 dbesc($person["photo"]),
1291 dbesc($person["url"]),
1292 intval($contact["id"]),
1293 dbesc($conversation["subject"]),
1297 dbesc($message_uri),
1298 dbesc($author.":".$parent_guid),
1302 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1303 dbesc(datetime_convert()),
1304 intval($conversation["id"])
1310 private function receive_participation($importer, $data) {
1311 // I'm not sure if we can fully support this message type
1315 private function receive_photo($importer, $data) {
1316 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1320 private function receive_poll_participation($importer, $data) {
1321 // We don't support polls by now
1325 private function receive_profile($importer, $data) {
1326 $author = notags(unxmlify($data->author));
1328 $contact = self::contact_by_handle($importer["uid"], $author);
1332 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1333 $image_url = unxmlify($data->image_url);
1334 $birthday = unxmlify($data->birthday);
1335 $location = diaspora2bb(unxmlify($data->location));
1336 $about = diaspora2bb(unxmlify($data->bio));
1337 $gender = unxmlify($data->gender);
1338 $searchable = (unxmlify($data->searchable) == "true");
1339 $nsfw = (unxmlify($data->nsfw) == "true");
1340 $tags = unxmlify($data->tag_string);
1342 $tags = explode("#", $tags);
1344 $keywords = array();
1345 foreach ($tags as $tag) {
1346 $tag = trim(strtolower($tag));
1351 $keywords = implode(", ", $keywords);
1353 $handle_parts = explode("@", $author);
1354 $nick = $handle_parts[0];
1357 $name = $handle_parts[0];
1359 if( preg_match("|^https?://|", $image_url) === 0)
1360 $image_url = "http://".$handle_parts[1].$image_url;
1362 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1364 // Generic birthday. We don't know the timezone. The year is irrelevant.
1366 $birthday = str_replace("1000", "1901", $birthday);
1368 if ($birthday != "")
1369 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1371 // this is to prevent multiple birthday notifications in a single year
1372 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1374 if(substr($birthday,5) === substr($contact["bd"],5))
1375 $birthday = $contact["bd"];
1377 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1378 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1382 dbesc(datetime_convert()),
1388 intval($contact["id"]),
1389 intval($importer["uid"])
1393 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1394 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1397 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1398 "photo" => $image_url, "name" => $name, "location" => $location,
1399 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1400 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1401 "hide" => !$searchable, "nsfw" => $nsfw);
1403 update_gcontact($gcontact);
1405 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1410 private function receive_request_make_friend($importer, $contact) {
1414 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1415 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1416 intval(CONTACT_IS_FRIEND),
1417 intval($contact["id"]),
1418 intval($importer["uid"])
1421 // send notification
1423 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1424 intval($importer["uid"])
1427 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1429 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1430 intval($importer["uid"])
1433 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1435 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1438 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1439 $arr["uid"] = $importer["uid"];
1440 $arr["contact-id"] = $self[0]["id"];
1442 $arr["type"] = 'wall';
1443 $arr["gravity"] = 0;
1445 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1446 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1447 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1448 $arr["verb"] = ACTIVITY_FRIEND;
1449 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1451 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1452 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1453 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1454 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1456 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1457 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1458 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1459 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1460 $arr["object"] .= "</link></object>\n";
1461 $arr["last-child"] = 1;
1463 $arr["allow_cid"] = $user[0]["allow_cid"];
1464 $arr["allow_gid"] = $user[0]["allow_gid"];
1465 $arr["deny_cid"] = $user[0]["deny_cid"];
1466 $arr["deny_gid"] = $user[0]["deny_gid"];
1468 $i = item_store($arr);
1470 proc_run("php", "include/notifier.php", "activity", $i);
1477 private function receive_request($importer, $data) {
1478 $author = unxmlify($data->author);
1479 $recipient = unxmlify($data->recipient);
1481 if (!$author || !$recipient)
1484 $contact = self::contact_by_handle($importer["uid"],$author);
1488 // perhaps we were already sharing with this person. Now they're sharing with us.
1489 // That makes us friends.
1491 self::receive_request_make_friend($importer, $contact);
1495 $ret = self::person_by_handle($author);
1497 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1498 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1502 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1504 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1505 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1506 intval($importer["uid"]),
1507 dbesc($ret["network"]),
1508 dbesc($ret["addr"]),
1511 dbesc(normalise_link($ret["url"])),
1513 dbesc($ret["name"]),
1514 dbesc($ret["nick"]),
1515 dbesc($ret["photo"]),
1516 dbesc($ret["pubkey"]),
1517 dbesc($ret["notify"]),
1518 dbesc($ret["poll"]),
1523 // find the contact record we just created
1525 $contact_record = self::contact_by_handle($importer["uid"],$author);
1527 if (!$contact_record) {
1528 logger("unable to locate newly created contact record.");
1532 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1533 intval($importer["uid"])
1536 if($g && intval($g[0]["def_gid"]))
1537 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1539 if($importer["page-flags"] == PAGE_NORMAL) {
1541 $hash = random_string().(string)time(); // Generate a confirm_key
1543 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1544 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1545 intval($importer["uid"]),
1546 intval($contact_record["id"]),
1549 dbesc(t("Sharing notification from Diaspora network")),
1551 dbesc(datetime_convert())
1555 // automatic friend approval
1557 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1559 // technically they are sharing with us (CONTACT_IS_SHARING),
1560 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1561 // we are going to change the relationship and make them a follower.
1563 if($importer["page-flags"] == PAGE_FREELOVE)
1564 $new_relation = CONTACT_IS_FRIEND;
1566 $new_relation = CONTACT_IS_FOLLOWER;
1568 $r = q("UPDATE `contact` SET `rel` = %d,
1576 intval($new_relation),
1577 dbesc(datetime_convert()),
1578 dbesc(datetime_convert()),
1579 intval($contact_record["id"])
1582 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1584 $ret = self::send_share($u[0], $contact_record);
1590 private function original_item($guid, $orig_author, $author) {
1592 // Do we already have this item?
1593 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1594 `author-name`, `author-link`, `author-avatar`
1595 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1599 logger("reshared message ".$guid." already exists on system.");
1601 // Maybe it is already a reshared item?
1602 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1603 if (self::is_reshare($r[0]["body"], false))
1610 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1611 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1612 $item_id = self::store_by_guid($guid, $server);
1615 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1616 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1617 $item_id = self::store_by_guid($guid, $server);
1620 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1622 $server = "https://".substr($author, strpos($author, "@") + 1);
1623 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1624 $item_id = self::store_by_guid($guid, $server);
1627 $server = "http://".substr($author, strpos($author, "@") + 1);
1628 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1629 $item_id = self::store_by_guid($guid, $server);
1633 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1634 `author-name`, `author-link`, `author-avatar`
1635 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1646 private function receive_reshare($importer, $data, $xml) {
1647 $root_author = notags(unxmlify($data->root_author));
1648 $root_guid = notags(unxmlify($data->root_guid));
1649 $guid = notags(unxmlify($data->guid));
1650 $author = notags(unxmlify($data->author));
1651 $public = notags(unxmlify($data->public));
1652 $created_at = notags(unxmlify($data->created_at));
1654 $contact = self::allowed_contact_by_handle($importer, $author, false);
1658 if (self::message_exists($importer["uid"], $guid))
1661 $original_item = self::original_item($root_guid, $root_author, $author);
1662 if (!$original_item)
1665 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1667 $datarray = array();
1669 $datarray["uid"] = $importer["uid"];
1670 $datarray["contact-id"] = $contact["id"];
1671 $datarray["network"] = NETWORK_DIASPORA;
1673 $datarray["author-name"] = $contact["name"];
1674 $datarray["author-link"] = $contact["url"];
1675 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1677 $datarray["owner-name"] = $datarray["author-name"];
1678 $datarray["owner-link"] = $datarray["author-link"];
1679 $datarray["owner-avatar"] = $datarray["author-avatar"];
1681 $datarray["guid"] = $guid;
1682 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1684 $datarray["verb"] = ACTIVITY_POST;
1685 $datarray["gravity"] = GRAVITY_PARENT;
1687 $datarray["object"] = $xml;
1689 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1690 $original_item["guid"], $original_item["created"], $orig_url);
1691 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1693 $datarray["tag"] = $original_item["tag"];
1694 $datarray["app"] = $original_item["app"];
1696 $datarray["plink"] = self::plink($author, $guid);
1697 $datarray["private"] = (($public == "false") ? 1 : 0);
1698 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1700 $datarray["object-type"] = $original_item["object-type"];
1702 self::fetch_guid($datarray);
1703 $message_id = item_store($datarray);
1706 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1711 private function item_retraction($importer, $contact, $data) {
1712 $target_type = notags(unxmlify($data->target_type));
1713 $target_guid = notags(unxmlify($data->target_guid));
1714 $author = notags(unxmlify($data->author));
1716 $person = self::person_by_handle($author);
1717 if (!is_array($person)) {
1718 logger("unable to find author detail for ".$author);
1722 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1723 dbesc($target_guid),
1724 intval($importer["uid"])
1729 // Only delete it if the author really fits
1730 if (!link_compare($r[0]["author-link"], $person["url"])) {
1731 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
1735 // Check if the sender is the thread owner
1736 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
1737 intval($r[0]["parent"]));
1739 // Only delete it if the parent author really fits
1740 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
1741 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
1745 // 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
1746 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1747 dbesc(datetime_convert()),
1748 dbesc(datetime_convert()),
1751 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1753 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
1755 // Now check if the retraction needs to be relayed by us
1756 if($p[0]["origin"]) {
1758 // Formerly we stored the signed text, the signature and the author in different fields.
1759 // We now store the raw data so that we are more flexible.
1760 q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1761 intval($r[0]["id"]),
1762 dbesc(json_encode($data))
1764 $s = q("select * from sign where retract_iid = %d", intval($r[0]["id"]));
1765 logger("Stored signatur for item ".$r[0]["id"]." - ".print_r($s, true), LOGGER_DEBUG);
1768 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1772 private function receive_retraction($importer, $sender, $data) {
1773 $target_type = notags(unxmlify($data->target_type));
1775 $contact = self::contact_by_handle($importer["uid"], $sender);
1777 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1781 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
1783 switch ($target_type) {
1786 case "Post": // "Post" will be supported in a future version
1788 case "StatusMessage":
1789 return self::item_retraction($importer, $contact, $data);;
1792 /// @todo What should we do with an "unshare"?
1793 // Removing the contact isn't correct since we still can read the public items
1794 //contact_remove($contact["id"]);
1798 logger("Unknown target type ".$target_type);
1804 private function receive_status_message($importer, $data, $xml) {
1806 $raw_message = unxmlify($data->raw_message);
1807 $guid = notags(unxmlify($data->guid));
1808 $author = notags(unxmlify($data->author));
1809 $public = notags(unxmlify($data->public));
1810 $created_at = notags(unxmlify($data->created_at));
1811 $provider_display_name = notags(unxmlify($data->provider_display_name));
1813 /// @todo enable support for polls
1814 //if ($data->poll) {
1815 // foreach ($data->poll AS $poll)
1819 $contact = self::allowed_contact_by_handle($importer, $author, false);
1823 if (self::message_exists($importer["uid"], $guid))
1827 if ($data->location)
1828 foreach ($data->location->children() AS $fieldname => $data)
1829 $address[$fieldname] = notags(unxmlify($data));
1831 $body = diaspora2bb($raw_message);
1833 $datarray = array();
1836 foreach ($data->photo AS $photo)
1837 $body = "[img]".unxmlify($photo->remote_photo_path).
1838 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
1840 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1842 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1844 // Add OEmbed and other information to the body
1845 if (!self::is_redmatrix($contact["url"]))
1846 $body = add_page_info_to_body($body, false, true);
1849 $datarray["uid"] = $importer["uid"];
1850 $datarray["contact-id"] = $contact["id"];
1851 $datarray["network"] = NETWORK_DIASPORA;
1853 $datarray["author-name"] = $contact["name"];
1854 $datarray["author-link"] = $contact["url"];
1855 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1857 $datarray["owner-name"] = $datarray["author-name"];
1858 $datarray["owner-link"] = $datarray["author-link"];
1859 $datarray["owner-avatar"] = $datarray["author-avatar"];
1861 $datarray["guid"] = $guid;
1862 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1864 $datarray["verb"] = ACTIVITY_POST;
1865 $datarray["gravity"] = GRAVITY_PARENT;
1867 $datarray["object"] = $xml;
1869 $datarray["body"] = $body;
1871 if ($provider_display_name != "")
1872 $datarray["app"] = $provider_display_name;
1874 $datarray["plink"] = self::plink($author, $guid);
1875 $datarray["private"] = (($public == "false") ? 1 : 0);
1876 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1878 if (isset($address["address"]))
1879 $datarray["location"] = $address["address"];
1881 if (isset($address["lat"]) AND isset($address["lng"]))
1882 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1884 self::fetch_guid($datarray);
1885 $message_id = item_store($datarray);
1888 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1893 /******************************************************************************************
1894 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1895 ******************************************************************************************/
1897 private function my_handle($me) {
1898 if ($contact["addr"] != "")
1899 return $contact["addr"];
1901 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1902 // So - just in case - we build the the address here.
1903 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1906 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1908 logger("Message: ".$msg, LOGGER_DATA);
1910 $handle = self::my_handle($user);
1912 $b64url_data = base64url_encode($msg);
1914 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1916 $type = "application/xml";
1917 $encoding = "base64url";
1918 $alg = "RSA-SHA256";
1920 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1922 $signature = rsa_sign($signable_data,$prvkey);
1923 $sig = base64url_encode($signature);
1925 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1926 "me:env" => array("me:encoding" => "base64url",
1927 "me:alg" => "RSA-SHA256",
1929 "@attributes" => array("type" => "application/xml"),
1930 "me:sig" => $sig)));
1932 $namespaces = array("" => "https://joindiaspora.com/protocol",
1933 "me" => "http://salmon-protocol.org/ns/magic-env");
1935 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1937 logger("magic_env: ".$magic_env, LOGGER_DATA);
1941 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1943 logger("Message: ".$msg, LOGGER_DATA);
1945 // without a public key nothing will work
1948 logger("pubkey missing: contact id: ".$contact["id"]);
1952 $inner_aes_key = random_string(32);
1953 $b_inner_aes_key = base64_encode($inner_aes_key);
1954 $inner_iv = random_string(16);
1955 $b_inner_iv = base64_encode($inner_iv);
1957 $outer_aes_key = random_string(32);
1958 $b_outer_aes_key = base64_encode($outer_aes_key);
1959 $outer_iv = random_string(16);
1960 $b_outer_iv = base64_encode($outer_iv);
1962 $handle = self::my_handle($user);
1964 $padded_data = pkcs5_pad($msg,16);
1965 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1967 $b64_data = base64_encode($inner_encrypted);
1970 $b64url_data = base64url_encode($b64_data);
1971 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1973 $type = "application/xml";
1974 $encoding = "base64url";
1975 $alg = "RSA-SHA256";
1977 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1979 $signature = rsa_sign($signable_data,$prvkey);
1980 $sig = base64url_encode($signature);
1982 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1983 "aes_key" => $b_inner_aes_key,
1984 "author_id" => $handle));
1986 $decrypted_header = xml::from_array($xmldata, $xml, true);
1987 $decrypted_header = pkcs5_pad($decrypted_header,16);
1989 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1991 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1993 $encrypted_outer_key_bundle = "";
1994 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1996 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1998 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2000 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2001 "ciphertext" => base64_encode($ciphertext)));
2002 $cipher_json = base64_encode($encrypted_header_json_object);
2004 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2005 "me:env" => array("me:encoding" => "base64url",
2006 "me:alg" => "RSA-SHA256",
2008 "@attributes" => array("type" => "application/xml"),
2009 "me:sig" => $sig)));
2011 $namespaces = array("" => "https://joindiaspora.com/protocol",
2012 "me" => "http://salmon-protocol.org/ns/magic-env");
2014 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2016 logger("magic_env: ".$magic_env, LOGGER_DATA);
2020 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2023 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2025 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2027 // The data that will be transmitted is double encoded via "urlencode", strange ...
2028 $slap = "xml=".urlencode(urlencode($magic_env));
2032 private function signature($owner, $message) {
2034 unset($sigmsg["author_signature"]);
2035 unset($sigmsg["parent_author_signature"]);
2037 $signed_text = implode(";", $sigmsg);
2039 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2042 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2046 $enabled = intval(get_config("system", "diaspora_enabled"));
2050 $logid = random_string(4);
2051 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2053 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2057 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2059 if (!$queue_run && was_recently_delayed($contact["id"])) {
2062 if (!intval(get_config("system", "diaspora_test"))) {
2063 post_url($dest_url."/", $slap);
2064 $return_code = $a->get_curl_code();
2066 logger("test_mode");
2071 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2073 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2074 logger("queue message");
2076 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2077 intval($contact["id"]),
2078 dbesc(NETWORK_DIASPORA),
2080 intval($public_batch)
2083 logger("add_to_queue ignored - identical item already in queue");
2085 // queue message for redelivery
2086 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2090 return(($return_code) ? $return_code : (-1));
2094 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2096 $data = array("XML" => array("post" => array($type => $message)));
2098 $msg = xml::from_array($data, $xml);
2100 logger('message: '.$msg, LOGGER_DATA);
2101 logger('send guid '.$guid, LOGGER_DEBUG);
2103 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2106 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2109 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2111 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2113 return $return_code;
2116 public static function send_share($owner,$contact) {
2118 $message = array("sender_handle" => self::my_handle($owner),
2119 "recipient_handle" => $contact["addr"]);
2121 return self::build_and_transmit($owner, $contact, "request", $message);
2124 public static function send_unshare($owner,$contact) {
2126 $message = array("post_guid" => $owner["guid"],
2127 "diaspora_handle" => self::my_handle($owner),
2128 "type" => "Person");
2130 return self::build_and_transmit($owner, $contact, "retraction", $message);
2133 public static function is_reshare($body, $complete = true) {
2134 $body = trim($body);
2136 // Skip if it isn't a pure repeated messages
2137 // Does it start with a share?
2138 if (strpos($body, "[share") > 0)
2141 // Does it end with a share?
2142 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2145 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2146 // Skip if there is no shared message in there
2147 if ($body == $attributes)
2150 // If we don't do the complete check we quit here
2155 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2156 if ($matches[1] != "")
2157 $guid = $matches[1];
2159 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2160 if ($matches[1] != "")
2161 $guid = $matches[1];
2164 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2165 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2168 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2169 $ret["root_guid"] = $guid;
2175 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2176 if ($matches[1] != "")
2177 $profile = $matches[1];
2179 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2180 if ($matches[1] != "")
2181 $profile = $matches[1];
2185 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2186 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2190 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2191 if ($matches[1] != "")
2192 $link = $matches[1];
2194 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2195 if ($matches[1] != "")
2196 $link = $matches[1];
2198 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2199 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2204 public static function send_status($item, $owner, $contact, $public_batch = false) {
2206 $myaddr = self::my_handle($owner);
2208 $public = (($item["private"]) ? "false" : "true");
2210 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2212 // Detect a share element and do a reshare
2213 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2214 $message = array("root_diaspora_id" => $ret["root_handle"],
2215 "root_guid" => $ret["root_guid"],
2216 "guid" => $item["guid"],
2217 "diaspora_handle" => $myaddr,
2218 "public" => $public,
2219 "created_at" => $created,
2220 "provider_display_name" => $item["app"]);
2224 $title = $item["title"];
2225 $body = $item["body"];
2227 // convert to markdown
2228 $body = html_entity_decode(bb2diaspora($body));
2232 $body = "## ".html_entity_decode($title)."\n\n".$body;
2234 if ($item["attach"]) {
2235 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2237 $body .= "\n".t("Attachments:")."\n";
2238 foreach($matches as $mtch)
2239 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2243 $location = array();
2245 if ($item["location"] != "")
2246 $location["address"] = $item["location"];
2248 if ($item["coord"] != "") {
2249 $coord = explode(" ", $item["coord"]);
2250 $location["lat"] = $coord[0];
2251 $location["lng"] = $coord[1];
2254 $message = array("raw_message" => $body,
2255 "location" => $location,
2256 "guid" => $item["guid"],
2257 "diaspora_handle" => $myaddr,
2258 "public" => $public,
2259 "created_at" => $created,
2260 "provider_display_name" => $item["app"]);
2262 if (count($location) == 0)
2263 unset($message["location"]);
2265 $type = "status_message";
2268 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2271 private function construct_like($item, $owner) {
2273 $myaddr = self::my_handle($owner);
2275 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2276 dbesc($item["thr-parent"]));
2282 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2285 return(array("positive" => $positive,
2286 "guid" => $item["guid"],
2287 "target_type" => $target_type,
2288 "parent_guid" => $parent["guid"],
2289 "author_signature" => $authorsig,
2290 "diaspora_handle" => $myaddr));
2293 private function construct_comment($item, $owner) {
2295 $myaddr = self::my_handle($owner);
2297 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2298 intval($item["parent"]),
2299 intval($item["parent"])
2307 $text = html_entity_decode(bb2diaspora($item["body"]));
2309 return(array("guid" => $item["guid"],
2310 "parent_guid" => $parent["guid"],
2311 "author_signature" => "",
2313 "diaspora_handle" => $myaddr));
2316 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2318 if($item['verb'] === ACTIVITY_LIKE) {
2319 $message = self::construct_like($item, $owner);
2322 $message = self::construct_comment($item, $owner);
2329 $message["author_signature"] = self::signature($owner, $message);
2331 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2334 private function message_from_signatur($item, $signature) {
2336 // Split the signed text
2337 $signed_parts = explode(";", $signature['signed_text']);
2339 if ($item["deleted"])
2340 $message = array("parent_author_signature" => "",
2341 "target_guid" => $signed_parts[0],
2342 "target_type" => $signed_parts[1],
2343 "sender_handle" => $signature['signer'],
2344 "target_author_signature" => $signature['signature']);
2345 elseif ($item['verb'] === ACTIVITY_LIKE)
2346 $message = array("positive" => $signed_parts[0],
2347 "guid" => $signed_parts[1],
2348 "target_type" => $signed_parts[2],
2349 "parent_guid" => $signed_parts[3],
2350 "parent_author_signature" => "",
2351 "author_signature" => $signature['signature'],
2352 "diaspora_handle" => $signed_parts[4]);
2354 // Remove the comment guid
2355 $guid = array_shift($signed_parts);
2357 // Remove the parent guid
2358 $parent_guid = array_shift($signed_parts);
2360 // Remove the handle
2361 $handle = array_pop($signed_parts);
2363 // Glue the parts together
2364 $text = implode(";", $signed_parts);
2366 $message = array("guid" => $guid,
2367 "parent_guid" => $parent_guid,
2368 "parent_author_signature" => "",
2369 "author_signature" => $signature['signature'],
2370 "text" => implode(";", $signed_parts),
2371 "diaspora_handle" => $handle);
2376 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2378 if ($item["deleted"]) {
2379 $sql_sign_id = "retract_iid";
2380 $type = "relayable_retraction";
2381 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2382 $sql_sign_id = "iid";
2385 $sql_sign_id = "iid";
2389 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2391 // fetch the original signature
2393 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2394 intval($item["id"]));
2397 logger("Couldn't fetch signatur for contact ".$contact["addr"]." at item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2403 // Old way - is used by the internal Friendica functions
2404 /// @todo Change all signatur storing functions to the new format
2405 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2406 $message = self::message_from_signatur($item, $signature);
2408 $msg = json_decode($signature['signed_text'], true);
2411 if (is_array($msg)) {
2412 foreach ($msg AS $field => $data) {
2413 if (!$item["deleted"]) {
2414 if ($field == "author")
2415 $field = "diaspora_handle";
2416 if ($field == "parent_type")
2417 $field = "target_type";
2420 $message[$field] = $data;
2423 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2426 if ($item["deleted"]) {
2427 $signed_text = $message["target_guid"].';'.$message["target_type"];
2428 $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2430 $message["parent_author_signature"] = self::signature($owner, $message);
2432 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2434 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2437 public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2439 $myaddr = self::my_handle($owner);
2441 // Check whether the retraction is for a top-level post or whether it's a relayable
2442 if ($item["uri"] !== $item["parent-uri"]) {
2443 $msg_type = "relayable_retraction";
2444 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2446 $msg_type = "signed_retraction";
2447 $target_type = "StatusMessage";
2450 $signed_text = $item["guid"].";".$target_type;
2452 $message = array("target_guid" => $item['guid'],
2453 "target_type" => $target_type,
2454 "sender_handle" => $myaddr,
2455 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2457 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2460 public static function send_mail($item, $owner, $contact) {
2462 $myaddr = self::my_handle($owner);
2464 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2465 intval($item["convid"]),
2466 intval($item["uid"])
2470 logger("conversation not found.");
2476 "guid" => $cnv["guid"],
2477 "subject" => $cnv["subject"],
2478 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2479 "diaspora_handle" => $cnv["creator"],
2480 "participant_handles" => $cnv["recips"]
2483 $body = bb2diaspora($item["body"]);
2484 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2486 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2487 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2490 "guid" => $item["guid"],
2491 "parent_guid" => $cnv["guid"],
2492 "parent_author_signature" => $sig,
2493 "author_signature" => $sig,
2495 "created_at" => $created,
2496 "diaspora_handle" => $myaddr,
2497 "conversation_guid" => $cnv["guid"]
2500 if ($item["reply"]) {
2504 $message = array("guid" => $cnv["guid"],
2505 "subject" => $cnv["subject"],
2506 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2508 "diaspora_handle" => $cnv["creator"],
2509 "participant_handles" => $cnv["recips"]);
2511 $type = "conversation";
2514 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2517 public static function send_profile($uid) {
2522 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2523 AND `uid` = %d AND `rel` != %d",
2524 dbesc(NETWORK_DIASPORA),
2526 intval(CONTACT_IS_SHARING)
2531 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2533 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2534 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2535 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
2544 $handle = $profile["addr"];
2545 $first = ((strpos($profile['name'],' ')
2546 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
2547 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
2548 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
2549 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
2550 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
2551 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
2553 if ($searchable === 'true') {
2554 $dob = '1000-00-00';
2556 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
2557 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
2559 $about = $profile['about'];
2560 $about = strip_tags(bbcode($about));
2562 $location = formatted_location($profile);
2564 if ($profile['pub_keywords']) {
2565 $kw = str_replace(',',' ',$profile['pub_keywords']);
2566 $kw = str_replace(' ',' ',$kw);
2567 $arr = explode(' ',$profile['pub_keywords']);
2569 for($x = 0; $x < 5; $x ++) {
2571 $tags .= '#'. trim($arr[$x]) .' ';
2575 $tags = trim($tags);
2578 $message = array("diaspora_handle" => $handle,
2579 "first_name" => $first,
2580 "last_name" => $last,
2581 "image_url" => $large,
2582 "image_url_medium" => $medium,
2583 "image_url_small" => $small,
2585 "gender" => $profile['gender'],
2587 "location" => $location,
2588 "searchable" => $searchable,
2589 "tag_string" => $tags);
2591 foreach($recips as $recip)
2592 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);