3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
13 * - send status retraction
14 * - send comment retraction on own post
15 * - send like retraction on own post
16 * - send comment retraction on diaspora post
17 * - send like retraction on diaspora post
22 * - receive connect request
23 * - receive profile data
25 * - receive comment retraction
26 * - receive like retraction
29 * - relay comment retraction from diaspora
30 * - relay comment retraction from friendica
31 * - relay like retraction from diaspora
32 * - relay like retraction from friendica
36 * - receive account deletion
42 require_once("include/items.php");
43 require_once("include/bb2diaspora.php");
44 require_once("include/Scrape.php");
45 require_once("include/Contact.php");
46 require_once("include/Photo.php");
47 require_once("include/socgraph.php");
48 require_once("include/group.php");
49 require_once("include/xml.php");
50 require_once("include/datetime.php");
51 require_once("include/queue_fn.php");
54 * @brief This class contain functions to create and send Diaspora XML files
59 public static function relay_list() {
61 $serverdata = get_config("system", "relay_server");
62 if ($serverdata == "")
67 $servers = explode(",", $serverdata);
69 foreach($servers AS $server) {
70 $server = trim($server);
71 $batch = $server."/receive/public";
73 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
76 $addr = "relay@".str_replace("http://", "", normalise_link($server));
78 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
79 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
84 dbesc(normalise_link($server)),
86 dbesc(NETWORK_DIASPORA),
87 intval(CONTACT_IS_FOLLOWER),
88 dbesc(datetime_convert()),
89 dbesc(datetime_convert()),
90 dbesc(datetime_convert())
93 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
95 $relay[] = $relais[0];
97 $relay[] = $relais[0];
103 function repair_signature($signature, $handle = "", $level = 1) {
105 if ($signature == "")
108 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
109 $signature = base64_decode($signature);
110 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
112 // Do a recursive call to be able to fix even multiple levels
114 $signature = self::repair_signature($signature, $handle, ++$level);
121 * @brief: Decodes incoming Diaspora message
123 * @param array $importer from user table
124 * @param string $xml urldecoded Diaspora salmon
127 * 'message' -> decoded Diaspora XML message
128 * 'author' -> author diaspora handle
129 * 'key' -> author public key (converted to pkcs#8)
131 function decode($importer, $xml) {
134 $basedom = parse_xml_string($xml);
136 if (!is_object($basedom))
139 $children = $basedom->children('https://joindiaspora.com/protocol');
141 if($children->header) {
143 $author_link = str_replace('acct:','',$children->header->author_id);
146 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
148 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
149 $ciphertext = base64_decode($encrypted_header->ciphertext);
151 $outer_key_bundle = '';
152 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
154 $j_outer_key_bundle = json_decode($outer_key_bundle);
156 $outer_iv = base64_decode($j_outer_key_bundle->iv);
157 $outer_key = base64_decode($j_outer_key_bundle->key);
159 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
162 $decrypted = pkcs5_unpad($decrypted);
165 * $decrypted now contains something like
168 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
169 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
170 * <author_id>galaxor@diaspora.priateship.org</author_id>
171 * </decrypted_header>
174 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
175 $idom = parse_xml_string($decrypted,false);
177 $inner_iv = base64_decode($idom->iv);
178 $inner_aes_key = base64_decode($idom->aes_key);
180 $author_link = str_replace('acct:','',$idom->author_id);
183 $dom = $basedom->children(NAMESPACE_SALMON_ME);
185 // figure out where in the DOM tree our data is hiding
187 if($dom->provenance->data)
188 $base = $dom->provenance;
189 elseif($dom->env->data)
195 logger('unable to locate salmon data in xml');
196 http_status_exit(400);
200 // Stash the signature away for now. We have to find their key or it won't be good for anything.
201 $signature = base64url_decode($base->sig);
205 // strip whitespace so our data element will return to one big base64 blob
206 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
209 // stash away some other stuff for later
211 $type = $base->data[0]->attributes()->type[0];
212 $keyhash = $base->sig[0]->attributes()->keyhash[0];
213 $encoding = $base->encoding;
217 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
221 $data = base64url_decode($data);
225 $inner_decrypted = $data;
228 // Decode the encrypted blob
230 $inner_encrypted = base64_decode($data);
231 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
232 $inner_decrypted = pkcs5_unpad($inner_decrypted);
236 logger('Could not retrieve author URI.');
237 http_status_exit(400);
239 // Once we have the author URI, go to the web and try to find their public key
240 // (first this will look it up locally if it is in the fcontact cache)
241 // This will also convert diaspora public key from pkcs#1 to pkcs#8
243 logger('Fetching key for '.$author_link);
244 $key = self::key($author_link);
247 logger('Could not retrieve author key.');
248 http_status_exit(400);
251 $verify = rsa_verify($signed_data,$signature,$key);
254 logger('Message did not verify. Discarding.');
255 http_status_exit(400);
258 logger('Message verified.');
260 return array('message' => (string)$inner_decrypted,
261 'author' => unxmlify($author_link),
262 'key' => (string)$key);
268 * @brief Dispatches public messages and find the fitting receivers
270 * @param array $msg The post that will be dispatched
272 * @return bool Was the message accepted?
274 public static function dispatch_public($msg) {
276 $enabled = intval(get_config("system", "diaspora_enabled"));
278 logger("diaspora is disabled");
282 // Use a dummy importer to import the data for the public copy
283 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
284 $item_id = self::dispatch($importer,$msg);
286 // Now distribute it to the followers
287 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
288 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
289 AND NOT `account_expired` AND NOT `account_removed`",
290 dbesc(NETWORK_DIASPORA),
291 dbesc($msg["author"])
295 logger("delivering to: ".$rr["username"]);
296 self::dispatch($rr,$msg);
299 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
305 * @brief Dispatches the different message types to the different functions
307 * @param array $importer Array of the importer user
308 * @param array $msg The post that will be dispatched
310 * @return bool Was the message accepted?
312 public static function dispatch($importer, $msg) {
314 // The sender is the handle of the contact that sent the message.
315 // This will often be different with relayed messages (for example "like" and "comment")
316 $sender = $msg["author"];
318 if (!diaspora::valid_posting($msg, $fields)) {
319 logger("Invalid posting");
323 $type = $fields->getName();
325 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
328 case "account_deletion":
329 return self::receive_account_deletion($importer, $fields);
332 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
335 return self::receive_conversation($importer, $msg, $fields);
338 return self::receive_like($importer, $sender, $fields);
341 return self::receive_message($importer, $fields);
343 case "participation": // Not implemented
344 return self::receive_participation($importer, $fields);
346 case "photo": // Not implemented
347 return self::receive_photo($importer, $fields);
349 case "poll_participation": // Not implemented
350 return self::receive_poll_participation($importer, $fields);
353 return self::receive_profile($importer, $fields);
356 return self::receive_request($importer, $fields);
359 return self::receive_reshare($importer, $fields, $msg["message"]);
362 return self::receive_retraction($importer, $sender, $fields);
364 case "status_message":
365 return self::receive_status_message($importer, $fields, $msg["message"]);
368 logger("Unknown message type ".$type);
376 * @brief Checks if a posting is valid and fetches the data fields.
378 * This function does not only check the signature.
379 * It also does the conversion between the old and the new diaspora format.
381 * @param array $msg Array with the XML, the sender handle and the sender signature
382 * @param object $fields SimpleXML object that contains the posting when it is valid
384 * @return bool Is the posting valid?
386 private function valid_posting($msg, &$fields) {
388 $data = parse_xml_string($msg["message"], false);
390 if (!is_object($data))
393 $first_child = $data->getName();
395 // Is this the new or the old version?
396 if ($data->getName() == "XML") {
398 foreach ($data->post->children() as $child)
405 $type = $element->getName();
408 // All retractions are handled identically from now on.
409 // In the new version there will only be "retraction".
410 if (in_array($type, array("signed_retraction", "relayable_retraction")))
411 $type = "retraction";
413 $fields = new SimpleXMLElement("<".$type."/>");
417 foreach ($element->children() AS $fieldname => $entry) {
419 // Translation for the old XML structure
420 if ($fieldname == "diaspora_handle")
421 $fieldname = "author";
423 if ($fieldname == "participant_handles")
424 $fieldname = "participants";
426 if (in_array($type, array("like", "participation"))) {
427 if ($fieldname == "target_type")
428 $fieldname = "parent_type";
431 if ($fieldname == "sender_handle")
432 $fieldname = "author";
434 if ($fieldname == "recipient_handle")
435 $fieldname = "recipient";
437 if ($fieldname == "root_diaspora_id")
438 $fieldname = "root_author";
440 if ($type == "retraction") {
441 if ($fieldname == "post_guid")
442 $fieldname = "target_guid";
444 if ($fieldname == "type")
445 $fieldname = "target_type";
449 if ($fieldname == "author_signature")
450 $author_signature = base64_decode($entry);
451 elseif ($fieldname == "parent_author_signature")
452 $parent_author_signature = base64_decode($entry);
453 elseif ($fieldname != "target_author_signature") {
454 if ($signed_data != "") {
456 $signed_data_parent .= ";";
459 $signed_data .= $entry;
461 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
462 ($orig_type == "relayable_retraction"))
463 xml::copy($entry, $fields, $fieldname);
466 // This is something that shouldn't happen at all.
467 if (in_array($type, array("status_message", "reshare", "profile")))
468 if ($msg["author"] != $fields->author) {
469 logger("Message handle is not the same as envelope sender. Quitting this message.");
473 // Only some message types have signatures. So we quit here for the other types.
474 if (!in_array($type, array("comment", "message", "like")))
477 // No author_signature? This is a must, so we quit.
478 if (!isset($author_signature))
481 if (isset($parent_author_signature)) {
482 $key = self::key($msg["author"]);
484 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
488 $key = self::key($fields->author);
490 return rsa_verify($signed_data, $author_signature, $key, "sha256");
494 * @brief Fetches the public key for a given handle
496 * @param string $handle The handle
498 * @return string The public key
500 private function key($handle) {
501 $handle = strval($handle);
503 logger("Fetching diaspora key for: ".$handle);
505 $r = self::person_by_handle($handle);
513 * @brief Fetches data for a given handle
515 * @param string $handle The handle
517 * @return array the queried data
519 private function person_by_handle($handle) {
521 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
522 dbesc(NETWORK_DIASPORA),
527 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
529 // update record occasionally so it doesn't get stale
530 $d = strtotime($person["updated"]." +00:00");
531 if ($d < strtotime("now - 14 days"))
535 if (!$person OR $update) {
536 logger("create or refresh", LOGGER_DEBUG);
537 $r = probe_url($handle, PROBE_DIASPORA);
539 // Note that Friendica contacts will return a "Diaspora person"
540 // if Diaspora connectivity is enabled on their server
541 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
542 self::add_fcontact($r, $update);
550 * @brief Updates the fcontact table
552 * @param array $arr The fcontact data
553 * @param bool $update Update or insert?
555 * @return string The id of the fcontact entry
557 private function add_fcontact($arr, $update = false) {
560 $r = q("UPDATE `fcontact` SET
573 WHERE `url` = '%s' AND `network` = '%s'",
575 dbesc($arr["photo"]),
576 dbesc($arr["request"]),
579 dbesc($arr["batch"]),
580 dbesc($arr["notify"]),
582 dbesc($arr["confirm"]),
583 dbesc($arr["alias"]),
584 dbesc($arr["pubkey"]),
585 dbesc(datetime_convert()),
587 dbesc($arr["network"])
590 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
591 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
592 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
595 dbesc($arr["photo"]),
596 dbesc($arr["request"]),
599 dbesc($arr["batch"]),
600 dbesc($arr["notify"]),
602 dbesc($arr["confirm"]),
603 dbesc($arr["network"]),
604 dbesc($arr["alias"]),
605 dbesc($arr["pubkey"]),
606 dbesc(datetime_convert())
613 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
616 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
618 if ($gcontact_id != 0) {
619 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
620 intval($gcontact_id));
622 return $r[0]["addr"];
625 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
626 intval($contact_id));
630 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
632 if($contact['addr'] != "")
633 $handle = $contact['addr'];
634 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
635 $baseurl_start = strpos($contact['url'],'://') + 3;
636 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
637 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
638 $handle = $contact['nick'].'@'.$baseurl;
645 private function contact_by_handle($uid, $handle) {
646 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
654 $handle_parts = explode("@", $handle);
655 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
656 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
667 private function post_allow($importer, $contact, $is_comment = false) {
669 // perhaps we were already sharing with this person. Now they're sharing with us.
670 // That makes us friends.
671 // Normally this should have handled by getting a request - but this could get lost
672 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
673 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
674 intval(CONTACT_IS_FRIEND),
675 intval($contact["id"]),
676 intval($importer["uid"])
678 $contact["rel"] = CONTACT_IS_FRIEND;
679 logger("defining user ".$contact["nick"]." as friend");
682 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
684 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
686 if($contact["rel"] == CONTACT_IS_FOLLOWER)
687 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
690 // Messages for the global users are always accepted
691 if ($importer["uid"] == 0)
697 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
698 $contact = self::contact_by_handle($importer["uid"], $handle);
700 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
704 if (!self::post_allow($importer, $contact, $is_comment)) {
705 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
711 private function message_exists($uid, $guid) {
712 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
718 logger("message ".$guid." already exists for user ".$uid);
725 private function fetch_guid($item) {
726 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
727 function ($match) use ($item){
728 return(self::fetch_guid_sub($match, $item));
732 private function fetch_guid_sub($match, $item) {
733 if (!self::store_by_guid($match[1], $item["author-link"]))
734 self::store_by_guid($match[1], $item["owner-link"]);
737 private function store_by_guid($guid, $server, $uid = 0) {
738 $serverparts = parse_url($server);
739 $server = $serverparts["scheme"]."://".$serverparts["host"];
741 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
743 $msg = self::message($guid, $server);
748 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
750 // Now call the dispatcher
751 return self::dispatch_public($msg);
754 private function message($guid, $server, $level = 0) {
759 // This will work for Diaspora and newer Friendica servers
760 $source_url = $server."/p/".$guid.".xml";
761 $x = fetch_url($source_url);
765 $source_xml = parse_xml_string($x, false);
767 if (!is_object($source_xml))
770 if ($source_xml->post->reshare) {
771 // Reshare of a reshare - old Diaspora version
772 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
773 } elseif ($source_xml->getName() == "reshare") {
774 // Reshare of a reshare - new Diaspora version
775 return self::message($source_xml->root_guid, $server, ++$level);
780 // Fetch the author - for the old and the new Diaspora version
781 if ($source_xml->post->status_message->diaspora_handle)
782 $author = (string)$source_xml->post->status_message->diaspora_handle;
783 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
784 $author = (string)$source_xml->author;
786 // If this isn't a "status_message" then quit
790 $msg = array("message" => $x, "author" => $author);
792 $msg["key"] = self::key($msg["author"]);
797 private function parent_item($uid, $guid, $author, $contact) {
798 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
799 `author-name`, `author-link`, `author-avatar`,
800 `owner-name`, `owner-link`, `owner-avatar`
801 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
802 intval($uid), dbesc($guid));
805 $result = self::store_by_guid($guid, $contact["url"], $uid);
808 $person = self::person_by_handle($author);
809 $result = self::store_by_guid($guid, $person["url"], $uid);
813 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
815 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
816 `author-name`, `author-link`, `author-avatar`,
817 `owner-name`, `owner-link`, `owner-avatar`
818 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
819 intval($uid), dbesc($guid));
824 logger("parent item not found: parent: ".$guid." - user: ".$uid);
827 logger("parent item found: parent: ".$guid." - user: ".$uid);
832 private function author_contact_by_url($contact, $person, $uid) {
834 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
835 dbesc(normalise_link($person["url"])), intval($uid));
838 $network = $r[0]["network"];
840 $cid = $contact["id"];
841 $network = NETWORK_DIASPORA;
844 return (array("cid" => $cid, "network" => $network));
847 public static function is_redmatrix($url) {
848 return(strstr($url, "/channel/"));
851 private function plink($addr, $guid) {
852 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
856 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
858 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
859 // So we try another way as well.
860 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
862 $r[0]["network"] = $s[0]["network"];
864 if ($r[0]["network"] == NETWORK_DFRN)
865 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
867 if (self::is_redmatrix($r[0]["url"]))
868 return $r[0]["url"]."/?f=&mid=".$guid;
870 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
873 private function receive_account_deletion($importer, $data) {
874 $author = notags(unxmlify($data->author));
876 $contact = self::contact_by_handle($importer["uid"], $author);
878 logger("cannot find contact for author: ".$author);
882 // We now remove the contact
883 contact_remove($contact["id"]);
887 private function receive_comment($importer, $sender, $data, $xml) {
888 $guid = notags(unxmlify($data->guid));
889 $parent_guid = notags(unxmlify($data->parent_guid));
890 $text = unxmlify($data->text);
891 $author = notags(unxmlify($data->author));
893 $contact = self::allowed_contact_by_handle($importer, $sender, true);
897 if (self::message_exists($importer["uid"], $guid))
900 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
904 $person = self::person_by_handle($author);
905 if (!is_array($person)) {
906 logger("unable to find author details");
910 // Fetch the contact id - if we know this contact
911 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
915 $datarray["uid"] = $importer["uid"];
916 $datarray["contact-id"] = $author_contact["cid"];
917 $datarray["network"] = $author_contact["network"];
919 $datarray["author-name"] = $person["name"];
920 $datarray["author-link"] = $person["url"];
921 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
923 $datarray["owner-name"] = $contact["name"];
924 $datarray["owner-link"] = $contact["url"];
925 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
927 $datarray["guid"] = $guid;
928 $datarray["uri"] = $author.":".$guid;
930 $datarray["type"] = "remote-comment";
931 $datarray["verb"] = ACTIVITY_POST;
932 $datarray["gravity"] = GRAVITY_COMMENT;
933 $datarray["parent-uri"] = $parent_item["uri"];
935 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
936 $datarray["object"] = $xml;
938 $datarray["body"] = diaspora2bb($text);
940 self::fetch_guid($datarray);
942 $message_id = item_store($datarray);
945 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
947 // If we are the origin of the parent we store the original data and notify our followers
948 if($message_id AND $parent_item["origin"]) {
950 // Formerly we stored the signed text, the signature and the author in different fields.
951 // We now store the raw data so that we are more flexible.
952 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
954 dbesc(json_encode($data))
958 proc_run("php", "include/notifier.php", "comment-import", $message_id);
964 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
965 $guid = notags(unxmlify($data->guid));
966 $subject = notags(unxmlify($data->subject));
967 $author = notags(unxmlify($data->author));
971 $msg_guid = notags(unxmlify($mesg->guid));
972 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
973 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
974 $msg_author_signature = notags(unxmlify($mesg->author_signature));
975 $msg_text = unxmlify($mesg->text);
976 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
978 // "diaspora_handle" is the element name from the old version
979 // "author" is the element name from the new version
981 $msg_author = notags(unxmlify($mesg->author));
982 elseif ($mesg->diaspora_handle)
983 $msg_author = notags(unxmlify($mesg->diaspora_handle));
987 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
989 if($msg_conversation_guid != $guid) {
990 logger("message conversation guid does not belong to the current conversation.");
994 $body = diaspora2bb($msg_text);
995 $message_uri = $msg_author.":".$msg_guid;
997 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
999 $author_signature = base64_decode($msg_author_signature);
1001 if(strcasecmp($msg_author,$msg["author"]) == 0) {
1005 $person = self::person_by_handle($msg_author);
1007 if (is_array($person) && x($person, "pubkey"))
1008 $key = $person["pubkey"];
1010 logger("unable to find author details");
1015 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1016 logger("verification failed.");
1020 if($msg_parent_author_signature) {
1021 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1023 $parent_author_signature = base64_decode($msg_parent_author_signature);
1027 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1028 logger("owner verification failed.");
1033 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1037 logger("duplicate message already delivered.", LOGGER_DEBUG);
1041 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1042 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1043 intval($importer["uid"]),
1045 intval($conversation["id"]),
1046 dbesc($person["name"]),
1047 dbesc($person["photo"]),
1048 dbesc($person["url"]),
1049 intval($contact["id"]),
1054 dbesc($message_uri),
1055 dbesc($author.":".$guid),
1056 dbesc($msg_created_at)
1059 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1060 dbesc(datetime_convert()),
1061 intval($conversation["id"])
1065 "type" => NOTIFY_MAIL,
1066 "notify_flags" => $importer["notify-flags"],
1067 "language" => $importer["language"],
1068 "to_name" => $importer["username"],
1069 "to_email" => $importer["email"],
1070 "uid" =>$importer["uid"],
1071 "item" => array("subject" => $subject, "body" => $body),
1072 "source_name" => $person["name"],
1073 "source_link" => $person["url"],
1074 "source_photo" => $person["thumb"],
1075 "verb" => ACTIVITY_POST,
1080 private function receive_conversation($importer, $msg, $data) {
1081 $guid = notags(unxmlify($data->guid));
1082 $subject = notags(unxmlify($data->subject));
1083 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1084 $author = notags(unxmlify($data->author));
1085 $participants = notags(unxmlify($data->participants));
1087 $messages = $data->message;
1089 if (!count($messages)) {
1090 logger("empty conversation");
1094 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1098 $conversation = null;
1100 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1101 intval($importer["uid"]),
1105 $conversation = $c[0];
1107 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1108 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1109 intval($importer["uid"]),
1112 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1113 dbesc(datetime_convert()),
1115 dbesc($participants)
1118 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1119 intval($importer["uid"]),
1124 $conversation = $c[0];
1126 if (!$conversation) {
1127 logger("unable to create conversation.");
1131 foreach($messages as $mesg)
1132 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1137 private function construct_like_body($contact, $parent_item, $guid) {
1138 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1140 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1141 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1142 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1144 return sprintf($bodyverb, $ulink, $alink, $plink);
1147 private function construct_like_object($importer, $parent_item) {
1148 $objtype = ACTIVITY_OBJ_NOTE;
1149 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1150 $parent_body = $parent_item["body"];
1152 $xmldata = array("object" => array("type" => $objtype,
1154 "id" => $parent_item["uri"],
1157 "content" => $parent_body));
1159 return xml::from_array($xmldata, $xml, true);
1162 private function receive_like($importer, $sender, $data) {
1163 $positive = notags(unxmlify($data->positive));
1164 $guid = notags(unxmlify($data->guid));
1165 $parent_type = notags(unxmlify($data->parent_type));
1166 $parent_guid = notags(unxmlify($data->parent_guid));
1167 $author = notags(unxmlify($data->author));
1169 // likes on comments aren't supported by Diaspora - only on posts
1170 // But maybe this will be supported in the future, so we will accept it.
1171 if (!in_array($parent_type, array("Post", "Comment")))
1174 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1178 if (self::message_exists($importer["uid"], $guid))
1181 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1185 $person = self::person_by_handle($author);
1186 if (!is_array($person)) {
1187 logger("unable to find author details");
1191 // Fetch the contact id - if we know this contact
1192 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1194 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1195 // We would accept this anyhow.
1196 if ($positive === "true")
1197 $verb = ACTIVITY_LIKE;
1199 $verb = ACTIVITY_DISLIKE;
1201 $datarray = array();
1203 $datarray["uid"] = $importer["uid"];
1204 $datarray["contact-id"] = $author_contact["cid"];
1205 $datarray["network"] = $author_contact["network"];
1207 $datarray["author-name"] = $person["name"];
1208 $datarray["author-link"] = $person["url"];
1209 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1211 $datarray["owner-name"] = $contact["name"];
1212 $datarray["owner-link"] = $contact["url"];
1213 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1215 $datarray["guid"] = $guid;
1216 $datarray["uri"] = $author.":".$guid;
1218 $datarray["type"] = "activity";
1219 $datarray["verb"] = $verb;
1220 $datarray["gravity"] = GRAVITY_LIKE;
1221 $datarray["parent-uri"] = $parent_item["uri"];
1223 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1224 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1226 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1228 $message_id = item_store($datarray);
1231 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1233 // If we are the origin of the parent we store the original data and notify our followers
1234 if($message_id AND $parent_item["origin"]) {
1236 // Formerly we stored the signed text, the signature and the author in different fields.
1237 // We now store the raw data so that we are more flexible.
1238 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1239 intval($message_id),
1240 dbesc(json_encode($data))
1244 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1250 private function receive_message($importer, $data) {
1251 $guid = notags(unxmlify($data->guid));
1252 $parent_guid = notags(unxmlify($data->parent_guid));
1253 $text = unxmlify($data->text);
1254 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1255 $author = notags(unxmlify($data->author));
1256 $conversation_guid = notags(unxmlify($data->conversation_guid));
1258 $contact = self::allowed_contact_by_handle($importer, $author, true);
1262 $conversation = null;
1264 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1265 intval($importer["uid"]),
1266 dbesc($conversation_guid)
1269 $conversation = $c[0];
1271 logger("conversation not available.");
1277 $body = diaspora2bb($text);
1278 $message_uri = $author.":".$guid;
1280 $person = self::person_by_handle($author);
1282 logger("unable to find author details");
1286 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1287 dbesc($message_uri),
1288 intval($importer["uid"])
1291 logger("duplicate message already delivered.", LOGGER_DEBUG);
1295 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1296 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1297 intval($importer["uid"]),
1299 intval($conversation["id"]),
1300 dbesc($person["name"]),
1301 dbesc($person["photo"]),
1302 dbesc($person["url"]),
1303 intval($contact["id"]),
1304 dbesc($conversation["subject"]),
1308 dbesc($message_uri),
1309 dbesc($author.":".$parent_guid),
1313 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1314 dbesc(datetime_convert()),
1315 intval($conversation["id"])
1321 private function receive_participation($importer, $data) {
1322 // I'm not sure if we can fully support this message type
1326 private function receive_photo($importer, $data) {
1327 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1331 private function receive_poll_participation($importer, $data) {
1332 // We don't support polls by now
1336 private function receive_profile($importer, $data) {
1337 $author = notags(unxmlify($data->author));
1339 $contact = self::contact_by_handle($importer["uid"], $author);
1343 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1344 $image_url = unxmlify($data->image_url);
1345 $birthday = unxmlify($data->birthday);
1346 $location = diaspora2bb(unxmlify($data->location));
1347 $about = diaspora2bb(unxmlify($data->bio));
1348 $gender = unxmlify($data->gender);
1349 $searchable = (unxmlify($data->searchable) == "true");
1350 $nsfw = (unxmlify($data->nsfw) == "true");
1351 $tags = unxmlify($data->tag_string);
1353 $tags = explode("#", $tags);
1355 $keywords = array();
1356 foreach ($tags as $tag) {
1357 $tag = trim(strtolower($tag));
1362 $keywords = implode(", ", $keywords);
1364 $handle_parts = explode("@", $author);
1365 $nick = $handle_parts[0];
1368 $name = $handle_parts[0];
1370 if( preg_match("|^https?://|", $image_url) === 0)
1371 $image_url = "http://".$handle_parts[1].$image_url;
1373 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1375 // Generic birthday. We don't know the timezone. The year is irrelevant.
1377 $birthday = str_replace("1000", "1901", $birthday);
1379 if ($birthday != "")
1380 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1382 // this is to prevent multiple birthday notifications in a single year
1383 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1385 if(substr($birthday,5) === substr($contact["bd"],5))
1386 $birthday = $contact["bd"];
1388 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1389 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1393 dbesc(datetime_convert()),
1399 intval($contact["id"]),
1400 intval($importer["uid"])
1404 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1405 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1408 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1409 "photo" => $image_url, "name" => $name, "location" => $location,
1410 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1411 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1412 "hide" => !$searchable, "nsfw" => $nsfw);
1414 update_gcontact($gcontact);
1416 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1421 private function receive_request_make_friend($importer, $contact) {
1425 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1426 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1427 intval(CONTACT_IS_FRIEND),
1428 intval($contact["id"]),
1429 intval($importer["uid"])
1432 // send notification
1434 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1435 intval($importer["uid"])
1438 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1440 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1441 intval($importer["uid"])
1444 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1446 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1449 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1450 $arr["uid"] = $importer["uid"];
1451 $arr["contact-id"] = $self[0]["id"];
1453 $arr["type"] = 'wall';
1454 $arr["gravity"] = 0;
1456 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1457 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1458 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1459 $arr["verb"] = ACTIVITY_FRIEND;
1460 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1462 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1463 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1464 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1465 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1467 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1468 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1469 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1470 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1471 $arr["object"] .= "</link></object>\n";
1472 $arr["last-child"] = 1;
1474 $arr["allow_cid"] = $user[0]["allow_cid"];
1475 $arr["allow_gid"] = $user[0]["allow_gid"];
1476 $arr["deny_cid"] = $user[0]["deny_cid"];
1477 $arr["deny_gid"] = $user[0]["deny_gid"];
1479 $i = item_store($arr);
1481 proc_run("php", "include/notifier.php", "activity", $i);
1488 private function receive_request($importer, $data) {
1489 $author = unxmlify($data->author);
1490 $recipient = unxmlify($data->recipient);
1492 if (!$author || !$recipient)
1495 $contact = self::contact_by_handle($importer["uid"],$author);
1499 // perhaps we were already sharing with this person. Now they're sharing with us.
1500 // That makes us friends.
1502 self::receive_request_make_friend($importer, $contact);
1506 $ret = self::person_by_handle($author);
1508 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1509 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1513 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1515 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1516 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1517 intval($importer["uid"]),
1518 dbesc($ret["network"]),
1519 dbesc($ret["addr"]),
1522 dbesc(normalise_link($ret["url"])),
1524 dbesc($ret["name"]),
1525 dbesc($ret["nick"]),
1526 dbesc($ret["photo"]),
1527 dbesc($ret["pubkey"]),
1528 dbesc($ret["notify"]),
1529 dbesc($ret["poll"]),
1534 // find the contact record we just created
1536 $contact_record = self::contact_by_handle($importer["uid"],$author);
1538 if (!$contact_record) {
1539 logger("unable to locate newly created contact record.");
1543 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1544 intval($importer["uid"])
1547 if($g && intval($g[0]["def_gid"]))
1548 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1550 if($importer["page-flags"] == PAGE_NORMAL) {
1552 $hash = random_string().(string)time(); // Generate a confirm_key
1554 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1555 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1556 intval($importer["uid"]),
1557 intval($contact_record["id"]),
1560 dbesc(t("Sharing notification from Diaspora network")),
1562 dbesc(datetime_convert())
1566 // automatic friend approval
1568 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1570 // technically they are sharing with us (CONTACT_IS_SHARING),
1571 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1572 // we are going to change the relationship and make them a follower.
1574 if($importer["page-flags"] == PAGE_FREELOVE)
1575 $new_relation = CONTACT_IS_FRIEND;
1577 $new_relation = CONTACT_IS_FOLLOWER;
1579 $r = q("UPDATE `contact` SET `rel` = %d,
1587 intval($new_relation),
1588 dbesc(datetime_convert()),
1589 dbesc(datetime_convert()),
1590 intval($contact_record["id"])
1593 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1595 $ret = self::send_share($u[0], $contact_record);
1601 private function original_item($guid, $orig_author, $author) {
1603 // Do we already have this item?
1604 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1605 `author-name`, `author-link`, `author-avatar`
1606 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1610 logger("reshared message ".$guid." already exists on system.");
1612 // Maybe it is already a reshared item?
1613 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1614 if (self::is_reshare($r[0]["body"], false))
1621 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1622 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1623 $item_id = self::store_by_guid($guid, $server);
1626 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1627 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1628 $item_id = self::store_by_guid($guid, $server);
1631 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1633 $server = "https://".substr($author, strpos($author, "@") + 1);
1634 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1635 $item_id = self::store_by_guid($guid, $server);
1638 $server = "http://".substr($author, strpos($author, "@") + 1);
1639 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1640 $item_id = self::store_by_guid($guid, $server);
1644 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1645 `author-name`, `author-link`, `author-avatar`
1646 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1657 private function receive_reshare($importer, $data, $xml) {
1658 $root_author = notags(unxmlify($data->root_author));
1659 $root_guid = notags(unxmlify($data->root_guid));
1660 $guid = notags(unxmlify($data->guid));
1661 $author = notags(unxmlify($data->author));
1662 $public = notags(unxmlify($data->public));
1663 $created_at = notags(unxmlify($data->created_at));
1665 $contact = self::allowed_contact_by_handle($importer, $author, false);
1669 if (self::message_exists($importer["uid"], $guid))
1672 $original_item = self::original_item($root_guid, $root_author, $author);
1673 if (!$original_item)
1676 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1678 $datarray = array();
1680 $datarray["uid"] = $importer["uid"];
1681 $datarray["contact-id"] = $contact["id"];
1682 $datarray["network"] = NETWORK_DIASPORA;
1684 $datarray["author-name"] = $contact["name"];
1685 $datarray["author-link"] = $contact["url"];
1686 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1688 $datarray["owner-name"] = $datarray["author-name"];
1689 $datarray["owner-link"] = $datarray["author-link"];
1690 $datarray["owner-avatar"] = $datarray["author-avatar"];
1692 $datarray["guid"] = $guid;
1693 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1695 $datarray["verb"] = ACTIVITY_POST;
1696 $datarray["gravity"] = GRAVITY_PARENT;
1698 $datarray["object"] = $xml;
1700 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1701 $original_item["guid"], $original_item["created"], $orig_url);
1702 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1704 $datarray["tag"] = $original_item["tag"];
1705 $datarray["app"] = $original_item["app"];
1707 $datarray["plink"] = self::plink($author, $guid);
1708 $datarray["private"] = (($public == "false") ? 1 : 0);
1709 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1711 $datarray["object-type"] = $original_item["object-type"];
1713 self::fetch_guid($datarray);
1714 $message_id = item_store($datarray);
1717 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1722 private function item_retraction($importer, $contact, $data) {
1723 $target_type = notags(unxmlify($data->target_type));
1724 $target_guid = notags(unxmlify($data->target_guid));
1725 $author = notags(unxmlify($data->author));
1727 $person = self::person_by_handle($author);
1728 if (!is_array($person)) {
1729 logger("unable to find author detail for ".$author);
1733 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1734 dbesc($target_guid),
1735 intval($importer["uid"])
1740 // Only delete it if the author really fits
1741 if (!link_compare($r[0]["author-link"], $person["url"])) {
1742 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
1746 // Check if the sender is the thread owner
1747 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
1748 intval($r[0]["parent"]));
1750 // Only delete it if the parent author really fits
1751 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
1752 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
1756 // 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
1757 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1758 dbesc(datetime_convert()),
1759 dbesc(datetime_convert()),
1762 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1764 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
1766 // Now check if the retraction needs to be relayed by us
1767 if($p[0]["origin"]) {
1769 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1773 private function receive_retraction($importer, $sender, $data) {
1774 $target_type = notags(unxmlify($data->target_type));
1776 $contact = self::contact_by_handle($importer["uid"], $sender);
1778 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1782 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
1784 switch ($target_type) {
1787 case "Post": // "Post" will be supported in a future version
1789 case "StatusMessage":
1790 return self::item_retraction($importer, $contact, $data);;
1793 /// @todo What should we do with an "unshare"?
1794 // Removing the contact isn't correct since we still can read the public items
1795 //contact_remove($contact["id"]);
1799 logger("Unknown target type ".$target_type);
1805 private function receive_status_message($importer, $data, $xml) {
1807 $raw_message = unxmlify($data->raw_message);
1808 $guid = notags(unxmlify($data->guid));
1809 $author = notags(unxmlify($data->author));
1810 $public = notags(unxmlify($data->public));
1811 $created_at = notags(unxmlify($data->created_at));
1812 $provider_display_name = notags(unxmlify($data->provider_display_name));
1814 /// @todo enable support for polls
1815 //if ($data->poll) {
1816 // foreach ($data->poll AS $poll)
1820 $contact = self::allowed_contact_by_handle($importer, $author, false);
1824 if (self::message_exists($importer["uid"], $guid))
1828 if ($data->location)
1829 foreach ($data->location->children() AS $fieldname => $data)
1830 $address[$fieldname] = notags(unxmlify($data));
1832 $body = diaspora2bb($raw_message);
1834 $datarray = array();
1837 foreach ($data->photo AS $photo)
1838 $body = "[img]".unxmlify($photo->remote_photo_path).
1839 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
1841 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1843 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1845 // Add OEmbed and other information to the body
1846 if (!self::is_redmatrix($contact["url"]))
1847 $body = add_page_info_to_body($body, false, true);
1850 $datarray["uid"] = $importer["uid"];
1851 $datarray["contact-id"] = $contact["id"];
1852 $datarray["network"] = NETWORK_DIASPORA;
1854 $datarray["author-name"] = $contact["name"];
1855 $datarray["author-link"] = $contact["url"];
1856 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1858 $datarray["owner-name"] = $datarray["author-name"];
1859 $datarray["owner-link"] = $datarray["author-link"];
1860 $datarray["owner-avatar"] = $datarray["author-avatar"];
1862 $datarray["guid"] = $guid;
1863 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1865 $datarray["verb"] = ACTIVITY_POST;
1866 $datarray["gravity"] = GRAVITY_PARENT;
1868 $datarray["object"] = $xml;
1870 $datarray["body"] = $body;
1872 if ($provider_display_name != "")
1873 $datarray["app"] = $provider_display_name;
1875 $datarray["plink"] = self::plink($author, $guid);
1876 $datarray["private"] = (($public == "false") ? 1 : 0);
1877 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1879 if (isset($address["address"]))
1880 $datarray["location"] = $address["address"];
1882 if (isset($address["lat"]) AND isset($address["lng"]))
1883 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1885 self::fetch_guid($datarray);
1886 $message_id = item_store($datarray);
1889 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1894 /******************************************************************************************
1895 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1896 ******************************************************************************************/
1898 private function my_handle($me) {
1899 if ($contact["addr"] != "")
1900 return $contact["addr"];
1902 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1903 // So - just in case - we build the the address here.
1904 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1907 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1909 logger("Message: ".$msg, LOGGER_DATA);
1911 $handle = self::my_handle($user);
1913 $b64url_data = base64url_encode($msg);
1915 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1917 $type = "application/xml";
1918 $encoding = "base64url";
1919 $alg = "RSA-SHA256";
1921 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1923 $signature = rsa_sign($signable_data,$prvkey);
1924 $sig = base64url_encode($signature);
1926 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1927 "me:env" => array("me:encoding" => "base64url",
1928 "me:alg" => "RSA-SHA256",
1930 "@attributes" => array("type" => "application/xml"),
1931 "me:sig" => $sig)));
1933 $namespaces = array("" => "https://joindiaspora.com/protocol",
1934 "me" => "http://salmon-protocol.org/ns/magic-env");
1936 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1938 logger("magic_env: ".$magic_env, LOGGER_DATA);
1942 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1944 logger("Message: ".$msg, LOGGER_DATA);
1946 // without a public key nothing will work
1949 logger("pubkey missing: contact id: ".$contact["id"]);
1953 $inner_aes_key = random_string(32);
1954 $b_inner_aes_key = base64_encode($inner_aes_key);
1955 $inner_iv = random_string(16);
1956 $b_inner_iv = base64_encode($inner_iv);
1958 $outer_aes_key = random_string(32);
1959 $b_outer_aes_key = base64_encode($outer_aes_key);
1960 $outer_iv = random_string(16);
1961 $b_outer_iv = base64_encode($outer_iv);
1963 $handle = self::my_handle($user);
1965 $padded_data = pkcs5_pad($msg,16);
1966 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1968 $b64_data = base64_encode($inner_encrypted);
1971 $b64url_data = base64url_encode($b64_data);
1972 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1974 $type = "application/xml";
1975 $encoding = "base64url";
1976 $alg = "RSA-SHA256";
1978 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1980 $signature = rsa_sign($signable_data,$prvkey);
1981 $sig = base64url_encode($signature);
1983 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1984 "aes_key" => $b_inner_aes_key,
1985 "author_id" => $handle));
1987 $decrypted_header = xml::from_array($xmldata, $xml, true);
1988 $decrypted_header = pkcs5_pad($decrypted_header,16);
1990 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1992 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1994 $encrypted_outer_key_bundle = "";
1995 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1997 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1999 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2001 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2002 "ciphertext" => base64_encode($ciphertext)));
2003 $cipher_json = base64_encode($encrypted_header_json_object);
2005 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2006 "me:env" => array("me:encoding" => "base64url",
2007 "me:alg" => "RSA-SHA256",
2009 "@attributes" => array("type" => "application/xml"),
2010 "me:sig" => $sig)));
2012 $namespaces = array("" => "https://joindiaspora.com/protocol",
2013 "me" => "http://salmon-protocol.org/ns/magic-env");
2015 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2017 logger("magic_env: ".$magic_env, LOGGER_DATA);
2021 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2024 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2026 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2028 // The data that will be transmitted is double encoded via "urlencode", strange ...
2029 $slap = "xml=".urlencode(urlencode($magic_env));
2033 private function signature($owner, $message) {
2035 unset($sigmsg["author_signature"]);
2036 unset($sigmsg["parent_author_signature"]);
2038 $signed_text = implode(";", $sigmsg);
2040 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2043 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2047 $enabled = intval(get_config("system", "diaspora_enabled"));
2051 $logid = random_string(4);
2052 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2054 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2058 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2060 if (!$queue_run && was_recently_delayed($contact["id"])) {
2063 if (!intval(get_config("system", "diaspora_test"))) {
2064 post_url($dest_url."/", $slap);
2065 $return_code = $a->get_curl_code();
2067 logger("test_mode");
2072 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2074 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2075 logger("queue message");
2077 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2078 intval($contact["id"]),
2079 dbesc(NETWORK_DIASPORA),
2081 intval($public_batch)
2084 logger("add_to_queue ignored - identical item already in queue");
2086 // queue message for redelivery
2087 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2091 return(($return_code) ? $return_code : (-1));
2095 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2097 $data = array("XML" => array("post" => array($type => $message)));
2099 $msg = xml::from_array($data, $xml);
2101 logger('message: '.$msg, LOGGER_DATA);
2102 logger('send guid '.$guid, LOGGER_DEBUG);
2104 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2107 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2110 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2112 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2114 return $return_code;
2117 public static function send_share($owner,$contact) {
2119 $message = array("sender_handle" => self::my_handle($owner),
2120 "recipient_handle" => $contact["addr"]);
2122 return self::build_and_transmit($owner, $contact, "request", $message);
2125 public static function send_unshare($owner,$contact) {
2127 $message = array("post_guid" => $owner["guid"],
2128 "diaspora_handle" => self::my_handle($owner),
2129 "type" => "Person");
2131 return self::build_and_transmit($owner, $contact, "retraction", $message);
2134 public static function is_reshare($body, $complete = true) {
2135 $body = trim($body);
2137 // Skip if it isn't a pure repeated messages
2138 // Does it start with a share?
2139 if (strpos($body, "[share") > 0)
2142 // Does it end with a share?
2143 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2146 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2147 // Skip if there is no shared message in there
2148 if ($body == $attributes)
2151 // If we don't do the complete check we quit here
2156 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2157 if ($matches[1] != "")
2158 $guid = $matches[1];
2160 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2161 if ($matches[1] != "")
2162 $guid = $matches[1];
2165 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2166 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2169 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2170 $ret["root_guid"] = $guid;
2176 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2177 if ($matches[1] != "")
2178 $profile = $matches[1];
2180 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2181 if ($matches[1] != "")
2182 $profile = $matches[1];
2186 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2187 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2191 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2192 if ($matches[1] != "")
2193 $link = $matches[1];
2195 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2196 if ($matches[1] != "")
2197 $link = $matches[1];
2199 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2200 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2205 public static function send_status($item, $owner, $contact, $public_batch = false) {
2207 $myaddr = self::my_handle($owner);
2209 $public = (($item["private"]) ? "false" : "true");
2211 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2213 // Detect a share element and do a reshare
2214 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2215 $message = array("root_diaspora_id" => $ret["root_handle"],
2216 "root_guid" => $ret["root_guid"],
2217 "guid" => $item["guid"],
2218 "diaspora_handle" => $myaddr,
2219 "public" => $public,
2220 "created_at" => $created,
2221 "provider_display_name" => $item["app"]);
2225 $title = $item["title"];
2226 $body = $item["body"];
2228 // convert to markdown
2229 $body = html_entity_decode(bb2diaspora($body));
2233 $body = "## ".html_entity_decode($title)."\n\n".$body;
2235 if ($item["attach"]) {
2236 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2238 $body .= "\n".t("Attachments:")."\n";
2239 foreach($matches as $mtch)
2240 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2244 $location = array();
2246 if ($item["location"] != "")
2247 $location["address"] = $item["location"];
2249 if ($item["coord"] != "") {
2250 $coord = explode(" ", $item["coord"]);
2251 $location["lat"] = $coord[0];
2252 $location["lng"] = $coord[1];
2255 $message = array("raw_message" => $body,
2256 "location" => $location,
2257 "guid" => $item["guid"],
2258 "diaspora_handle" => $myaddr,
2259 "public" => $public,
2260 "created_at" => $created,
2261 "provider_display_name" => $item["app"]);
2263 if (count($location) == 0)
2264 unset($message["location"]);
2266 $type = "status_message";
2269 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2272 private function construct_like($item, $owner) {
2274 $myaddr = self::my_handle($owner);
2276 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2277 dbesc($item["thr-parent"]));
2283 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2286 return(array("positive" => $positive,
2287 "guid" => $item["guid"],
2288 "target_type" => $target_type,
2289 "parent_guid" => $parent["guid"],
2290 "author_signature" => $authorsig,
2291 "diaspora_handle" => $myaddr));
2294 private function construct_comment($item, $owner) {
2296 $myaddr = self::my_handle($owner);
2298 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2299 intval($item["parent"]),
2300 intval($item["parent"])
2308 $text = html_entity_decode(bb2diaspora($item["body"]));
2310 return(array("guid" => $item["guid"],
2311 "parent_guid" => $parent["guid"],
2312 "author_signature" => "",
2314 "diaspora_handle" => $myaddr));
2317 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2319 if($item['verb'] === ACTIVITY_LIKE) {
2320 $message = self::construct_like($item, $owner);
2323 $message = self::construct_comment($item, $owner);
2330 $message["author_signature"] = self::signature($owner, $message);
2332 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2335 private function message_from_signatur($item, $signature) {
2337 // Split the signed text
2338 $signed_parts = explode(";", $signature['signed_text']);
2340 if ($item["deleted"])
2341 $message = array("parent_author_signature" => "",
2342 "target_guid" => $signed_parts[0],
2343 "target_type" => $signed_parts[1],
2344 "sender_handle" => $signature['signer'],
2345 "target_author_signature" => $signature['signature']);
2346 elseif ($item['verb'] === ACTIVITY_LIKE)
2347 $message = array("positive" => $signed_parts[0],
2348 "guid" => $signed_parts[1],
2349 "target_type" => $signed_parts[2],
2350 "parent_guid" => $signed_parts[3],
2351 "parent_author_signature" => "",
2352 "author_signature" => $signature['signature'],
2353 "diaspora_handle" => $signed_parts[4]);
2355 // Remove the comment guid
2356 $guid = array_shift($signed_parts);
2358 // Remove the parent guid
2359 $parent_guid = array_shift($signed_parts);
2361 // Remove the handle
2362 $handle = array_pop($signed_parts);
2364 // Glue the parts together
2365 $text = implode(";", $signed_parts);
2367 $message = array("guid" => $guid,
2368 "parent_guid" => $parent_guid,
2369 "parent_author_signature" => "",
2370 "author_signature" => $signature['signature'],
2371 "text" => implode(";", $signed_parts),
2372 "diaspora_handle" => $handle);
2377 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2379 if ($item["deleted"])
2380 return self::send_retraction($item, $owner, $contact, $public_batch, true);
2381 elseif ($item['verb'] === ACTIVITY_LIKE)
2386 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2388 // fetch the original signature
2390 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
2391 intval($item["id"]));
2394 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2400 // Old way - is used by the internal Friendica functions
2401 /// @todo Change all signatur storing functions to the new format
2402 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2403 $message = self::message_from_signatur($item, $signature);
2405 $msg = json_decode($signature['signed_text'], true);
2408 if (is_array($msg)) {
2409 foreach ($msg AS $field => $data) {
2410 if (!$item["deleted"]) {
2411 if ($field == "author")
2412 $field = "diaspora_handle";
2413 if ($field == "parent_type")
2414 $field = "target_type";
2417 $message[$field] = $data;
2420 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2423 $message["parent_author_signature"] = self::signature($owner, $message);
2425 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2427 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2430 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
2432 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
2433 //$myaddr = self::my_handle($owner);
2435 // Check whether the retraction is for a top-level post or whether it's a relayable
2436 if ($item["uri"] !== $item["parent-uri"]) {
2437 $msg_type = "relayable_retraction";
2438 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2440 $msg_type = "signed_retraction";
2441 $target_type = "StatusMessage";
2444 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
2445 $signature = "parent_author_signature";
2447 $signature = "target_author_signature";
2449 $signed_text = $item["guid"].";".$target_type;
2451 $message = array("target_guid" => $item['guid'],
2452 "target_type" => $target_type,
2453 "sender_handle" => $itemaddr,
2454 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2456 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2458 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2461 public static function send_mail($item, $owner, $contact) {
2463 $myaddr = self::my_handle($owner);
2465 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2466 intval($item["convid"]),
2467 intval($item["uid"])
2471 logger("conversation not found.");
2477 "guid" => $cnv["guid"],
2478 "subject" => $cnv["subject"],
2479 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2480 "diaspora_handle" => $cnv["creator"],
2481 "participant_handles" => $cnv["recips"]
2484 $body = bb2diaspora($item["body"]);
2485 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2487 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2488 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2491 "guid" => $item["guid"],
2492 "parent_guid" => $cnv["guid"],
2493 "parent_author_signature" => $sig,
2494 "author_signature" => $sig,
2496 "created_at" => $created,
2497 "diaspora_handle" => $myaddr,
2498 "conversation_guid" => $cnv["guid"]
2501 if ($item["reply"]) {
2505 $message = array("guid" => $cnv["guid"],
2506 "subject" => $cnv["subject"],
2507 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2509 "diaspora_handle" => $cnv["creator"],
2510 "participant_handles" => $cnv["recips"]);
2512 $type = "conversation";
2515 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2518 public static function send_profile($uid) {
2523 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2524 AND `uid` = %d AND `rel` != %d",
2525 dbesc(NETWORK_DIASPORA),
2527 intval(CONTACT_IS_SHARING)
2532 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2534 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2535 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2536 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
2545 $handle = $profile["addr"];
2546 $first = ((strpos($profile['name'],' ')
2547 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
2548 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
2549 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
2550 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
2551 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
2552 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
2554 if ($searchable === 'true') {
2555 $dob = '1000-00-00';
2557 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
2558 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
2560 $about = $profile['about'];
2561 $about = strip_tags(bbcode($about));
2563 $location = formatted_location($profile);
2565 if ($profile['pub_keywords']) {
2566 $kw = str_replace(',',' ',$profile['pub_keywords']);
2567 $kw = str_replace(' ',' ',$kw);
2568 $arr = explode(' ',$profile['pub_keywords']);
2570 for($x = 0; $x < 5; $x ++) {
2572 $tags .= '#'. trim($arr[$x]) .' ';
2576 $tags = trim($tags);
2579 $message = array("diaspora_handle" => $handle,
2580 "first_name" => $first,
2581 "last_name" => $last,
2582 "image_url" => $large,
2583 "image_url_medium" => $medium,
2584 "image_url_small" => $small,
2586 "gender" => $profile['gender'],
2588 "location" => $location,
2589 "searchable" => $searchable,
2590 "tag_string" => $tags);
2592 foreach($recips as $recip)
2593 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);