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
60 * @brief Return a list of relay servers
62 * This is an experimental Diaspora feature.
64 * @return array of relay servers
66 public static function relay_list() {
68 $serverdata = get_config("system", "relay_server");
69 if ($serverdata == "")
74 $servers = explode(",", $serverdata);
76 foreach($servers AS $server) {
77 $server = trim($server);
78 $batch = $server."/receive/public";
80 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
83 $addr = "relay@".str_replace("http://", "", normalise_link($server));
85 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
86 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
91 dbesc(normalise_link($server)),
93 dbesc(NETWORK_DIASPORA),
94 intval(CONTACT_IS_FOLLOWER),
95 dbesc(datetime_convert()),
96 dbesc(datetime_convert()),
97 dbesc(datetime_convert())
100 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
102 $relay[] = $relais[0];
104 $relay[] = $relais[0];
111 * @brief repairs a signature that was double encoded
113 * The function is unused at the moment. It was copied from the old implementation.
115 * @param string $signature The signature
116 * @param string $handle The handle of the signature owner
117 * @param integer $level This value is only set inside this function to avoid endless loops
119 * @return string the repaired signature
121 private function repair_signature($signature, $handle = "", $level = 1) {
123 if ($signature == "")
126 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
127 $signature = base64_decode($signature);
128 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
130 // Do a recursive call to be able to fix even multiple levels
132 $signature = self::repair_signature($signature, $handle, ++$level);
139 * @brief: Decodes incoming Diaspora message
141 * @param array $importer Array of the importer user
142 * @param string $xml urldecoded Diaspora salmon
145 * 'message' -> decoded Diaspora XML message
146 * 'author' -> author diaspora handle
147 * 'key' -> author public key (converted to pkcs#8)
149 public static function decode($importer, $xml) {
152 $basedom = parse_xml_string($xml);
154 if (!is_object($basedom))
157 $children = $basedom->children('https://joindiaspora.com/protocol');
159 if($children->header) {
161 $author_link = str_replace('acct:','',$children->header->author_id);
164 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
166 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
167 $ciphertext = base64_decode($encrypted_header->ciphertext);
169 $outer_key_bundle = '';
170 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
172 $j_outer_key_bundle = json_decode($outer_key_bundle);
174 $outer_iv = base64_decode($j_outer_key_bundle->iv);
175 $outer_key = base64_decode($j_outer_key_bundle->key);
177 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
180 $decrypted = pkcs5_unpad($decrypted);
182 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
183 $idom = parse_xml_string($decrypted,false);
185 $inner_iv = base64_decode($idom->iv);
186 $inner_aes_key = base64_decode($idom->aes_key);
188 $author_link = str_replace('acct:','',$idom->author_id);
191 $dom = $basedom->children(NAMESPACE_SALMON_ME);
193 // figure out where in the DOM tree our data is hiding
195 if($dom->provenance->data)
196 $base = $dom->provenance;
197 elseif($dom->env->data)
203 logger('unable to locate salmon data in xml');
204 http_status_exit(400);
208 // Stash the signature away for now. We have to find their key or it won't be good for anything.
209 $signature = base64url_decode($base->sig);
213 // strip whitespace so our data element will return to one big base64 blob
214 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
217 // stash away some other stuff for later
219 $type = $base->data[0]->attributes()->type[0];
220 $keyhash = $base->sig[0]->attributes()->keyhash[0];
221 $encoding = $base->encoding;
225 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
229 $data = base64url_decode($data);
233 $inner_decrypted = $data;
236 // Decode the encrypted blob
238 $inner_encrypted = base64_decode($data);
239 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
240 $inner_decrypted = pkcs5_unpad($inner_decrypted);
244 logger('Could not retrieve author URI.');
245 http_status_exit(400);
247 // Once we have the author URI, go to the web and try to find their public key
248 // (first this will look it up locally if it is in the fcontact cache)
249 // This will also convert diaspora public key from pkcs#1 to pkcs#8
251 logger('Fetching key for '.$author_link);
252 $key = self::key($author_link);
255 logger('Could not retrieve author key.');
256 http_status_exit(400);
259 $verify = rsa_verify($signed_data,$signature,$key);
262 logger('Message did not verify. Discarding.');
263 http_status_exit(400);
266 logger('Message verified.');
268 return array('message' => (string)$inner_decrypted,
269 'author' => unxmlify($author_link),
270 'key' => (string)$key);
276 * @brief Dispatches public messages and find the fitting receivers
278 * @param array $msg The post that will be dispatched
280 * @return int The message id of the generated message, "true" or "false" if there was an error
282 public static function dispatch_public($msg) {
284 $enabled = intval(get_config("system", "diaspora_enabled"));
286 logger("diaspora is disabled");
290 // Use a dummy importer to import the data for the public copy
291 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
292 $message_id = self::dispatch($importer,$msg);
294 // Now distribute it to the followers
295 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
296 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
297 AND NOT `account_expired` AND NOT `account_removed`",
298 dbesc(NETWORK_DIASPORA),
299 dbesc($msg["author"])
303 logger("delivering to: ".$rr["username"]);
304 self::dispatch($rr,$msg);
307 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
313 * @brief Dispatches the different message types to the different functions
315 * @param array $importer Array of the importer user
316 * @param array $msg The post that will be dispatched
318 * @return int The message id of the generated message, "true" or "false" if there was an error
320 public static function dispatch($importer, $msg) {
322 // The sender is the handle of the contact that sent the message.
323 // This will often be different with relayed messages (for example "like" and "comment")
324 $sender = $msg["author"];
326 if (!diaspora::valid_posting($msg, $fields)) {
327 logger("Invalid posting");
331 $type = $fields->getName();
333 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
336 case "account_deletion":
337 return self::receive_account_deletion($importer, $fields);
340 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
343 return self::receive_contact_request($importer, $fields);
346 return self::receive_conversation($importer, $msg, $fields);
349 return self::receive_like($importer, $sender, $fields);
352 return self::receive_message($importer, $fields);
354 case "participation": // Not implemented
355 return self::receive_participation($importer, $fields);
357 case "photo": // Not implemented
358 return self::receive_photo($importer, $fields);
360 case "poll_participation": // Not implemented
361 return self::receive_poll_participation($importer, $fields);
364 return self::receive_profile($importer, $fields);
367 return self::receive_reshare($importer, $fields, $msg["message"]);
370 return self::receive_retraction($importer, $sender, $fields);
372 case "status_message":
373 return self::receive_status_message($importer, $fields, $msg["message"]);
376 logger("Unknown message type ".$type);
384 * @brief Checks if a posting is valid and fetches the data fields.
386 * This function does not only check the signature.
387 * It also does the conversion between the old and the new diaspora format.
389 * @param array $msg Array with the XML, the sender handle and the sender signature
390 * @param object $fields SimpleXML object that contains the posting when it is valid
392 * @return bool Is the posting valid?
394 private function valid_posting($msg, &$fields) {
396 $data = parse_xml_string($msg["message"], false);
398 if (!is_object($data))
401 $first_child = $data->getName();
403 // Is this the new or the old version?
404 if ($data->getName() == "XML") {
406 foreach ($data->post->children() as $child)
413 $type = $element->getName();
416 // All retractions are handled identically from now on.
417 // In the new version there will only be "retraction".
418 if (in_array($type, array("signed_retraction", "relayable_retraction")))
419 $type = "retraction";
421 if ($type == "request")
424 $fields = new SimpleXMLElement("<".$type."/>");
428 foreach ($element->children() AS $fieldname => $entry) {
430 // Translation for the old XML structure
431 if ($fieldname == "diaspora_handle")
432 $fieldname = "author";
434 if ($fieldname == "participant_handles")
435 $fieldname = "participants";
437 if (in_array($type, array("like", "participation"))) {
438 if ($fieldname == "target_type")
439 $fieldname = "parent_type";
442 if ($fieldname == "sender_handle")
443 $fieldname = "author";
445 if ($fieldname == "recipient_handle")
446 $fieldname = "recipient";
448 if ($fieldname == "root_diaspora_id")
449 $fieldname = "root_author";
451 if ($type == "retraction") {
452 if ($fieldname == "post_guid")
453 $fieldname = "target_guid";
455 if ($fieldname == "type")
456 $fieldname = "target_type";
460 if ($fieldname == "author_signature")
461 $author_signature = base64_decode($entry);
462 elseif ($fieldname == "parent_author_signature")
463 $parent_author_signature = base64_decode($entry);
464 elseif ($fieldname != "target_author_signature") {
465 if ($signed_data != "") {
467 $signed_data_parent .= ";";
470 $signed_data .= $entry;
472 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
473 ($orig_type == "relayable_retraction"))
474 xml::copy($entry, $fields, $fieldname);
477 // This is something that shouldn't happen at all.
478 if (in_array($type, array("status_message", "reshare", "profile")))
479 if ($msg["author"] != $fields->author) {
480 logger("Message handle is not the same as envelope sender. Quitting this message.");
484 // Only some message types have signatures. So we quit here for the other types.
485 if (!in_array($type, array("comment", "message", "like")))
488 // No author_signature? This is a must, so we quit.
489 if (!isset($author_signature))
492 if (isset($parent_author_signature)) {
493 $key = self::key($msg["author"]);
495 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
499 $key = self::key($fields->author);
501 return rsa_verify($signed_data, $author_signature, $key, "sha256");
505 * @brief Fetches the public key for a given handle
507 * @param string $handle The handle
509 * @return string The public key
511 private function key($handle) {
512 $handle = strval($handle);
514 logger("Fetching diaspora key for: ".$handle);
516 $r = self::person_by_handle($handle);
524 * @brief Fetches data for a given handle
526 * @param string $handle The handle
528 * @return array the queried data
530 private function person_by_handle($handle) {
532 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
533 dbesc(NETWORK_DIASPORA),
538 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
540 // update record occasionally so it doesn't get stale
541 $d = strtotime($person["updated"]." +00:00");
542 if ($d < strtotime("now - 14 days"))
546 if (!$person OR $update) {
547 logger("create or refresh", LOGGER_DEBUG);
548 $r = probe_url($handle, PROBE_DIASPORA);
550 // Note that Friendica contacts will return a "Diaspora person"
551 // if Diaspora connectivity is enabled on their server
552 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
553 self::add_fcontact($r, $update);
561 * @brief Updates the fcontact table
563 * @param array $arr The fcontact data
564 * @param bool $update Update or insert?
566 * @return string The id of the fcontact entry
568 private function add_fcontact($arr, $update = false) {
571 $r = q("UPDATE `fcontact` SET
584 WHERE `url` = '%s' AND `network` = '%s'",
586 dbesc($arr["photo"]),
587 dbesc($arr["request"]),
590 dbesc($arr["batch"]),
591 dbesc($arr["notify"]),
593 dbesc($arr["confirm"]),
594 dbesc($arr["alias"]),
595 dbesc($arr["pubkey"]),
596 dbesc(datetime_convert()),
598 dbesc($arr["network"])
601 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
602 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
603 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
606 dbesc($arr["photo"]),
607 dbesc($arr["request"]),
610 dbesc($arr["batch"]),
611 dbesc($arr["notify"]),
613 dbesc($arr["confirm"]),
614 dbesc($arr["network"]),
615 dbesc($arr["alias"]),
616 dbesc($arr["pubkey"]),
617 dbesc(datetime_convert())
625 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
627 * @param int $contact_id The id in the contact table
628 * @param int $gcontact_id The id in the gcontact table
630 * @return string the handle
632 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
635 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
637 if ($gcontact_id != 0) {
638 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
639 intval($gcontact_id));
641 return $r[0]["addr"];
644 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
645 intval($contact_id));
649 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
651 if($contact['addr'] != "")
652 $handle = $contact['addr'];
654 $baseurl_start = strpos($contact['url'],'://') + 3;
655 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
656 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
657 $handle = $contact['nick'].'@'.$baseurl;
665 * @brief Get a contact id for a given handle
667 * @param int $uid The user id
668 * @param string $handle The handle in the format user@domain.tld
670 * @return The contact id
672 private function contact_by_handle($uid, $handle) {
673 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
681 $handle_parts = explode("@", $handle);
682 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
683 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
695 * @brief Check if posting is allowed for this contact
697 * @param array $importer Array of the importer user
698 * @param array $contact The contact that is checked
699 * @param bool $is_comment Is the check for a comment?
701 * @return bool is the contact allowed to post?
703 private function post_allow($importer, $contact, $is_comment = false) {
705 // perhaps we were already sharing with this person. Now they're sharing with us.
706 // That makes us friends.
707 // Normally this should have handled by getting a request - but this could get lost
708 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
709 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
710 intval(CONTACT_IS_FRIEND),
711 intval($contact["id"]),
712 intval($importer["uid"])
714 $contact["rel"] = CONTACT_IS_FRIEND;
715 logger("defining user ".$contact["nick"]." as friend");
718 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
720 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
722 if($contact["rel"] == CONTACT_IS_FOLLOWER)
723 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
726 // Messages for the global users are always accepted
727 if ($importer["uid"] == 0)
734 * @brief Fetches the contact id for a handle and checks if posting is allowed
736 * @param array $importer Array of the importer user
737 * @param string $handle The checked handle in the format user@domain.tld
738 * @param bool $is_comment Is the check for a comment?
740 * @return array The contact data
742 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
743 $contact = self::contact_by_handle($importer["uid"], $handle);
745 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
749 if (!self::post_allow($importer, $contact, $is_comment)) {
750 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
757 * @brief Does the message already exists on the system?
759 * @param int $uid The user id
760 * @param string $guid The guid of the message
762 * @return int|bool message id if the message already was stored into the system - or false.
764 private function message_exists($uid, $guid) {
765 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
771 logger("message ".$guid." already exists for user ".$uid);
779 * @brief Checks for links to posts in a message
781 * @param array $item The item array
783 private function fetch_guid($item) {
784 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
785 function ($match) use ($item){
786 return(self::fetch_guid_sub($match, $item));
791 * @brief sub function of "fetch_guid" which checks for links in messages
793 * @param array $match array containing a link that has to be checked for a message link
794 * @param array $item The item array
796 private function fetch_guid_sub($match, $item) {
797 if (!self::store_by_guid($match[1], $item["author-link"]))
798 self::store_by_guid($match[1], $item["owner-link"]);
802 * @brief Fetches an item with a given guid from a given server
804 * @param string $guid the message guid
805 * @param string $server The server address
806 * @param int $uid The user id of the user
808 * @return int the message id of the stored message or false
810 private function store_by_guid($guid, $server, $uid = 0) {
811 $serverparts = parse_url($server);
812 $server = $serverparts["scheme"]."://".$serverparts["host"];
814 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
816 $msg = self::message($guid, $server);
821 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
823 // Now call the dispatcher
824 return self::dispatch_public($msg);
828 * @brief Fetches a message from a server
830 * @param string $guid message guid
831 * @param string $server The url of the server
832 * @param int $level Endless loop prevention
835 * 'message' => The message XML
836 * 'author' => The author handle
837 * 'key' => The public key of the author
839 private function message($guid, $server, $level = 0) {
844 // This will work for Diaspora and newer Friendica servers
845 $source_url = $server."/p/".$guid.".xml";
846 $x = fetch_url($source_url);
850 $source_xml = parse_xml_string($x, false);
852 if (!is_object($source_xml))
855 if ($source_xml->post->reshare) {
856 // Reshare of a reshare - old Diaspora version
857 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
858 } elseif ($source_xml->getName() == "reshare") {
859 // Reshare of a reshare - new Diaspora version
860 return self::message($source_xml->root_guid, $server, ++$level);
865 // Fetch the author - for the old and the new Diaspora version
866 if ($source_xml->post->status_message->diaspora_handle)
867 $author = (string)$source_xml->post->status_message->diaspora_handle;
868 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
869 $author = (string)$source_xml->author;
871 // If this isn't a "status_message" then quit
875 $msg = array("message" => $x, "author" => $author);
877 $msg["key"] = self::key($msg["author"]);
883 * @brief Fetches the item record of a given guid
885 * @param int $uid The user id
886 * @param string $guid message guid
887 * @param string $author The handle of the item
888 * @param array $contact The contact of the item owner
890 * @return array the item record
892 private function parent_item($uid, $guid, $author, $contact) {
893 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
894 `author-name`, `author-link`, `author-avatar`,
895 `owner-name`, `owner-link`, `owner-avatar`
896 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
897 intval($uid), dbesc($guid));
900 $result = self::store_by_guid($guid, $contact["url"], $uid);
903 $person = self::person_by_handle($author);
904 $result = self::store_by_guid($guid, $person["url"], $uid);
908 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
910 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
911 `author-name`, `author-link`, `author-avatar`,
912 `owner-name`, `owner-link`, `owner-avatar`
913 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
914 intval($uid), dbesc($guid));
919 logger("parent item not found: parent: ".$guid." - user: ".$uid);
922 logger("parent item found: parent: ".$guid." - user: ".$uid);
928 * @brief returns contact details
930 * @param array $contact The default contact if the person isn't found
931 * @param array $person The record of the person
932 * @param int $uid The user id
935 * 'cid' => contact id
936 * 'network' => network type
938 private function author_contact_by_url($contact, $person, $uid) {
940 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
941 dbesc(normalise_link($person["url"])), intval($uid));
944 $network = $r[0]["network"];
946 $cid = $contact["id"];
947 $network = NETWORK_DIASPORA;
950 return (array("cid" => $cid, "network" => $network));
954 * @brief Is the profile a hubzilla profile?
956 * @param string $url The profile link
958 * @return bool is it a hubzilla server?
960 public static function is_redmatrix($url) {
961 return(strstr($url, "/channel/"));
965 * @brief Generate a post link with a given handle and message guid
967 * @param string $addr The user handle
968 * @param string $guid message guid
970 * @return string the post link
972 private function plink($addr, $guid) {
973 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
977 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
979 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
980 // So we try another way as well.
981 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
983 $r[0]["network"] = $s[0]["network"];
985 if ($r[0]["network"] == NETWORK_DFRN)
986 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
988 if (self::is_redmatrix($r[0]["url"]))
989 return $r[0]["url"]."/?f=&mid=".$guid;
991 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
995 * @brief Processes an account deletion
997 * @param array $importer Array of the importer user
998 * @param object $data The message object
1000 * @return bool Success
1002 private function receive_account_deletion($importer, $data) {
1003 $author = notags(unxmlify($data->author));
1005 $contact = self::contact_by_handle($importer["uid"], $author);
1007 logger("cannot find contact for author: ".$author);
1011 // We now remove the contact
1012 contact_remove($contact["id"]);
1017 * @brief Processes an incoming comment
1019 * @param array $importer Array of the importer user
1020 * @param string $sender The sender of the message
1021 * @param object $data The message object
1022 * @param string $xml The original XML of the message
1024 * @return int The message id of the generated comment or "false" if there was an error
1026 private function receive_comment($importer, $sender, $data, $xml) {
1027 $guid = notags(unxmlify($data->guid));
1028 $parent_guid = notags(unxmlify($data->parent_guid));
1029 $text = unxmlify($data->text);
1030 $author = notags(unxmlify($data->author));
1032 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1036 $message_id = self::message_exists($importer["uid"], $guid);
1040 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1044 $person = self::person_by_handle($author);
1045 if (!is_array($person)) {
1046 logger("unable to find author details");
1050 // Fetch the contact id - if we know this contact
1051 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1053 $datarray = array();
1055 $datarray["uid"] = $importer["uid"];
1056 $datarray["contact-id"] = $author_contact["cid"];
1057 $datarray["network"] = $author_contact["network"];
1059 $datarray["author-name"] = $person["name"];
1060 $datarray["author-link"] = $person["url"];
1061 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1063 $datarray["owner-name"] = $contact["name"];
1064 $datarray["owner-link"] = $contact["url"];
1065 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1067 $datarray["guid"] = $guid;
1068 $datarray["uri"] = $author.":".$guid;
1070 $datarray["type"] = "remote-comment";
1071 $datarray["verb"] = ACTIVITY_POST;
1072 $datarray["gravity"] = GRAVITY_COMMENT;
1073 $datarray["parent-uri"] = $parent_item["uri"];
1075 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1076 $datarray["object"] = $xml;
1078 $datarray["body"] = diaspora2bb($text);
1080 self::fetch_guid($datarray);
1082 $message_id = item_store($datarray);
1085 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1087 // If we are the origin of the parent we store the original data and notify our followers
1088 if($message_id AND $parent_item["origin"]) {
1090 // Formerly we stored the signed text, the signature and the author in different fields.
1091 // We now store the raw data so that we are more flexible.
1092 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1093 intval($message_id),
1094 dbesc(json_encode($data))
1098 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1105 * @brief processes and stores private messages
1107 * @param array $importer Array of the importer user
1108 * @param array $contact The contact of the message
1109 * @param object $data The message object
1110 * @param array $msg Array of the processed message, author handle and key
1111 * @param object $mesg The private message
1112 * @param array $conversation The conversation record to which this message belongs
1114 * @return bool "true" if it was successful
1116 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1117 $guid = notags(unxmlify($data->guid));
1118 $subject = notags(unxmlify($data->subject));
1119 $author = notags(unxmlify($data->author));
1123 $msg_guid = notags(unxmlify($mesg->guid));
1124 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1125 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1126 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1127 $msg_text = unxmlify($mesg->text);
1128 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1130 // "diaspora_handle" is the element name from the old version
1131 // "author" is the element name from the new version
1133 $msg_author = notags(unxmlify($mesg->author));
1134 elseif ($mesg->diaspora_handle)
1135 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1139 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1141 if($msg_conversation_guid != $guid) {
1142 logger("message conversation guid does not belong to the current conversation.");
1146 $body = diaspora2bb($msg_text);
1147 $message_uri = $msg_author.":".$msg_guid;
1149 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1151 $author_signature = base64_decode($msg_author_signature);
1153 if(strcasecmp($msg_author,$msg["author"]) == 0) {
1157 $person = self::person_by_handle($msg_author);
1159 if (is_array($person) && x($person, "pubkey"))
1160 $key = $person["pubkey"];
1162 logger("unable to find author details");
1167 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1168 logger("verification failed.");
1172 if($msg_parent_author_signature) {
1173 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1175 $parent_author_signature = base64_decode($msg_parent_author_signature);
1179 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1180 logger("owner verification failed.");
1185 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1189 logger("duplicate message already delivered.", LOGGER_DEBUG);
1193 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1194 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1195 intval($importer["uid"]),
1197 intval($conversation["id"]),
1198 dbesc($person["name"]),
1199 dbesc($person["photo"]),
1200 dbesc($person["url"]),
1201 intval($contact["id"]),
1206 dbesc($message_uri),
1207 dbesc($author.":".$guid),
1208 dbesc($msg_created_at)
1211 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1212 dbesc(datetime_convert()),
1213 intval($conversation["id"])
1217 "type" => NOTIFY_MAIL,
1218 "notify_flags" => $importer["notify-flags"],
1219 "language" => $importer["language"],
1220 "to_name" => $importer["username"],
1221 "to_email" => $importer["email"],
1222 "uid" =>$importer["uid"],
1223 "item" => array("subject" => $subject, "body" => $body),
1224 "source_name" => $person["name"],
1225 "source_link" => $person["url"],
1226 "source_photo" => $person["thumb"],
1227 "verb" => ACTIVITY_POST,
1234 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1236 * @param array $importer Array of the importer user
1237 * @param array $msg Array of the processed message, author handle and key
1238 * @param object $data The message object
1240 * @return bool Success
1242 private function receive_conversation($importer, $msg, $data) {
1243 $guid = notags(unxmlify($data->guid));
1244 $subject = notags(unxmlify($data->subject));
1245 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1246 $author = notags(unxmlify($data->author));
1247 $participants = notags(unxmlify($data->participants));
1249 $messages = $data->message;
1251 if (!count($messages)) {
1252 logger("empty conversation");
1256 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1260 $conversation = null;
1262 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1263 intval($importer["uid"]),
1267 $conversation = $c[0];
1269 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1270 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1271 intval($importer["uid"]),
1274 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1275 dbesc(datetime_convert()),
1277 dbesc($participants)
1280 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1281 intval($importer["uid"]),
1286 $conversation = $c[0];
1288 if (!$conversation) {
1289 logger("unable to create conversation.");
1293 foreach($messages as $mesg)
1294 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1300 * @brief Creates the body for a "like" message
1302 * @param array $contact The contact that send us the "like"
1303 * @param array $parent_item The item array of the parent item
1304 * @param string $guid message guid
1306 * @return string the body
1308 private function construct_like_body($contact, $parent_item, $guid) {
1309 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1311 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1312 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1313 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1315 return sprintf($bodyverb, $ulink, $alink, $plink);
1319 * @brief Creates a XML object for a "like"
1321 * @param array $importer Array of the importer user
1322 * @param array $parent_item The item array of the parent item
1324 * @return string The XML
1326 private function construct_like_object($importer, $parent_item) {
1327 $objtype = ACTIVITY_OBJ_NOTE;
1328 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1329 $parent_body = $parent_item["body"];
1331 $xmldata = array("object" => array("type" => $objtype,
1333 "id" => $parent_item["uri"],
1336 "content" => $parent_body));
1338 return xml::from_array($xmldata, $xml, true);
1342 * @brief Processes "like" messages
1344 * @param array $importer Array of the importer user
1345 * @param string $sender The sender of the message
1346 * @param object $data The message object
1348 * @return int The message id of the generated like or "false" if there was an error
1350 private function receive_like($importer, $sender, $data) {
1351 $positive = notags(unxmlify($data->positive));
1352 $guid = notags(unxmlify($data->guid));
1353 $parent_type = notags(unxmlify($data->parent_type));
1354 $parent_guid = notags(unxmlify($data->parent_guid));
1355 $author = notags(unxmlify($data->author));
1357 // likes on comments aren't supported by Diaspora - only on posts
1358 // But maybe this will be supported in the future, so we will accept it.
1359 if (!in_array($parent_type, array("Post", "Comment")))
1362 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1366 $message_id = self::message_exists($importer["uid"], $guid);
1370 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1374 $person = self::person_by_handle($author);
1375 if (!is_array($person)) {
1376 logger("unable to find author details");
1380 // Fetch the contact id - if we know this contact
1381 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1383 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1384 // We would accept this anyhow.
1385 if ($positive == "true")
1386 $verb = ACTIVITY_LIKE;
1388 $verb = ACTIVITY_DISLIKE;
1390 $datarray = array();
1392 $datarray["uid"] = $importer["uid"];
1393 $datarray["contact-id"] = $author_contact["cid"];
1394 $datarray["network"] = $author_contact["network"];
1396 $datarray["author-name"] = $person["name"];
1397 $datarray["author-link"] = $person["url"];
1398 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1400 $datarray["owner-name"] = $contact["name"];
1401 $datarray["owner-link"] = $contact["url"];
1402 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1404 $datarray["guid"] = $guid;
1405 $datarray["uri"] = $author.":".$guid;
1407 $datarray["type"] = "activity";
1408 $datarray["verb"] = $verb;
1409 $datarray["gravity"] = GRAVITY_LIKE;
1410 $datarray["parent-uri"] = $parent_item["uri"];
1412 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1413 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1415 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1417 $message_id = item_store($datarray);
1420 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1422 // If we are the origin of the parent we store the original data and notify our followers
1423 if($message_id AND $parent_item["origin"]) {
1425 // Formerly we stored the signed text, the signature and the author in different fields.
1426 // We now store the raw data so that we are more flexible.
1427 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1428 intval($message_id),
1429 dbesc(json_encode($data))
1433 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1440 * @brief Processes private messages
1442 * @param array $importer Array of the importer user
1443 * @param object $data The message object
1445 * @return bool Success?
1447 private function receive_message($importer, $data) {
1448 $guid = notags(unxmlify($data->guid));
1449 $parent_guid = notags(unxmlify($data->parent_guid));
1450 $text = unxmlify($data->text);
1451 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1452 $author = notags(unxmlify($data->author));
1453 $conversation_guid = notags(unxmlify($data->conversation_guid));
1455 $contact = self::allowed_contact_by_handle($importer, $author, true);
1459 $conversation = null;
1461 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1462 intval($importer["uid"]),
1463 dbesc($conversation_guid)
1466 $conversation = $c[0];
1468 logger("conversation not available.");
1474 $body = diaspora2bb($text);
1475 $message_uri = $author.":".$guid;
1477 $person = self::person_by_handle($author);
1479 logger("unable to find author details");
1483 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1484 dbesc($message_uri),
1485 intval($importer["uid"])
1488 logger("duplicate message already delivered.", LOGGER_DEBUG);
1492 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1493 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1494 intval($importer["uid"]),
1496 intval($conversation["id"]),
1497 dbesc($person["name"]),
1498 dbesc($person["photo"]),
1499 dbesc($person["url"]),
1500 intval($contact["id"]),
1501 dbesc($conversation["subject"]),
1505 dbesc($message_uri),
1506 dbesc($author.":".$parent_guid),
1510 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1511 dbesc(datetime_convert()),
1512 intval($conversation["id"])
1519 * @brief Processes participations - unsupported by now
1521 * @param array $importer Array of the importer user
1522 * @param object $data The message object
1524 * @return bool always true
1526 private function receive_participation($importer, $data) {
1527 // I'm not sure if we can fully support this message type
1532 * @brief Processes photos - unneeded
1534 * @param array $importer Array of the importer user
1535 * @param object $data The message object
1537 * @return bool always true
1539 private function receive_photo($importer, $data) {
1540 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1545 * @brief Processes poll participations - unssupported
1547 * @param array $importer Array of the importer user
1548 * @param object $data The message object
1550 * @return bool always true
1552 private function receive_poll_participation($importer, $data) {
1553 // We don't support polls by now
1558 * @brief Processes incoming profile updates
1560 * @param array $importer Array of the importer user
1561 * @param object $data The message object
1563 * @return bool Success
1565 private function receive_profile($importer, $data) {
1566 $author = notags(unxmlify($data->author));
1568 $contact = self::contact_by_handle($importer["uid"], $author);
1572 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1573 $image_url = unxmlify($data->image_url);
1574 $birthday = unxmlify($data->birthday);
1575 $location = diaspora2bb(unxmlify($data->location));
1576 $about = diaspora2bb(unxmlify($data->bio));
1577 $gender = unxmlify($data->gender);
1578 $searchable = (unxmlify($data->searchable) == "true");
1579 $nsfw = (unxmlify($data->nsfw) == "true");
1580 $tags = unxmlify($data->tag_string);
1582 $tags = explode("#", $tags);
1584 $keywords = array();
1585 foreach ($tags as $tag) {
1586 $tag = trim(strtolower($tag));
1591 $keywords = implode(", ", $keywords);
1593 $handle_parts = explode("@", $author);
1594 $nick = $handle_parts[0];
1597 $name = $handle_parts[0];
1599 if( preg_match("|^https?://|", $image_url) === 0)
1600 $image_url = "http://".$handle_parts[1].$image_url;
1602 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1604 // Generic birthday. We don't know the timezone. The year is irrelevant.
1606 $birthday = str_replace("1000", "1901", $birthday);
1608 if ($birthday != "")
1609 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1611 // this is to prevent multiple birthday notifications in a single year
1612 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1614 if(substr($birthday,5) === substr($contact["bd"],5))
1615 $birthday = $contact["bd"];
1617 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1618 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1622 dbesc(datetime_convert()),
1628 intval($contact["id"]),
1629 intval($importer["uid"])
1633 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1634 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1637 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1638 "photo" => $image_url, "name" => $name, "location" => $location,
1639 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1640 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1641 "hide" => !$searchable, "nsfw" => $nsfw);
1643 update_gcontact($gcontact);
1645 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1651 * @brief Processes incoming friend requests
1653 * @param array $importer Array of the importer user
1654 * @param array $contact The contact that send the request
1656 private function receive_request_make_friend($importer, $contact) {
1660 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1661 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1662 intval(CONTACT_IS_FRIEND),
1663 intval($contact["id"]),
1664 intval($importer["uid"])
1667 // send notification
1669 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1670 intval($importer["uid"])
1673 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1675 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1676 intval($importer["uid"])
1679 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1681 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1684 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1685 $arr["uid"] = $importer["uid"];
1686 $arr["contact-id"] = $self[0]["id"];
1688 $arr["type"] = 'wall';
1689 $arr["gravity"] = 0;
1691 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1692 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1693 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1694 $arr["verb"] = ACTIVITY_FRIEND;
1695 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1697 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1698 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1699 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1700 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1702 $arr["object"] = self::construct_new_friend_object($contact);
1704 $arr["last-child"] = 1;
1706 $arr["allow_cid"] = $user[0]["allow_cid"];
1707 $arr["allow_gid"] = $user[0]["allow_gid"];
1708 $arr["deny_cid"] = $user[0]["deny_cid"];
1709 $arr["deny_gid"] = $user[0]["deny_gid"];
1711 $i = item_store($arr);
1713 proc_run("php", "include/notifier.php", "activity", $i);
1719 * @brief Creates a XML object for a "new friend" message
1721 * @param array $contact Array of the contact
1723 * @return string The XML
1725 private function construct_new_friend_object($contact) {
1726 $objtype = ACTIVITY_OBJ_PERSON;
1727 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1728 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1730 $xmldata = array("object" => array("type" => $objtype,
1731 "title" => $contact["name"],
1732 "id" => $contact["url"]."/".$contact["name"],
1735 return xml::from_array($xmldata, $xml, true);
1739 * @brief Processes incoming sharing notification
1741 * @param array $importer Array of the importer user
1742 * @param object $data The message object
1744 * @return bool Success
1746 private function receive_contact_request($importer, $data) {
1747 $author = unxmlify($data->author);
1748 $recipient = unxmlify($data->recipient);
1750 if (!$author || !$recipient)
1753 // the current protocol version doesn't know these fields
1754 // That means that we will assume their existance
1755 if (isset($data->following))
1756 $following = (unxmlify($data->following) == "true");
1760 if (isset($data->sharing))
1761 $sharing = (unxmlify($data->sharing) == "true");
1765 $contact = self::contact_by_handle($importer["uid"],$author);
1767 // perhaps we were already sharing with this person. Now they're sharing with us.
1768 // That makes us friends.
1770 if ($following AND $sharing) {
1771 self::receive_request_make_friend($importer, $contact);
1773 } else /// @todo Handle all possible variations of adding and retracting of permissions
1777 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
1778 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
1780 } elseif (!$following AND !$sharing) {
1781 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
1785 $ret = self::person_by_handle($author);
1787 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1788 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1792 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1794 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1795 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1796 intval($importer["uid"]),
1797 dbesc($ret["network"]),
1798 dbesc($ret["addr"]),
1801 dbesc(normalise_link($ret["url"])),
1803 dbesc($ret["name"]),
1804 dbesc($ret["nick"]),
1805 dbesc($ret["photo"]),
1806 dbesc($ret["pubkey"]),
1807 dbesc($ret["notify"]),
1808 dbesc($ret["poll"]),
1813 // find the contact record we just created
1815 $contact_record = self::contact_by_handle($importer["uid"],$author);
1817 if (!$contact_record) {
1818 logger("unable to locate newly created contact record.");
1822 $def_gid = get_default_group($importer['uid'], $ret["network"]);
1824 if(intval($def_gid))
1825 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
1827 if($importer["page-flags"] == PAGE_NORMAL) {
1829 $hash = random_string().(string)time(); // Generate a confirm_key
1831 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1832 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1833 intval($importer["uid"]),
1834 intval($contact_record["id"]),
1837 dbesc(t("Sharing notification from Diaspora network")),
1839 dbesc(datetime_convert())
1843 // automatic friend approval
1845 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1847 // technically they are sharing with us (CONTACT_IS_SHARING),
1848 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1849 // we are going to change the relationship and make them a follower.
1851 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
1852 $new_relation = CONTACT_IS_FRIEND;
1853 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
1854 $new_relation = CONTACT_IS_SHARING;
1856 $new_relation = CONTACT_IS_FOLLOWER;
1858 $r = q("UPDATE `contact` SET `rel` = %d,
1866 intval($new_relation),
1867 dbesc(datetime_convert()),
1868 dbesc(datetime_convert()),
1869 intval($contact_record["id"])
1872 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1874 $ret = self::send_share($u[0], $contact_record);
1881 * @brief Fetches a message with a given guid
1883 * @param string $guid message guid
1884 * @param string $orig_author handle of the original post
1885 * @param string $author handle of the sharer
1887 * @return array The fetched item
1889 private function original_item($guid, $orig_author, $author) {
1891 // Do we already have this item?
1892 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1893 `author-name`, `author-link`, `author-avatar`
1894 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1898 logger("reshared message ".$guid." already exists on system.");
1900 // Maybe it is already a reshared item?
1901 // Then refetch the content, if it is a reshare from a reshare.
1902 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
1903 if (self::is_reshare($r[0]["body"], true))
1905 elseif (self::is_reshare($r[0]["body"], false)) {
1906 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
1908 // Add OEmbed and other information to the body
1909 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
1917 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1918 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1919 $item_id = self::store_by_guid($guid, $server);
1922 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1923 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1924 $item_id = self::store_by_guid($guid, $server);
1927 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1929 $server = "https://".substr($author, strpos($author, "@") + 1);
1930 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1931 $item_id = self::store_by_guid($guid, $server);
1934 $server = "http://".substr($author, strpos($author, "@") + 1);
1935 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1936 $item_id = self::store_by_guid($guid, $server);
1940 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1941 `author-name`, `author-link`, `author-avatar`
1942 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1954 * @brief Processes a reshare message
1956 * @param array $importer Array of the importer user
1957 * @param object $data The message object
1958 * @param string $xml The original XML of the message
1960 * @return int the message id
1962 private function receive_reshare($importer, $data, $xml) {
1963 $root_author = notags(unxmlify($data->root_author));
1964 $root_guid = notags(unxmlify($data->root_guid));
1965 $guid = notags(unxmlify($data->guid));
1966 $author = notags(unxmlify($data->author));
1967 $public = notags(unxmlify($data->public));
1968 $created_at = notags(unxmlify($data->created_at));
1970 $contact = self::allowed_contact_by_handle($importer, $author, false);
1974 $message_id = self::message_exists($importer["uid"], $guid);
1978 $original_item = self::original_item($root_guid, $root_author, $author);
1979 if (!$original_item)
1982 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1984 $datarray = array();
1986 $datarray["uid"] = $importer["uid"];
1987 $datarray["contact-id"] = $contact["id"];
1988 $datarray["network"] = NETWORK_DIASPORA;
1990 $datarray["author-name"] = $contact["name"];
1991 $datarray["author-link"] = $contact["url"];
1992 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1994 $datarray["owner-name"] = $datarray["author-name"];
1995 $datarray["owner-link"] = $datarray["author-link"];
1996 $datarray["owner-avatar"] = $datarray["author-avatar"];
1998 $datarray["guid"] = $guid;
1999 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
2001 $datarray["verb"] = ACTIVITY_POST;
2002 $datarray["gravity"] = GRAVITY_PARENT;
2004 $datarray["object"] = $xml;
2006 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2007 $original_item["guid"], $original_item["created"], $orig_url);
2008 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2010 $datarray["tag"] = $original_item["tag"];
2011 $datarray["app"] = $original_item["app"];
2013 $datarray["plink"] = self::plink($author, $guid);
2014 $datarray["private"] = (($public == "false") ? 1 : 0);
2015 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2017 $datarray["object-type"] = $original_item["object-type"];
2019 self::fetch_guid($datarray);
2020 $message_id = item_store($datarray);
2023 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2029 * @brief Processes retractions
2031 * @param array $importer Array of the importer user
2032 * @param array $contact The contact of the item owner
2033 * @param object $data The message object
2035 * @return bool success
2037 private function item_retraction($importer, $contact, $data) {
2038 $target_type = notags(unxmlify($data->target_type));
2039 $target_guid = notags(unxmlify($data->target_guid));
2040 $author = notags(unxmlify($data->author));
2042 $person = self::person_by_handle($author);
2043 if (!is_array($person)) {
2044 logger("unable to find author detail for ".$author);
2048 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2049 dbesc($target_guid),
2050 intval($importer["uid"])
2055 // Only delete it if the author really fits
2056 if (!link_compare($r[0]["author-link"], $person["url"])) {
2057 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
2061 // Check if the sender is the thread owner
2062 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2063 intval($r[0]["parent"]));
2065 // Only delete it if the parent author really fits
2066 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2067 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2071 // 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
2072 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2073 dbesc(datetime_convert()),
2074 dbesc(datetime_convert()),
2077 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2079 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2081 // Now check if the retraction needs to be relayed by us
2082 if($p[0]["origin"]) {
2084 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
2091 * @brief Receives retraction messages
2093 * @param array $importer Array of the importer user
2094 * @param string $sender The sender of the message
2095 * @param object $data The message object
2097 * @return bool Success
2099 private function receive_retraction($importer, $sender, $data) {
2100 $target_type = notags(unxmlify($data->target_type));
2102 $contact = self::contact_by_handle($importer["uid"], $sender);
2104 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2108 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2110 switch ($target_type) {
2113 case "Post": // "Post" will be supported in a future version
2115 case "StatusMessage":
2116 return self::item_retraction($importer, $contact, $data);;
2119 /// @todo What should we do with an "unshare"?
2120 // Removing the contact isn't correct since we still can read the public items
2121 //contact_remove($contact["id"]);
2125 logger("Unknown target type ".$target_type);
2132 * @brief Receives status messages
2134 * @param array $importer Array of the importer user
2135 * @param object $data The message object
2136 * @param string $xml The original XML of the message
2138 * @return int The message id of the newly created item
2140 private function receive_status_message($importer, $data, $xml) {
2142 $raw_message = unxmlify($data->raw_message);
2143 $guid = notags(unxmlify($data->guid));
2144 $author = notags(unxmlify($data->author));
2145 $public = notags(unxmlify($data->public));
2146 $created_at = notags(unxmlify($data->created_at));
2147 $provider_display_name = notags(unxmlify($data->provider_display_name));
2149 /// @todo enable support for polls
2150 //if ($data->poll) {
2151 // foreach ($data->poll AS $poll)
2155 $contact = self::allowed_contact_by_handle($importer, $author, false);
2159 $message_id = self::message_exists($importer["uid"], $guid);
2164 if ($data->location)
2165 foreach ($data->location->children() AS $fieldname => $data)
2166 $address[$fieldname] = notags(unxmlify($data));
2168 $body = diaspora2bb($raw_message);
2170 $datarray = array();
2172 // Attach embedded pictures to the body
2174 foreach ($data->photo AS $photo)
2175 $body = "[img]".unxmlify($photo->remote_photo_path).
2176 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2178 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2180 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2182 // Add OEmbed and other information to the body
2183 if (!self::is_redmatrix($contact["url"]))
2184 $body = add_page_info_to_body($body, false, true);
2187 $datarray["uid"] = $importer["uid"];
2188 $datarray["contact-id"] = $contact["id"];
2189 $datarray["network"] = NETWORK_DIASPORA;
2191 $datarray["author-name"] = $contact["name"];
2192 $datarray["author-link"] = $contact["url"];
2193 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2195 $datarray["owner-name"] = $datarray["author-name"];
2196 $datarray["owner-link"] = $datarray["author-link"];
2197 $datarray["owner-avatar"] = $datarray["author-avatar"];
2199 $datarray["guid"] = $guid;
2200 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
2202 $datarray["verb"] = ACTIVITY_POST;
2203 $datarray["gravity"] = GRAVITY_PARENT;
2205 $datarray["object"] = $xml;
2207 $datarray["body"] = $body;
2209 if ($provider_display_name != "")
2210 $datarray["app"] = $provider_display_name;
2212 $datarray["plink"] = self::plink($author, $guid);
2213 $datarray["private"] = (($public == "false") ? 1 : 0);
2214 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2216 if (isset($address["address"]))
2217 $datarray["location"] = $address["address"];
2219 if (isset($address["lat"]) AND isset($address["lng"]))
2220 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2222 self::fetch_guid($datarray);
2223 $message_id = item_store($datarray);
2226 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2231 /* ************************************************************************************** *
2232 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2233 * ************************************************************************************** */
2236 * @brief returnes the handle of a contact
2238 * @param array $me contact array
2240 * @return string the handle in the format user@domain.tld
2242 private function my_handle($contact) {
2243 if ($contact["addr"] != "")
2244 return $contact["addr"];
2246 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2247 // So - just in case - we build the the address here.
2248 if ($contact["nickname"] != "")
2249 $nick = $contact["nickname"];
2251 $nick = $contact["nick"];
2253 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2257 * @brief Creates the envelope for a public message
2259 * @param string $msg The message that is to be transmitted
2260 * @param array $user The record of the sender
2261 * @param array $contact Target of the communication
2262 * @param string $prvkey The private key of the sender
2263 * @param string $pubkey The public key of the receiver
2265 * @return string The envelope
2267 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2269 logger("Message: ".$msg, LOGGER_DATA);
2271 $handle = self::my_handle($user);
2273 $b64url_data = base64url_encode($msg);
2275 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2277 $type = "application/xml";
2278 $encoding = "base64url";
2279 $alg = "RSA-SHA256";
2281 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2283 $signature = rsa_sign($signable_data,$prvkey);
2284 $sig = base64url_encode($signature);
2286 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2287 "me:env" => array("me:encoding" => "base64url",
2288 "me:alg" => "RSA-SHA256",
2290 "@attributes" => array("type" => "application/xml"),
2291 "me:sig" => $sig)));
2293 $namespaces = array("" => "https://joindiaspora.com/protocol",
2294 "me" => "http://salmon-protocol.org/ns/magic-env");
2296 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2298 logger("magic_env: ".$magic_env, LOGGER_DATA);
2303 * @brief Creates the envelope for a private message
2305 * @param string $msg The message that is to be transmitted
2306 * @param array $user The record of the sender
2307 * @param array $contact Target of the communication
2308 * @param string $prvkey The private key of the sender
2309 * @param string $pubkey The public key of the receiver
2311 * @return string The envelope
2313 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2315 logger("Message: ".$msg, LOGGER_DATA);
2317 // without a public key nothing will work
2320 logger("pubkey missing: contact id: ".$contact["id"]);
2324 $inner_aes_key = random_string(32);
2325 $b_inner_aes_key = base64_encode($inner_aes_key);
2326 $inner_iv = random_string(16);
2327 $b_inner_iv = base64_encode($inner_iv);
2329 $outer_aes_key = random_string(32);
2330 $b_outer_aes_key = base64_encode($outer_aes_key);
2331 $outer_iv = random_string(16);
2332 $b_outer_iv = base64_encode($outer_iv);
2334 $handle = self::my_handle($user);
2336 $padded_data = pkcs5_pad($msg,16);
2337 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2339 $b64_data = base64_encode($inner_encrypted);
2342 $b64url_data = base64url_encode($b64_data);
2343 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2345 $type = "application/xml";
2346 $encoding = "base64url";
2347 $alg = "RSA-SHA256";
2349 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2351 $signature = rsa_sign($signable_data,$prvkey);
2352 $sig = base64url_encode($signature);
2354 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2355 "aes_key" => $b_inner_aes_key,
2356 "author_id" => $handle));
2358 $decrypted_header = xml::from_array($xmldata, $xml, true);
2359 $decrypted_header = pkcs5_pad($decrypted_header,16);
2361 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2363 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2365 $encrypted_outer_key_bundle = "";
2366 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2368 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2370 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2372 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2373 "ciphertext" => base64_encode($ciphertext)));
2374 $cipher_json = base64_encode($encrypted_header_json_object);
2376 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2377 "me:env" => array("me:encoding" => "base64url",
2378 "me:alg" => "RSA-SHA256",
2380 "@attributes" => array("type" => "application/xml"),
2381 "me:sig" => $sig)));
2383 $namespaces = array("" => "https://joindiaspora.com/protocol",
2384 "me" => "http://salmon-protocol.org/ns/magic-env");
2386 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2388 logger("magic_env: ".$magic_env, LOGGER_DATA);
2393 * @brief Create the envelope for a message
2395 * @param string $msg The message that is to be transmitted
2396 * @param array $user The record of the sender
2397 * @param array $contact Target of the communication
2398 * @param string $prvkey The private key of the sender
2399 * @param string $pubkey The public key of the receiver
2400 * @param bool $public Is the message public?
2402 * @return string The message that will be transmitted to other servers
2404 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2407 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2409 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2411 // The data that will be transmitted is double encoded via "urlencode", strange ...
2412 $slap = "xml=".urlencode(urlencode($magic_env));
2417 * @brief Creates a signature for a message
2419 * @param array $owner the array of the owner of the message
2420 * @param array $message The message that is to be signed
2422 * @return string The signature
2424 private function signature($owner, $message) {
2426 unset($sigmsg["author_signature"]);
2427 unset($sigmsg["parent_author_signature"]);
2429 $signed_text = implode(";", $sigmsg);
2431 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2435 * @brief Transmit a message to a target server
2437 * @param array $owner the array of the item owner
2438 * @param array $contact Target of the communication
2439 * @param string $slap The message that is to be transmitted
2440 * @param bool $public_batch Is it a public post?
2441 * @param bool $queue_run Is the transmission called from the queue?
2442 * @param string $guid message guid
2444 * @return int Result of the transmission
2446 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2450 $enabled = intval(get_config("system", "diaspora_enabled"));
2454 $logid = random_string(4);
2455 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2457 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2461 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2463 if (!$queue_run && was_recently_delayed($contact["id"])) {
2466 if (!intval(get_config("system", "diaspora_test"))) {
2467 post_url($dest_url."/", $slap);
2468 $return_code = $a->get_curl_code();
2470 logger("test_mode");
2475 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2477 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2478 logger("queue message");
2480 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2481 intval($contact["id"]),
2482 dbesc(NETWORK_DIASPORA),
2484 intval($public_batch)
2487 logger("add_to_queue ignored - identical item already in queue");
2489 // queue message for redelivery
2490 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2494 return(($return_code) ? $return_code : (-1));
2499 * @brief Builds and transmit messages
2501 * @param array $owner the array of the item owner
2502 * @param array $contact Target of the communication
2503 * @param string $type The message type
2504 * @param array $message The message data
2505 * @param bool $public_batch Is it a public post?
2506 * @param string $guid message guid
2507 * @param bool $spool Should the transmission be spooled or transmitted?
2509 * @return int Result of the transmission
2511 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2513 $data = array("XML" => array("post" => array($type => $message)));
2515 $msg = xml::from_array($data, $xml);
2517 logger('message: '.$msg, LOGGER_DATA);
2518 logger('send guid '.$guid, LOGGER_DEBUG);
2520 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2523 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2526 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2528 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2530 return $return_code;
2534 * @brief Sends a "share" message
2536 * @param array $owner the array of the item owner
2537 * @param array $contact Target of the communication
2539 * @return int The result of the transmission
2541 public static function send_share($owner,$contact) {
2543 $message = array("sender_handle" => self::my_handle($owner),
2544 "recipient_handle" => $contact["addr"]);
2546 return self::build_and_transmit($owner, $contact, "request", $message);
2550 * @brief sends an "unshare"
2552 * @param array $owner the array of the item owner
2553 * @param array $contact Target of the communication
2555 * @return int The result of the transmission
2557 public static function send_unshare($owner,$contact) {
2559 $message = array("post_guid" => $owner["guid"],
2560 "diaspora_handle" => self::my_handle($owner),
2561 "type" => "Person");
2563 return self::build_and_transmit($owner, $contact, "retraction", $message);
2567 * @brief Checks a message body if it is a reshare
2569 * @param string $body The message body that is to be check
2570 * @param bool $complete Should it be a complete check or a simple check?
2572 * @return array|bool Reshare details or "false" if no reshare
2574 public static function is_reshare($body, $complete = true) {
2575 $body = trim($body);
2577 // Skip if it isn't a pure repeated messages
2578 // Does it start with a share?
2579 if (strpos($body, "[share") > 0)
2582 // Does it end with a share?
2583 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2586 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2587 // Skip if there is no shared message in there
2588 if ($body == $attributes)
2591 // If we don't do the complete check we quit here
2596 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2597 if ($matches[1] != "")
2598 $guid = $matches[1];
2600 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2601 if ($matches[1] != "")
2602 $guid = $matches[1];
2605 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2606 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2609 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2610 $ret["root_guid"] = $guid;
2616 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2617 if ($matches[1] != "")
2618 $profile = $matches[1];
2620 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2621 if ($matches[1] != "")
2622 $profile = $matches[1];
2626 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2627 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2631 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2632 if ($matches[1] != "")
2633 $link = $matches[1];
2635 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2636 if ($matches[1] != "")
2637 $link = $matches[1];
2639 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2640 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2647 * @brief Sends a post
2649 * @param array $item The item that will be exported
2650 * @param array $owner the array of the item owner
2651 * @param array $contact Target of the communication
2652 * @param bool $public_batch Is it a public post?
2654 * @return int The result of the transmission
2656 public static function send_status($item, $owner, $contact, $public_batch = false) {
2658 $myaddr = self::my_handle($owner);
2660 $public = (($item["private"]) ? "false" : "true");
2662 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2664 // Detect a share element and do a reshare
2665 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2666 $message = array("root_diaspora_id" => $ret["root_handle"],
2667 "root_guid" => $ret["root_guid"],
2668 "guid" => $item["guid"],
2669 "diaspora_handle" => $myaddr,
2670 "public" => $public,
2671 "created_at" => $created,
2672 "provider_display_name" => $item["app"]);
2676 $title = $item["title"];
2677 $body = $item["body"];
2679 // convert to markdown
2680 $body = html_entity_decode(bb2diaspora($body));
2684 $body = "## ".html_entity_decode($title)."\n\n".$body;
2686 if ($item["attach"]) {
2687 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2689 $body .= "\n".t("Attachments:")."\n";
2690 foreach($matches as $mtch)
2691 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2695 $location = array();
2697 if ($item["location"] != "")
2698 $location["address"] = $item["location"];
2700 if ($item["coord"] != "") {
2701 $coord = explode(" ", $item["coord"]);
2702 $location["lat"] = $coord[0];
2703 $location["lng"] = $coord[1];
2706 $message = array("raw_message" => $body,
2707 "location" => $location,
2708 "guid" => $item["guid"],
2709 "diaspora_handle" => $myaddr,
2710 "public" => $public,
2711 "created_at" => $created,
2712 "provider_display_name" => $item["app"]);
2714 if (count($location) == 0)
2715 unset($message["location"]);
2717 $type = "status_message";
2720 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2724 * @brief Creates a "like" object
2726 * @param array $item The item that will be exported
2727 * @param array $owner the array of the item owner
2729 * @return array The data for a "like"
2731 private function construct_like($item, $owner) {
2733 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2734 dbesc($item["thr-parent"]));
2740 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2743 return(array("positive" => $positive,
2744 "guid" => $item["guid"],
2745 "target_type" => $target_type,
2746 "parent_guid" => $parent["guid"],
2747 "author_signature" => "",
2748 "diaspora_handle" => self::my_handle($owner)));
2752 * @brief Creates the object for a comment
2754 * @param array $item The item that will be exported
2755 * @param array $owner the array of the item owner
2757 * @return array The data for a comment
2759 private function construct_comment($item, $owner) {
2761 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2762 intval($item["parent"]),
2763 intval($item["parent"])
2771 $text = html_entity_decode(bb2diaspora($item["body"]));
2773 return(array("guid" => $item["guid"],
2774 "parent_guid" => $parent["guid"],
2775 "author_signature" => "",
2777 "diaspora_handle" => self::my_handle($owner)));
2781 * @brief Send a like or a comment
2783 * @param array $item The item that will be exported
2784 * @param array $owner the array of the item owner
2785 * @param array $contact Target of the communication
2786 * @param bool $public_batch Is it a public post?
2788 * @return int The result of the transmission
2790 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2792 if($item['verb'] === ACTIVITY_LIKE) {
2793 $message = self::construct_like($item, $owner);
2796 $message = self::construct_comment($item, $owner);
2803 $message["author_signature"] = self::signature($owner, $message);
2805 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2809 * @brief Creates a message from a signature record entry
2811 * @param array $item The item that will be exported
2812 * @param array $signature The entry of the "sign" record
2814 * @return string The message
2816 private function message_from_signature($item, $signature) {
2818 // Split the signed text
2819 $signed_parts = explode(";", $signature['signed_text']);
2821 if ($item["deleted"])
2822 $message = array("parent_author_signature" => "",
2823 "target_guid" => $signed_parts[0],
2824 "target_type" => $signed_parts[1],
2825 "sender_handle" => $signature['signer'],
2826 "target_author_signature" => $signature['signature']);
2827 elseif ($item['verb'] === ACTIVITY_LIKE)
2828 $message = array("positive" => $signed_parts[0],
2829 "guid" => $signed_parts[1],
2830 "target_type" => $signed_parts[2],
2831 "parent_guid" => $signed_parts[3],
2832 "parent_author_signature" => "",
2833 "author_signature" => $signature['signature'],
2834 "diaspora_handle" => $signed_parts[4]);
2836 // Remove the comment guid
2837 $guid = array_shift($signed_parts);
2839 // Remove the parent guid
2840 $parent_guid = array_shift($signed_parts);
2842 // Remove the handle
2843 $handle = array_pop($signed_parts);
2845 // Glue the parts together
2846 $text = implode(";", $signed_parts);
2848 $message = array("guid" => $guid,
2849 "parent_guid" => $parent_guid,
2850 "parent_author_signature" => "",
2851 "author_signature" => $signature['signature'],
2852 "text" => implode(";", $signed_parts),
2853 "diaspora_handle" => $handle);
2859 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
2861 * @param array $item The item that will be exported
2862 * @param array $owner the array of the item owner
2863 * @param array $contact Target of the communication
2864 * @param bool $public_batch Is it a public post?
2866 * @return int The result of the transmission
2868 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2870 if ($item["deleted"])
2871 return self::send_retraction($item, $owner, $contact, $public_batch, true);
2872 elseif ($item['verb'] === ACTIVITY_LIKE)
2877 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2879 // fetch the original signature
2881 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
2882 intval($item["id"]));
2885 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2891 // Old way - is used by the internal Friendica functions
2892 /// @todo Change all signatur storing functions to the new format
2893 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2894 $message = self::message_from_signature($item, $signature);
2896 $msg = json_decode($signature['signed_text'], true);
2899 if (is_array($msg)) {
2900 foreach ($msg AS $field => $data) {
2901 if (!$item["deleted"]) {
2902 if ($field == "author")
2903 $field = "diaspora_handle";
2904 if ($field == "parent_type")
2905 $field = "target_type";
2908 $message[$field] = $data;
2911 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2914 $message["parent_author_signature"] = self::signature($owner, $message);
2916 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2918 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2922 * @brief Sends a retraction (deletion) of a message, like or comment
2924 * @param array $item The item that will be exported
2925 * @param array $owner the array of the item owner
2926 * @param array $contact Target of the communication
2927 * @param bool $public_batch Is it a public post?
2928 * @param bool $relay Is the retraction transmitted from a relay?
2930 * @return int The result of the transmission
2932 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
2934 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
2936 // Check whether the retraction is for a top-level post or whether it's a relayable
2937 if ($item["uri"] !== $item["parent-uri"]) {
2938 $msg_type = "relayable_retraction";
2939 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2941 $msg_type = "signed_retraction";
2942 $target_type = "StatusMessage";
2945 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
2946 $signature = "parent_author_signature";
2948 $signature = "target_author_signature";
2950 $signed_text = $item["guid"].";".$target_type;
2952 $message = array("target_guid" => $item['guid'],
2953 "target_type" => $target_type,
2954 "sender_handle" => $itemaddr,
2955 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2957 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2959 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2963 * @brief Sends a mail
2965 * @param array $item The item that will be exported
2966 * @param array $owner The owner
2967 * @param array $contact Target of the communication
2969 * @return int The result of the transmission
2971 public static function send_mail($item, $owner, $contact) {
2973 $myaddr = self::my_handle($owner);
2975 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2976 intval($item["convid"]),
2977 intval($item["uid"])
2981 logger("conversation not found.");
2987 "guid" => $cnv["guid"],
2988 "subject" => $cnv["subject"],
2989 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2990 "diaspora_handle" => $cnv["creator"],
2991 "participant_handles" => $cnv["recips"]
2994 $body = bb2diaspora($item["body"]);
2995 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2997 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2998 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3001 "guid" => $item["guid"],
3002 "parent_guid" => $cnv["guid"],
3003 "parent_author_signature" => $sig,
3004 "author_signature" => $sig,
3006 "created_at" => $created,
3007 "diaspora_handle" => $myaddr,
3008 "conversation_guid" => $cnv["guid"]
3011 if ($item["reply"]) {
3015 $message = array("guid" => $cnv["guid"],
3016 "subject" => $cnv["subject"],
3017 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
3019 "diaspora_handle" => $cnv["creator"],
3020 "participant_handles" => $cnv["recips"]);
3022 $type = "conversation";
3025 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3029 * @brief Sends profile data
3031 * @param int $uid The user id
3033 public static function send_profile($uid) {
3038 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3039 AND `uid` = %d AND `rel` != %d",
3040 dbesc(NETWORK_DIASPORA),
3042 intval(CONTACT_IS_SHARING)
3047 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3049 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3050 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3051 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3060 $handle = $profile["addr"];
3061 $first = ((strpos($profile['name'],' ')
3062 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3063 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3064 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3065 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3066 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3067 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3069 if ($searchable === 'true') {
3070 $dob = '1000-00-00';
3072 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3073 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3075 $about = $profile['about'];
3076 $about = strip_tags(bbcode($about));
3078 $location = formatted_location($profile);
3080 if ($profile['pub_keywords']) {
3081 $kw = str_replace(',',' ',$profile['pub_keywords']);
3082 $kw = str_replace(' ',' ',$kw);
3083 $arr = explode(' ',$profile['pub_keywords']);
3085 for($x = 0; $x < 5; $x ++) {
3087 $tags .= '#'. trim($arr[$x]) .' ';
3091 $tags = trim($tags);
3094 $message = array("diaspora_handle" => $handle,
3095 "first_name" => $first,
3096 "last_name" => $last,
3097 "image_url" => $large,
3098 "image_url_medium" => $medium,
3099 "image_url_small" => $small,
3101 "gender" => $profile['gender'],
3103 "location" => $location,
3104 "searchable" => $searchable,
3105 "tag_string" => $tags);
3107 foreach($recips as $recip)
3108 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3112 * @brief Stores the signature for likes that are created on our system
3114 * @param array $contact The contact array of the "like"
3115 * @param int $post_id The post id of the "like"
3117 * @return bool Success
3119 public static function store_like_signature($contact, $post_id) {
3121 $enabled = intval(get_config('system','diaspora_enabled'));
3123 logger('Diaspora support disabled, not storing like signature', LOGGER_DEBUG);
3127 // Is the contact the owner? Then fetch the private key
3128 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3129 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3133 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3137 $contact["uprvkey"] = $r[0]['prvkey'];
3139 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3143 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3146 $message = self::construct_like($r[0], $contact);
3147 $message["author_signature"] = self::signature($contact, $message);
3149 // In the future we will store the signature more flexible to support new fields.
3150 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3151 // (We are transmitting this data here via DFRN)
3153 $signed_text = $message["positive"].";".$message["guid"].";".$message["target_type"].";".
3154 $message["parent_guid"].";".$message["diaspora_handle"];
3156 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3158 dbesc($signed_text),
3159 dbesc($message["author_signature"]),
3160 dbesc($message["diaspora_handle"])
3163 // This here will replace the lines above, once Diaspora changed its protocol
3164 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3165 // intval($message_id),
3166 // dbesc(json_encode($message))
3169 logger('Stored diaspora like signature');
3174 * @brief Stores the signature for comments that are created on our system
3176 * @param array $item The item array of the comment
3177 * @param array $contact The contact array of the item owner
3178 * @param string $uprvkey The private key of the sender
3179 * @param int $message_id The message id of the comment
3181 * @return bool Success
3183 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3185 if ($uprvkey == "") {
3186 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3190 $enabled = intval(get_config('system','diaspora_enabled'));
3192 logger('Diaspora support disabled, not storing comment signature', LOGGER_DEBUG);
3196 $contact["uprvkey"] = $uprvkey;
3198 $message = self::construct_comment($item, $contact);
3199 $message["author_signature"] = self::signature($contact, $message);
3201 // In the future we will store the signature more flexible to support new fields.
3202 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3203 // (We are transmitting this data here via DFRN)
3204 $signed_text = $message["guid"].";".$message["parent_guid"].";".
3205 $message["text"].";".$message["diaspora_handle"];
3207 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3208 intval($message_id),
3209 dbesc($signed_text),
3210 dbesc($message["author_signature"]),
3211 dbesc($message["diaspora_handle"])
3214 // This here will replace the lines above, once Diaspora changed its protocol
3215 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3216 // intval($message_id),
3217 // dbesc(json_encode($message))
3220 logger('Stored diaspora comment signature');