3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
7 /// @todo reshare of some reshare doesn't work well, see guid c1d534b0ed19013358694860008dbc6c
8 // 14f571c0f244013358694860008dbc6c
10 require_once("include/items.php");
11 require_once("include/bb2diaspora.php");
12 require_once("include/Scrape.php");
13 require_once("include/Contact.php");
14 require_once("include/Photo.php");
15 require_once("include/socgraph.php");
16 require_once("include/group.php");
17 require_once("include/xml.php");
18 require_once("include/datetime.php");
19 require_once("include/queue_fn.php");
22 * @brief This class contain functions to create and send Diaspora XML files
28 * @brief Return a list of relay servers
30 * This is an experimental Diaspora feature.
32 * @return array of relay servers
34 public static function relay_list() {
36 $serverdata = get_config("system", "relay_server");
37 if ($serverdata == "")
42 $servers = explode(",", $serverdata);
44 foreach($servers AS $server) {
45 $server = trim($server);
46 $batch = $server."/receive/public";
48 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
51 $addr = "relay@".str_replace("http://", "", normalise_link($server));
53 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
54 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
59 dbesc(normalise_link($server)),
61 dbesc(NETWORK_DIASPORA),
62 intval(CONTACT_IS_FOLLOWER),
63 dbesc(datetime_convert()),
64 dbesc(datetime_convert()),
65 dbesc(datetime_convert())
68 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
70 $relay[] = $relais[0];
72 $relay[] = $relais[0];
79 * @brief repairs a signature that was double encoded
81 * The function is unused at the moment. It was copied from the old implementation.
83 * @param string $signature The signature
84 * @param string $handle The handle of the signature owner
85 * @param integer $level This value is only set inside this function to avoid endless loops
87 * @return string the repaired signature
89 private function repair_signature($signature, $handle = "", $level = 1) {
94 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
95 $signature = base64_decode($signature);
96 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
98 // Do a recursive call to be able to fix even multiple levels
100 $signature = self::repair_signature($signature, $handle, ++$level);
107 * @brief: Decodes incoming Diaspora message
109 * @param array $importer Array of the importer user
110 * @param string $xml urldecoded Diaspora salmon
113 * 'message' -> decoded Diaspora XML message
114 * 'author' -> author diaspora handle
115 * 'key' -> author public key (converted to pkcs#8)
117 public static function decode($importer, $xml) {
120 $basedom = parse_xml_string($xml);
122 if (!is_object($basedom))
125 $children = $basedom->children('https://joindiaspora.com/protocol');
127 if($children->header) {
129 $author_link = str_replace('acct:','',$children->header->author_id);
132 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
134 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
135 $ciphertext = base64_decode($encrypted_header->ciphertext);
137 $outer_key_bundle = '';
138 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
140 $j_outer_key_bundle = json_decode($outer_key_bundle);
142 $outer_iv = base64_decode($j_outer_key_bundle->iv);
143 $outer_key = base64_decode($j_outer_key_bundle->key);
145 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
148 $decrypted = pkcs5_unpad($decrypted);
150 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
151 $idom = parse_xml_string($decrypted,false);
153 $inner_iv = base64_decode($idom->iv);
154 $inner_aes_key = base64_decode($idom->aes_key);
156 $author_link = str_replace('acct:','',$idom->author_id);
159 $dom = $basedom->children(NAMESPACE_SALMON_ME);
161 // figure out where in the DOM tree our data is hiding
163 if($dom->provenance->data)
164 $base = $dom->provenance;
165 elseif($dom->env->data)
171 logger('unable to locate salmon data in xml');
172 http_status_exit(400);
176 // Stash the signature away for now. We have to find their key or it won't be good for anything.
177 $signature = base64url_decode($base->sig);
181 // strip whitespace so our data element will return to one big base64 blob
182 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
185 // stash away some other stuff for later
187 $type = $base->data[0]->attributes()->type[0];
188 $keyhash = $base->sig[0]->attributes()->keyhash[0];
189 $encoding = $base->encoding;
193 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
197 $data = base64url_decode($data);
201 $inner_decrypted = $data;
204 // Decode the encrypted blob
206 $inner_encrypted = base64_decode($data);
207 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
208 $inner_decrypted = pkcs5_unpad($inner_decrypted);
212 logger('Could not retrieve author URI.');
213 http_status_exit(400);
215 // Once we have the author URI, go to the web and try to find their public key
216 // (first this will look it up locally if it is in the fcontact cache)
217 // This will also convert diaspora public key from pkcs#1 to pkcs#8
219 logger('Fetching key for '.$author_link);
220 $key = self::key($author_link);
223 logger('Could not retrieve author key.');
224 http_status_exit(400);
227 $verify = rsa_verify($signed_data,$signature,$key);
230 logger('Message did not verify. Discarding.');
231 http_status_exit(400);
234 logger('Message verified.');
236 return array('message' => (string)$inner_decrypted,
237 'author' => unxmlify($author_link),
238 'key' => (string)$key);
244 * @brief Dispatches public messages and find the fitting receivers
246 * @param array $msg The post that will be dispatched
248 * @return int The message id of the generated message, "true" or "false" if there was an error
250 public static function dispatch_public($msg) {
252 $enabled = intval(get_config("system", "diaspora_enabled"));
254 logger("diaspora is disabled");
258 // Use a dummy importer to import the data for the public copy
259 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
260 $message_id = self::dispatch($importer,$msg);
262 // Now distribute it to the followers
263 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
264 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
265 AND NOT `account_expired` AND NOT `account_removed`",
266 dbesc(NETWORK_DIASPORA),
267 dbesc($msg["author"])
271 logger("delivering to: ".$rr["username"]);
272 self::dispatch($rr,$msg);
275 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
281 * @brief Dispatches the different message types to the different functions
283 * @param array $importer Array of the importer user
284 * @param array $msg The post that will be dispatched
286 * @return int The message id of the generated message, "true" or "false" if there was an error
288 public static function dispatch($importer, $msg) {
290 // The sender is the handle of the contact that sent the message.
291 // This will often be different with relayed messages (for example "like" and "comment")
292 $sender = $msg["author"];
294 if (!diaspora::valid_posting($msg, $fields)) {
295 logger("Invalid posting");
299 $type = $fields->getName();
301 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
304 case "account_deletion":
305 return self::receive_account_deletion($importer, $fields);
308 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
311 return self::receive_contact_request($importer, $fields);
314 return self::receive_conversation($importer, $msg, $fields);
317 return self::receive_like($importer, $sender, $fields);
320 return self::receive_message($importer, $fields);
322 case "participation": // Not implemented
323 return self::receive_participation($importer, $fields);
325 case "photo": // Not implemented
326 return self::receive_photo($importer, $fields);
328 case "poll_participation": // Not implemented
329 return self::receive_poll_participation($importer, $fields);
332 return self::receive_profile($importer, $fields);
335 return self::receive_reshare($importer, $fields, $msg["message"]);
338 return self::receive_retraction($importer, $sender, $fields);
340 case "status_message":
341 return self::receive_status_message($importer, $fields, $msg["message"]);
344 logger("Unknown message type ".$type);
352 * @brief Checks if a posting is valid and fetches the data fields.
354 * This function does not only check the signature.
355 * It also does the conversion between the old and the new diaspora format.
357 * @param array $msg Array with the XML, the sender handle and the sender signature
358 * @param object $fields SimpleXML object that contains the posting when it is valid
360 * @return bool Is the posting valid?
362 private function valid_posting($msg, &$fields) {
364 $data = parse_xml_string($msg["message"], false);
366 if (!is_object($data))
369 $first_child = $data->getName();
371 // Is this the new or the old version?
372 if ($data->getName() == "XML") {
374 foreach ($data->post->children() as $child)
381 $type = $element->getName();
384 // All retractions are handled identically from now on.
385 // In the new version there will only be "retraction".
386 if (in_array($type, array("signed_retraction", "relayable_retraction")))
387 $type = "retraction";
389 if ($type == "request")
392 $fields = new SimpleXMLElement("<".$type."/>");
396 foreach ($element->children() AS $fieldname => $entry) {
398 // Translation for the old XML structure
399 if ($fieldname == "diaspora_handle")
400 $fieldname = "author";
402 if ($fieldname == "participant_handles")
403 $fieldname = "participants";
405 if (in_array($type, array("like", "participation"))) {
406 if ($fieldname == "target_type")
407 $fieldname = "parent_type";
410 if ($fieldname == "sender_handle")
411 $fieldname = "author";
413 if ($fieldname == "recipient_handle")
414 $fieldname = "recipient";
416 if ($fieldname == "root_diaspora_id")
417 $fieldname = "root_author";
419 if ($type == "retraction") {
420 if ($fieldname == "post_guid")
421 $fieldname = "target_guid";
423 if ($fieldname == "type")
424 $fieldname = "target_type";
428 if ($fieldname == "author_signature")
429 $author_signature = base64_decode($entry);
430 elseif ($fieldname == "parent_author_signature")
431 $parent_author_signature = base64_decode($entry);
432 elseif ($fieldname != "target_author_signature") {
433 if ($signed_data != "") {
435 $signed_data_parent .= ";";
438 $signed_data .= $entry;
440 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
441 ($orig_type == "relayable_retraction"))
442 xml::copy($entry, $fields, $fieldname);
445 // This is something that shouldn't happen at all.
446 if (in_array($type, array("status_message", "reshare", "profile")))
447 if ($msg["author"] != $fields->author) {
448 logger("Message handle is not the same as envelope sender. Quitting this message.");
452 // Only some message types have signatures. So we quit here for the other types.
453 if (!in_array($type, array("comment", "message", "like")))
456 // No author_signature? This is a must, so we quit.
457 if (!isset($author_signature))
460 if (isset($parent_author_signature)) {
461 $key = self::key($msg["author"]);
463 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
467 $key = self::key($fields->author);
469 return rsa_verify($signed_data, $author_signature, $key, "sha256");
473 * @brief Fetches the public key for a given handle
475 * @param string $handle The handle
477 * @return string The public key
479 private function key($handle) {
480 $handle = strval($handle);
482 logger("Fetching diaspora key for: ".$handle);
484 $r = self::person_by_handle($handle);
492 * @brief Fetches data for a given handle
494 * @param string $handle The handle
496 * @return array the queried data
498 private function person_by_handle($handle) {
500 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
501 dbesc(NETWORK_DIASPORA),
506 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
508 // update record occasionally so it doesn't get stale
509 $d = strtotime($person["updated"]." +00:00");
510 if ($d < strtotime("now - 14 days"))
514 if (!$person OR $update) {
515 logger("create or refresh", LOGGER_DEBUG);
516 $r = probe_url($handle, PROBE_DIASPORA);
518 // Note that Friendica contacts will return a "Diaspora person"
519 // if Diaspora connectivity is enabled on their server
520 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
521 self::add_fcontact($r, $update);
529 * @brief Updates the fcontact table
531 * @param array $arr The fcontact data
532 * @param bool $update Update or insert?
534 * @return string The id of the fcontact entry
536 private function add_fcontact($arr, $update = false) {
539 $r = q("UPDATE `fcontact` SET
552 WHERE `url` = '%s' AND `network` = '%s'",
554 dbesc($arr["photo"]),
555 dbesc($arr["request"]),
558 dbesc($arr["batch"]),
559 dbesc($arr["notify"]),
561 dbesc($arr["confirm"]),
562 dbesc($arr["alias"]),
563 dbesc($arr["pubkey"]),
564 dbesc(datetime_convert()),
566 dbesc($arr["network"])
569 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
570 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
571 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
574 dbesc($arr["photo"]),
575 dbesc($arr["request"]),
578 dbesc($arr["batch"]),
579 dbesc($arr["notify"]),
581 dbesc($arr["confirm"]),
582 dbesc($arr["network"]),
583 dbesc($arr["alias"]),
584 dbesc($arr["pubkey"]),
585 dbesc(datetime_convert())
593 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
595 * @param int $contact_id The id in the contact table
596 * @param int $gcontact_id The id in the gcontact table
598 * @return string the handle
600 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
603 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
605 if ($gcontact_id != 0) {
606 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
607 intval($gcontact_id));
609 return $r[0]["addr"];
612 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
613 intval($contact_id));
617 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
619 if($contact['addr'] != "")
620 $handle = $contact['addr'];
622 $baseurl_start = strpos($contact['url'],'://') + 3;
623 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
624 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
625 $handle = $contact['nick'].'@'.$baseurl;
633 * @brief Get a contact id for a given handle
635 * @param int $uid The user id
636 * @param string $handle The handle in the format user@domain.tld
638 * @return The contact id
640 private function contact_by_handle($uid, $handle) {
641 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
649 $handle_parts = explode("@", $handle);
650 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
651 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
663 * @brief Check if posting is allowed for this contact
665 * @param array $importer Array of the importer user
666 * @param array $contact The contact that is checked
667 * @param bool $is_comment Is the check for a comment?
669 * @return bool is the contact allowed to post?
671 private function post_allow($importer, $contact, $is_comment = false) {
673 // perhaps we were already sharing with this person. Now they're sharing with us.
674 // That makes us friends.
675 // Normally this should have handled by getting a request - but this could get lost
676 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
677 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
678 intval(CONTACT_IS_FRIEND),
679 intval($contact["id"]),
680 intval($importer["uid"])
682 $contact["rel"] = CONTACT_IS_FRIEND;
683 logger("defining user ".$contact["nick"]." as friend");
686 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
688 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
690 if($contact["rel"] == CONTACT_IS_FOLLOWER)
691 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
694 // Messages for the global users are always accepted
695 if ($importer["uid"] == 0)
702 * @brief Fetches the contact id for a handle and checks if posting is allowed
704 * @param array $importer Array of the importer user
705 * @param string $handle The checked handle in the format user@domain.tld
706 * @param bool $is_comment Is the check for a comment?
708 * @return array The contact data
710 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
711 $contact = self::contact_by_handle($importer["uid"], $handle);
713 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
717 if (!self::post_allow($importer, $contact, $is_comment)) {
718 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
725 * @brief Does the message already exists on the system?
727 * @param int $uid The user id
728 * @param string $guid The guid of the message
730 * @return int|bool message id if the message already was stored into the system - or false.
732 private function message_exists($uid, $guid) {
733 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
739 logger("message ".$guid." already exists for user ".$uid);
747 * @brief Checks for links to posts in a message
749 * @param array $item The item array
751 private function fetch_guid($item) {
752 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
753 function ($match) use ($item){
754 return(self::fetch_guid_sub($match, $item));
759 * @brief sub function of "fetch_guid" which checks for links in messages
761 * @param array $match array containing a link that has to be checked for a message link
762 * @param array $item The item array
764 private function fetch_guid_sub($match, $item) {
765 if (!self::store_by_guid($match[1], $item["author-link"]))
766 self::store_by_guid($match[1], $item["owner-link"]);
770 * @brief Fetches an item with a given guid from a given server
772 * @param string $guid the message guid
773 * @param string $server The server address
774 * @param int $uid The user id of the user
776 * @return int the message id of the stored message or false
778 private function store_by_guid($guid, $server, $uid = 0) {
779 $serverparts = parse_url($server);
780 $server = $serverparts["scheme"]."://".$serverparts["host"];
782 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
784 $msg = self::message($guid, $server);
789 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
791 // Now call the dispatcher
792 return self::dispatch_public($msg);
796 * @brief Fetches a message from a server
798 * @param string $guid message guid
799 * @param string $server The url of the server
800 * @param int $level Endless loop prevention
803 * 'message' => The message XML
804 * 'author' => The author handle
805 * 'key' => The public key of the author
807 private function message($guid, $server, $level = 0) {
812 // This will work for Diaspora and newer Friendica servers
813 $source_url = $server."/p/".$guid.".xml";
814 $x = fetch_url($source_url);
818 $source_xml = parse_xml_string($x, false);
820 if (!is_object($source_xml))
823 if ($source_xml->post->reshare) {
824 // Reshare of a reshare - old Diaspora version
825 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
826 } elseif ($source_xml->getName() == "reshare") {
827 // Reshare of a reshare - new Diaspora version
828 return self::message($source_xml->root_guid, $server, ++$level);
833 // Fetch the author - for the old and the new Diaspora version
834 if ($source_xml->post->status_message->diaspora_handle)
835 $author = (string)$source_xml->post->status_message->diaspora_handle;
836 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
837 $author = (string)$source_xml->author;
839 // If this isn't a "status_message" then quit
843 $msg = array("message" => $x, "author" => $author);
845 $msg["key"] = self::key($msg["author"]);
851 * @brief Fetches the item record of a given guid
853 * @param int $uid The user id
854 * @param string $guid message guid
855 * @param string $author The handle of the item
856 * @param array $contact The contact of the item owner
858 * @return array the item record
860 private function parent_item($uid, $guid, $author, $contact) {
861 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
862 `author-name`, `author-link`, `author-avatar`,
863 `owner-name`, `owner-link`, `owner-avatar`
864 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
865 intval($uid), dbesc($guid));
868 $result = self::store_by_guid($guid, $contact["url"], $uid);
871 $person = self::person_by_handle($author);
872 $result = self::store_by_guid($guid, $person["url"], $uid);
876 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
878 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
879 `author-name`, `author-link`, `author-avatar`,
880 `owner-name`, `owner-link`, `owner-avatar`
881 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
882 intval($uid), dbesc($guid));
887 logger("parent item not found: parent: ".$guid." - user: ".$uid);
890 logger("parent item found: parent: ".$guid." - user: ".$uid);
896 * @brief returns contact details
898 * @param array $contact The default contact if the person isn't found
899 * @param array $person The record of the person
900 * @param int $uid The user id
903 * 'cid' => contact id
904 * 'network' => network type
906 private function author_contact_by_url($contact, $person, $uid) {
908 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
909 dbesc(normalise_link($person["url"])), intval($uid));
912 $network = $r[0]["network"];
914 $cid = $contact["id"];
915 $network = NETWORK_DIASPORA;
918 return (array("cid" => $cid, "network" => $network));
922 * @brief Is the profile a hubzilla profile?
924 * @param string $url The profile link
926 * @return bool is it a hubzilla server?
928 public static function is_redmatrix($url) {
929 return(strstr($url, "/channel/"));
933 * @brief Generate a post link with a given handle and message guid
935 * @param string $addr The user handle
936 * @param string $guid message guid
938 * @return string the post link
940 private function plink($addr, $guid) {
941 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
945 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
947 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
948 // So we try another way as well.
949 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
951 $r[0]["network"] = $s[0]["network"];
953 if ($r[0]["network"] == NETWORK_DFRN)
954 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
956 if (self::is_redmatrix($r[0]["url"]))
957 return $r[0]["url"]."/?f=&mid=".$guid;
959 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
963 * @brief Processes an account deletion
965 * @param array $importer Array of the importer user
966 * @param object $data The message object
968 * @return bool Success
970 private function receive_account_deletion($importer, $data) {
972 /// @todo Account deletion should remove the contact from the global contacts as well
974 $author = notags(unxmlify($data->author));
976 $contact = self::contact_by_handle($importer["uid"], $author);
978 logger("cannot find contact for author: ".$author);
982 // We now remove the contact
983 contact_remove($contact["id"]);
988 * @brief Processes an incoming comment
990 * @param array $importer Array of the importer user
991 * @param string $sender The sender of the message
992 * @param object $data The message object
993 * @param string $xml The original XML of the message
995 * @return int The message id of the generated comment or "false" if there was an error
997 private function receive_comment($importer, $sender, $data, $xml) {
998 $guid = notags(unxmlify($data->guid));
999 $parent_guid = notags(unxmlify($data->parent_guid));
1000 $text = unxmlify($data->text);
1001 $author = notags(unxmlify($data->author));
1003 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1007 $message_id = self::message_exists($importer["uid"], $guid);
1011 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1015 $person = self::person_by_handle($author);
1016 if (!is_array($person)) {
1017 logger("unable to find author details");
1021 // Fetch the contact id - if we know this contact
1022 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1024 $datarray = array();
1026 $datarray["uid"] = $importer["uid"];
1027 $datarray["contact-id"] = $author_contact["cid"];
1028 $datarray["network"] = $author_contact["network"];
1030 $datarray["author-name"] = $person["name"];
1031 $datarray["author-link"] = $person["url"];
1032 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1034 $datarray["owner-name"] = $contact["name"];
1035 $datarray["owner-link"] = $contact["url"];
1036 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1038 $datarray["guid"] = $guid;
1039 $datarray["uri"] = $author.":".$guid;
1041 $datarray["type"] = "remote-comment";
1042 $datarray["verb"] = ACTIVITY_POST;
1043 $datarray["gravity"] = GRAVITY_COMMENT;
1044 $datarray["parent-uri"] = $parent_item["uri"];
1046 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1047 $datarray["object"] = $xml;
1049 $datarray["body"] = diaspora2bb($text);
1051 self::fetch_guid($datarray);
1053 $message_id = item_store($datarray);
1056 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1058 // If we are the origin of the parent we store the original data and notify our followers
1059 if($message_id AND $parent_item["origin"]) {
1061 // Formerly we stored the signed text, the signature and the author in different fields.
1062 // We now store the raw data so that we are more flexible.
1063 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1064 intval($message_id),
1065 dbesc(json_encode($data))
1069 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1076 * @brief processes and stores private messages
1078 * @param array $importer Array of the importer user
1079 * @param array $contact The contact of the message
1080 * @param object $data The message object
1081 * @param array $msg Array of the processed message, author handle and key
1082 * @param object $mesg The private message
1083 * @param array $conversation The conversation record to which this message belongs
1085 * @return bool "true" if it was successful
1087 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1088 $guid = notags(unxmlify($data->guid));
1089 $subject = notags(unxmlify($data->subject));
1090 $author = notags(unxmlify($data->author));
1094 $msg_guid = notags(unxmlify($mesg->guid));
1095 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1096 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1097 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1098 $msg_text = unxmlify($mesg->text);
1099 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1101 // "diaspora_handle" is the element name from the old version
1102 // "author" is the element name from the new version
1104 $msg_author = notags(unxmlify($mesg->author));
1105 elseif ($mesg->diaspora_handle)
1106 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1110 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1112 if($msg_conversation_guid != $guid) {
1113 logger("message conversation guid does not belong to the current conversation.");
1117 $body = diaspora2bb($msg_text);
1118 $message_uri = $msg_author.":".$msg_guid;
1120 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1122 $author_signature = base64_decode($msg_author_signature);
1124 if(strcasecmp($msg_author,$msg["author"]) == 0) {
1128 $person = self::person_by_handle($msg_author);
1130 if (is_array($person) && x($person, "pubkey"))
1131 $key = $person["pubkey"];
1133 logger("unable to find author details");
1138 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1139 logger("verification failed.");
1143 if($msg_parent_author_signature) {
1144 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1146 $parent_author_signature = base64_decode($msg_parent_author_signature);
1150 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1151 logger("owner verification failed.");
1156 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1160 logger("duplicate message already delivered.", LOGGER_DEBUG);
1164 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1165 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1166 intval($importer["uid"]),
1168 intval($conversation["id"]),
1169 dbesc($person["name"]),
1170 dbesc($person["photo"]),
1171 dbesc($person["url"]),
1172 intval($contact["id"]),
1177 dbesc($message_uri),
1178 dbesc($author.":".$guid),
1179 dbesc($msg_created_at)
1182 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1183 dbesc(datetime_convert()),
1184 intval($conversation["id"])
1188 "type" => NOTIFY_MAIL,
1189 "notify_flags" => $importer["notify-flags"],
1190 "language" => $importer["language"],
1191 "to_name" => $importer["username"],
1192 "to_email" => $importer["email"],
1193 "uid" =>$importer["uid"],
1194 "item" => array("subject" => $subject, "body" => $body),
1195 "source_name" => $person["name"],
1196 "source_link" => $person["url"],
1197 "source_photo" => $person["thumb"],
1198 "verb" => ACTIVITY_POST,
1205 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1207 * @param array $importer Array of the importer user
1208 * @param array $msg Array of the processed message, author handle and key
1209 * @param object $data The message object
1211 * @return bool Success
1213 private function receive_conversation($importer, $msg, $data) {
1214 $guid = notags(unxmlify($data->guid));
1215 $subject = notags(unxmlify($data->subject));
1216 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1217 $author = notags(unxmlify($data->author));
1218 $participants = notags(unxmlify($data->participants));
1220 $messages = $data->message;
1222 if (!count($messages)) {
1223 logger("empty conversation");
1227 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1231 $conversation = null;
1233 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1234 intval($importer["uid"]),
1238 $conversation = $c[0];
1240 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1241 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1242 intval($importer["uid"]),
1245 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1246 dbesc(datetime_convert()),
1248 dbesc($participants)
1251 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1252 intval($importer["uid"]),
1257 $conversation = $c[0];
1259 if (!$conversation) {
1260 logger("unable to create conversation.");
1264 foreach($messages as $mesg)
1265 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1271 * @brief Creates the body for a "like" message
1273 * @param array $contact The contact that send us the "like"
1274 * @param array $parent_item The item array of the parent item
1275 * @param string $guid message guid
1277 * @return string the body
1279 private function construct_like_body($contact, $parent_item, $guid) {
1280 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1282 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1283 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1284 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1286 return sprintf($bodyverb, $ulink, $alink, $plink);
1290 * @brief Creates a XML object for a "like"
1292 * @param array $importer Array of the importer user
1293 * @param array $parent_item The item array of the parent item
1295 * @return string The XML
1297 private function construct_like_object($importer, $parent_item) {
1298 $objtype = ACTIVITY_OBJ_NOTE;
1299 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1300 $parent_body = $parent_item["body"];
1302 $xmldata = array("object" => array("type" => $objtype,
1304 "id" => $parent_item["uri"],
1307 "content" => $parent_body));
1309 return xml::from_array($xmldata, $xml, true);
1313 * @brief Processes "like" messages
1315 * @param array $importer Array of the importer user
1316 * @param string $sender The sender of the message
1317 * @param object $data The message object
1319 * @return int The message id of the generated like or "false" if there was an error
1321 private function receive_like($importer, $sender, $data) {
1322 $positive = notags(unxmlify($data->positive));
1323 $guid = notags(unxmlify($data->guid));
1324 $parent_type = notags(unxmlify($data->parent_type));
1325 $parent_guid = notags(unxmlify($data->parent_guid));
1326 $author = notags(unxmlify($data->author));
1328 // likes on comments aren't supported by Diaspora - only on posts
1329 // But maybe this will be supported in the future, so we will accept it.
1330 if (!in_array($parent_type, array("Post", "Comment")))
1333 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1337 $message_id = self::message_exists($importer["uid"], $guid);
1341 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1345 $person = self::person_by_handle($author);
1346 if (!is_array($person)) {
1347 logger("unable to find author details");
1351 // Fetch the contact id - if we know this contact
1352 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1354 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1355 // We would accept this anyhow.
1356 if ($positive == "true")
1357 $verb = ACTIVITY_LIKE;
1359 $verb = ACTIVITY_DISLIKE;
1361 $datarray = array();
1363 $datarray["uid"] = $importer["uid"];
1364 $datarray["contact-id"] = $author_contact["cid"];
1365 $datarray["network"] = $author_contact["network"];
1367 $datarray["author-name"] = $person["name"];
1368 $datarray["author-link"] = $person["url"];
1369 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1371 $datarray["owner-name"] = $contact["name"];
1372 $datarray["owner-link"] = $contact["url"];
1373 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1375 $datarray["guid"] = $guid;
1376 $datarray["uri"] = $author.":".$guid;
1378 $datarray["type"] = "activity";
1379 $datarray["verb"] = $verb;
1380 $datarray["gravity"] = GRAVITY_LIKE;
1381 $datarray["parent-uri"] = $parent_item["uri"];
1383 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1384 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1386 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1388 $message_id = item_store($datarray);
1391 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1393 // If we are the origin of the parent we store the original data and notify our followers
1394 if($message_id AND $parent_item["origin"]) {
1396 // Formerly we stored the signed text, the signature and the author in different fields.
1397 // We now store the raw data so that we are more flexible.
1398 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1399 intval($message_id),
1400 dbesc(json_encode($data))
1404 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1411 * @brief Processes private messages
1413 * @param array $importer Array of the importer user
1414 * @param object $data The message object
1416 * @return bool Success?
1418 private function receive_message($importer, $data) {
1419 $guid = notags(unxmlify($data->guid));
1420 $parent_guid = notags(unxmlify($data->parent_guid));
1421 $text = unxmlify($data->text);
1422 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1423 $author = notags(unxmlify($data->author));
1424 $conversation_guid = notags(unxmlify($data->conversation_guid));
1426 $contact = self::allowed_contact_by_handle($importer, $author, true);
1430 $conversation = null;
1432 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1433 intval($importer["uid"]),
1434 dbesc($conversation_guid)
1437 $conversation = $c[0];
1439 logger("conversation not available.");
1445 $body = diaspora2bb($text);
1446 $message_uri = $author.":".$guid;
1448 $person = self::person_by_handle($author);
1450 logger("unable to find author details");
1454 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1455 dbesc($message_uri),
1456 intval($importer["uid"])
1459 logger("duplicate message already delivered.", LOGGER_DEBUG);
1463 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1464 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1465 intval($importer["uid"]),
1467 intval($conversation["id"]),
1468 dbesc($person["name"]),
1469 dbesc($person["photo"]),
1470 dbesc($person["url"]),
1471 intval($contact["id"]),
1472 dbesc($conversation["subject"]),
1476 dbesc($message_uri),
1477 dbesc($author.":".$parent_guid),
1481 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1482 dbesc(datetime_convert()),
1483 intval($conversation["id"])
1490 * @brief Processes participations - unsupported by now
1492 * @param array $importer Array of the importer user
1493 * @param object $data The message object
1495 * @return bool always true
1497 private function receive_participation($importer, $data) {
1498 // I'm not sure if we can fully support this message type
1503 * @brief Processes photos - unneeded
1505 * @param array $importer Array of the importer user
1506 * @param object $data The message object
1508 * @return bool always true
1510 private function receive_photo($importer, $data) {
1511 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1516 * @brief Processes poll participations - unssupported
1518 * @param array $importer Array of the importer user
1519 * @param object $data The message object
1521 * @return bool always true
1523 private function receive_poll_participation($importer, $data) {
1524 // We don't support polls by now
1529 * @brief Processes incoming profile updates
1531 * @param array $importer Array of the importer user
1532 * @param object $data The message object
1534 * @return bool Success
1536 private function receive_profile($importer, $data) {
1537 $author = notags(unxmlify($data->author));
1539 $contact = self::contact_by_handle($importer["uid"], $author);
1543 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1544 $image_url = unxmlify($data->image_url);
1545 $birthday = unxmlify($data->birthday);
1546 $location = diaspora2bb(unxmlify($data->location));
1547 $about = diaspora2bb(unxmlify($data->bio));
1548 $gender = unxmlify($data->gender);
1549 $searchable = (unxmlify($data->searchable) == "true");
1550 $nsfw = (unxmlify($data->nsfw) == "true");
1551 $tags = unxmlify($data->tag_string);
1553 $tags = explode("#", $tags);
1555 $keywords = array();
1556 foreach ($tags as $tag) {
1557 $tag = trim(strtolower($tag));
1562 $keywords = implode(", ", $keywords);
1564 $handle_parts = explode("@", $author);
1565 $nick = $handle_parts[0];
1568 $name = $handle_parts[0];
1570 if( preg_match("|^https?://|", $image_url) === 0)
1571 $image_url = "http://".$handle_parts[1].$image_url;
1573 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1575 // Generic birthday. We don't know the timezone. The year is irrelevant.
1577 $birthday = str_replace("1000", "1901", $birthday);
1579 if ($birthday != "")
1580 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1582 // this is to prevent multiple birthday notifications in a single year
1583 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1585 if(substr($birthday,5) === substr($contact["bd"],5))
1586 $birthday = $contact["bd"];
1588 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1589 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1593 dbesc(datetime_convert()),
1599 intval($contact["id"]),
1600 intval($importer["uid"])
1604 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1605 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1608 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1609 "photo" => $image_url, "name" => $name, "location" => $location,
1610 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1611 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1612 "hide" => !$searchable, "nsfw" => $nsfw);
1614 update_gcontact($gcontact);
1616 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1622 * @brief Processes incoming friend requests
1624 * @param array $importer Array of the importer user
1625 * @param array $contact The contact that send the request
1627 private function receive_request_make_friend($importer, $contact) {
1631 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1632 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1633 intval(CONTACT_IS_FRIEND),
1634 intval($contact["id"]),
1635 intval($importer["uid"])
1638 // send notification
1640 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1641 intval($importer["uid"])
1644 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1646 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1647 intval($importer["uid"])
1650 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1652 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1655 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1656 $arr["uid"] = $importer["uid"];
1657 $arr["contact-id"] = $self[0]["id"];
1659 $arr["type"] = 'wall';
1660 $arr["gravity"] = 0;
1662 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1663 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1664 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1665 $arr["verb"] = ACTIVITY_FRIEND;
1666 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1668 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1669 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1670 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1671 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1673 $arr["object"] = self::construct_new_friend_object($contact);
1675 $arr["last-child"] = 1;
1677 $arr["allow_cid"] = $user[0]["allow_cid"];
1678 $arr["allow_gid"] = $user[0]["allow_gid"];
1679 $arr["deny_cid"] = $user[0]["deny_cid"];
1680 $arr["deny_gid"] = $user[0]["deny_gid"];
1682 $i = item_store($arr);
1684 proc_run("php", "include/notifier.php", "activity", $i);
1690 * @brief Creates a XML object for a "new friend" message
1692 * @param array $contact Array of the contact
1694 * @return string The XML
1696 private function construct_new_friend_object($contact) {
1697 $objtype = ACTIVITY_OBJ_PERSON;
1698 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1699 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1701 $xmldata = array("object" => array("type" => $objtype,
1702 "title" => $contact["name"],
1703 "id" => $contact["url"]."/".$contact["name"],
1706 return xml::from_array($xmldata, $xml, true);
1710 * @brief Processes incoming sharing notification
1712 * @param array $importer Array of the importer user
1713 * @param object $data The message object
1715 * @return bool Success
1717 private function receive_contact_request($importer, $data) {
1718 $author = unxmlify($data->author);
1719 $recipient = unxmlify($data->recipient);
1721 if (!$author || !$recipient)
1724 // the current protocol version doesn't know these fields
1725 // That means that we will assume their existance
1726 if (isset($data->following))
1727 $following = (unxmlify($data->following) == "true");
1731 if (isset($data->sharing))
1732 $sharing = (unxmlify($data->sharing) == "true");
1736 $contact = self::contact_by_handle($importer["uid"],$author);
1738 // perhaps we were already sharing with this person. Now they're sharing with us.
1739 // That makes us friends.
1741 if ($following AND $sharing) {
1742 self::receive_request_make_friend($importer, $contact);
1744 } else /// @todo Handle all possible variations of adding and retracting of permissions
1748 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
1749 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
1751 } elseif (!$following AND !$sharing) {
1752 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
1756 $ret = self::person_by_handle($author);
1758 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1759 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1763 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1765 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1766 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1767 intval($importer["uid"]),
1768 dbesc($ret["network"]),
1769 dbesc($ret["addr"]),
1772 dbesc(normalise_link($ret["url"])),
1774 dbesc($ret["name"]),
1775 dbesc($ret["nick"]),
1776 dbesc($ret["photo"]),
1777 dbesc($ret["pubkey"]),
1778 dbesc($ret["notify"]),
1779 dbesc($ret["poll"]),
1784 // find the contact record we just created
1786 $contact_record = self::contact_by_handle($importer["uid"],$author);
1788 if (!$contact_record) {
1789 logger("unable to locate newly created contact record.");
1793 $def_gid = get_default_group($importer['uid'], $ret["network"]);
1795 if(intval($def_gid))
1796 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
1798 if($importer["page-flags"] == PAGE_NORMAL) {
1800 $hash = random_string().(string)time(); // Generate a confirm_key
1802 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1803 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1804 intval($importer["uid"]),
1805 intval($contact_record["id"]),
1808 dbesc(t("Sharing notification from Diaspora network")),
1810 dbesc(datetime_convert())
1814 // automatic friend approval
1816 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1818 // technically they are sharing with us (CONTACT_IS_SHARING),
1819 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1820 // we are going to change the relationship and make them a follower.
1822 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
1823 $new_relation = CONTACT_IS_FRIEND;
1824 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
1825 $new_relation = CONTACT_IS_SHARING;
1827 $new_relation = CONTACT_IS_FOLLOWER;
1829 $r = q("UPDATE `contact` SET `rel` = %d,
1837 intval($new_relation),
1838 dbesc(datetime_convert()),
1839 dbesc(datetime_convert()),
1840 intval($contact_record["id"])
1843 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1845 $ret = self::send_share($u[0], $contact_record);
1852 * @brief Fetches a message with a given guid
1854 * @param string $guid message guid
1855 * @param string $orig_author handle of the original post
1856 * @param string $author handle of the sharer
1858 * @return array The fetched item
1860 private function original_item($guid, $orig_author, $author) {
1862 // Do we already have this item?
1863 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1864 `author-name`, `author-link`, `author-avatar`
1865 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1869 logger("reshared message ".$guid." already exists on system.");
1871 // Maybe it is already a reshared item?
1872 // Then refetch the content, if it is a reshare from a reshare.
1873 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
1874 if (self::is_reshare($r[0]["body"], true))
1876 elseif (self::is_reshare($r[0]["body"], false)) {
1877 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
1879 // Add OEmbed and other information to the body
1880 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
1888 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1889 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1890 $item_id = self::store_by_guid($guid, $server);
1893 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1894 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1895 $item_id = self::store_by_guid($guid, $server);
1898 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1900 $server = "https://".substr($author, strpos($author, "@") + 1);
1901 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1902 $item_id = self::store_by_guid($guid, $server);
1905 $server = "http://".substr($author, strpos($author, "@") + 1);
1906 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1907 $item_id = self::store_by_guid($guid, $server);
1911 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1912 `author-name`, `author-link`, `author-avatar`
1913 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1925 * @brief Processes a reshare message
1927 * @param array $importer Array of the importer user
1928 * @param object $data The message object
1929 * @param string $xml The original XML of the message
1931 * @return int the message id
1933 private function receive_reshare($importer, $data, $xml) {
1934 $root_author = notags(unxmlify($data->root_author));
1935 $root_guid = notags(unxmlify($data->root_guid));
1936 $guid = notags(unxmlify($data->guid));
1937 $author = notags(unxmlify($data->author));
1938 $public = notags(unxmlify($data->public));
1939 $created_at = notags(unxmlify($data->created_at));
1941 $contact = self::allowed_contact_by_handle($importer, $author, false);
1945 $message_id = self::message_exists($importer["uid"], $guid);
1949 $original_item = self::original_item($root_guid, $root_author, $author);
1950 if (!$original_item)
1953 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1955 $datarray = array();
1957 $datarray["uid"] = $importer["uid"];
1958 $datarray["contact-id"] = $contact["id"];
1959 $datarray["network"] = NETWORK_DIASPORA;
1961 $datarray["author-name"] = $contact["name"];
1962 $datarray["author-link"] = $contact["url"];
1963 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1965 $datarray["owner-name"] = $datarray["author-name"];
1966 $datarray["owner-link"] = $datarray["author-link"];
1967 $datarray["owner-avatar"] = $datarray["author-avatar"];
1969 $datarray["guid"] = $guid;
1970 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1972 $datarray["verb"] = ACTIVITY_POST;
1973 $datarray["gravity"] = GRAVITY_PARENT;
1975 $datarray["object"] = $xml;
1977 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1978 $original_item["guid"], $original_item["created"], $orig_url);
1979 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1981 $datarray["tag"] = $original_item["tag"];
1982 $datarray["app"] = $original_item["app"];
1984 $datarray["plink"] = self::plink($author, $guid);
1985 $datarray["private"] = (($public == "false") ? 1 : 0);
1986 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1988 $datarray["object-type"] = $original_item["object-type"];
1990 self::fetch_guid($datarray);
1991 $message_id = item_store($datarray);
1994 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2000 * @brief Processes retractions
2002 * @param array $importer Array of the importer user
2003 * @param array $contact The contact of the item owner
2004 * @param object $data The message object
2006 * @return bool success
2008 private function item_retraction($importer, $contact, $data) {
2009 $target_type = notags(unxmlify($data->target_type));
2010 $target_guid = notags(unxmlify($data->target_guid));
2011 $author = notags(unxmlify($data->author));
2013 $person = self::person_by_handle($author);
2014 if (!is_array($person)) {
2015 logger("unable to find author detail for ".$author);
2019 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2020 dbesc($target_guid),
2021 intval($importer["uid"])
2026 // Only delete it if the author really fits
2027 if (!link_compare($r[0]["author-link"], $person["url"])) {
2028 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
2032 // Check if the sender is the thread owner
2033 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2034 intval($r[0]["parent"]));
2036 // Only delete it if the parent author really fits
2037 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2038 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2042 // 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
2043 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2044 dbesc(datetime_convert()),
2045 dbesc(datetime_convert()),
2048 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2050 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2052 // Now check if the retraction needs to be relayed by us
2053 if($p[0]["origin"]) {
2055 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
2062 * @brief Receives retraction messages
2064 * @param array $importer Array of the importer user
2065 * @param string $sender The sender of the message
2066 * @param object $data The message object
2068 * @return bool Success
2070 private function receive_retraction($importer, $sender, $data) {
2071 $target_type = notags(unxmlify($data->target_type));
2073 $contact = self::contact_by_handle($importer["uid"], $sender);
2075 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2079 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2081 switch ($target_type) {
2084 case "Post": // "Post" will be supported in a future version
2086 case "StatusMessage":
2087 return self::item_retraction($importer, $contact, $data);;
2091 /// @todo What should we do with an "unshare"?
2092 // Removing the contact isn't correct since we still can read the public items
2093 contact_remove($contact["id"]);
2097 logger("Unknown target type ".$target_type);
2104 * @brief Receives status messages
2106 * @param array $importer Array of the importer user
2107 * @param object $data The message object
2108 * @param string $xml The original XML of the message
2110 * @return int The message id of the newly created item
2112 private function receive_status_message($importer, $data, $xml) {
2114 $raw_message = unxmlify($data->raw_message);
2115 $guid = notags(unxmlify($data->guid));
2116 $author = notags(unxmlify($data->author));
2117 $public = notags(unxmlify($data->public));
2118 $created_at = notags(unxmlify($data->created_at));
2119 $provider_display_name = notags(unxmlify($data->provider_display_name));
2121 /// @todo enable support for polls
2122 //if ($data->poll) {
2123 // foreach ($data->poll AS $poll)
2127 $contact = self::allowed_contact_by_handle($importer, $author, false);
2131 $message_id = self::message_exists($importer["uid"], $guid);
2136 if ($data->location)
2137 foreach ($data->location->children() AS $fieldname => $data)
2138 $address[$fieldname] = notags(unxmlify($data));
2140 $body = diaspora2bb($raw_message);
2142 $datarray = array();
2144 // Attach embedded pictures to the body
2146 foreach ($data->photo AS $photo)
2147 $body = "[img]".unxmlify($photo->remote_photo_path).
2148 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2150 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2152 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2154 // Add OEmbed and other information to the body
2155 if (!self::is_redmatrix($contact["url"]))
2156 $body = add_page_info_to_body($body, false, true);
2159 $datarray["uid"] = $importer["uid"];
2160 $datarray["contact-id"] = $contact["id"];
2161 $datarray["network"] = NETWORK_DIASPORA;
2163 $datarray["author-name"] = $contact["name"];
2164 $datarray["author-link"] = $contact["url"];
2165 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2167 $datarray["owner-name"] = $datarray["author-name"];
2168 $datarray["owner-link"] = $datarray["author-link"];
2169 $datarray["owner-avatar"] = $datarray["author-avatar"];
2171 $datarray["guid"] = $guid;
2172 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
2174 $datarray["verb"] = ACTIVITY_POST;
2175 $datarray["gravity"] = GRAVITY_PARENT;
2177 $datarray["object"] = $xml;
2179 $datarray["body"] = $body;
2181 if ($provider_display_name != "")
2182 $datarray["app"] = $provider_display_name;
2184 $datarray["plink"] = self::plink($author, $guid);
2185 $datarray["private"] = (($public == "false") ? 1 : 0);
2186 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2188 if (isset($address["address"]))
2189 $datarray["location"] = $address["address"];
2191 if (isset($address["lat"]) AND isset($address["lng"]))
2192 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2194 self::fetch_guid($datarray);
2195 $message_id = item_store($datarray);
2198 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2203 /* ************************************************************************************** *
2204 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2205 * ************************************************************************************** */
2208 * @brief returnes the handle of a contact
2210 * @param array $me contact array
2212 * @return string the handle in the format user@domain.tld
2214 private function my_handle($contact) {
2215 if ($contact["addr"] != "")
2216 return $contact["addr"];
2218 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2219 // So - just in case - we build the the address here.
2220 if ($contact["nickname"] != "")
2221 $nick = $contact["nickname"];
2223 $nick = $contact["nick"];
2225 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2229 * @brief Creates the envelope for a public message
2231 * @param string $msg The message that is to be transmitted
2232 * @param array $user The record of the sender
2233 * @param array $contact Target of the communication
2234 * @param string $prvkey The private key of the sender
2235 * @param string $pubkey The public key of the receiver
2237 * @return string The envelope
2239 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2241 logger("Message: ".$msg, LOGGER_DATA);
2243 $handle = self::my_handle($user);
2245 $b64url_data = base64url_encode($msg);
2247 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2249 $type = "application/xml";
2250 $encoding = "base64url";
2251 $alg = "RSA-SHA256";
2253 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2255 $signature = rsa_sign($signable_data,$prvkey);
2256 $sig = base64url_encode($signature);
2258 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2259 "me:env" => array("me:encoding" => "base64url",
2260 "me:alg" => "RSA-SHA256",
2262 "@attributes" => array("type" => "application/xml"),
2263 "me:sig" => $sig)));
2265 $namespaces = array("" => "https://joindiaspora.com/protocol",
2266 "me" => "http://salmon-protocol.org/ns/magic-env");
2268 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2270 logger("magic_env: ".$magic_env, LOGGER_DATA);
2275 * @brief Creates the envelope for a private message
2277 * @param string $msg The message that is to be transmitted
2278 * @param array $user The record of the sender
2279 * @param array $contact Target of the communication
2280 * @param string $prvkey The private key of the sender
2281 * @param string $pubkey The public key of the receiver
2283 * @return string The envelope
2285 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2287 logger("Message: ".$msg, LOGGER_DATA);
2289 // without a public key nothing will work
2292 logger("pubkey missing: contact id: ".$contact["id"]);
2296 $inner_aes_key = random_string(32);
2297 $b_inner_aes_key = base64_encode($inner_aes_key);
2298 $inner_iv = random_string(16);
2299 $b_inner_iv = base64_encode($inner_iv);
2301 $outer_aes_key = random_string(32);
2302 $b_outer_aes_key = base64_encode($outer_aes_key);
2303 $outer_iv = random_string(16);
2304 $b_outer_iv = base64_encode($outer_iv);
2306 $handle = self::my_handle($user);
2308 $padded_data = pkcs5_pad($msg,16);
2309 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2311 $b64_data = base64_encode($inner_encrypted);
2314 $b64url_data = base64url_encode($b64_data);
2315 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2317 $type = "application/xml";
2318 $encoding = "base64url";
2319 $alg = "RSA-SHA256";
2321 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2323 $signature = rsa_sign($signable_data,$prvkey);
2324 $sig = base64url_encode($signature);
2326 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2327 "aes_key" => $b_inner_aes_key,
2328 "author_id" => $handle));
2330 $decrypted_header = xml::from_array($xmldata, $xml, true);
2331 $decrypted_header = pkcs5_pad($decrypted_header,16);
2333 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2335 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2337 $encrypted_outer_key_bundle = "";
2338 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2340 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2342 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2344 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2345 "ciphertext" => base64_encode($ciphertext)));
2346 $cipher_json = base64_encode($encrypted_header_json_object);
2348 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2349 "me:env" => array("me:encoding" => "base64url",
2350 "me:alg" => "RSA-SHA256",
2352 "@attributes" => array("type" => "application/xml"),
2353 "me:sig" => $sig)));
2355 $namespaces = array("" => "https://joindiaspora.com/protocol",
2356 "me" => "http://salmon-protocol.org/ns/magic-env");
2358 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2360 logger("magic_env: ".$magic_env, LOGGER_DATA);
2365 * @brief Create the envelope for a message
2367 * @param string $msg The message that is to be transmitted
2368 * @param array $user The record of the sender
2369 * @param array $contact Target of the communication
2370 * @param string $prvkey The private key of the sender
2371 * @param string $pubkey The public key of the receiver
2372 * @param bool $public Is the message public?
2374 * @return string The message that will be transmitted to other servers
2376 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2379 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2381 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2383 // The data that will be transmitted is double encoded via "urlencode", strange ...
2384 $slap = "xml=".urlencode(urlencode($magic_env));
2389 * @brief Creates a signature for a message
2391 * @param array $owner the array of the owner of the message
2392 * @param array $message The message that is to be signed
2394 * @return string The signature
2396 private function signature($owner, $message) {
2398 unset($sigmsg["author_signature"]);
2399 unset($sigmsg["parent_author_signature"]);
2401 $signed_text = implode(";", $sigmsg);
2403 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2407 * @brief Transmit a message to a target server
2409 * @param array $owner the array of the item owner
2410 * @param array $contact Target of the communication
2411 * @param string $slap The message that is to be transmitted
2412 * @param bool $public_batch Is it a public post?
2413 * @param bool $queue_run Is the transmission called from the queue?
2414 * @param string $guid message guid
2416 * @return int Result of the transmission
2418 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2422 $enabled = intval(get_config("system", "diaspora_enabled"));
2426 $logid = random_string(4);
2427 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2429 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2433 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2435 if (!$queue_run && was_recently_delayed($contact["id"])) {
2438 if (!intval(get_config("system", "diaspora_test"))) {
2439 post_url($dest_url."/", $slap);
2440 $return_code = $a->get_curl_code();
2442 logger("test_mode");
2447 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2449 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2450 logger("queue message");
2452 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2453 intval($contact["id"]),
2454 dbesc(NETWORK_DIASPORA),
2456 intval($public_batch)
2459 logger("add_to_queue ignored - identical item already in queue");
2461 // queue message for redelivery
2462 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2466 return(($return_code) ? $return_code : (-1));
2471 * @brief Builds and transmit messages
2473 * @param array $owner the array of the item owner
2474 * @param array $contact Target of the communication
2475 * @param string $type The message type
2476 * @param array $message The message data
2477 * @param bool $public_batch Is it a public post?
2478 * @param string $guid message guid
2479 * @param bool $spool Should the transmission be spooled or transmitted?
2481 * @return int Result of the transmission
2483 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2485 $data = array("XML" => array("post" => array($type => $message)));
2487 $msg = xml::from_array($data, $xml);
2489 logger('message: '.$msg, LOGGER_DATA);
2490 logger('send guid '.$guid, LOGGER_DEBUG);
2492 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2495 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2498 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2500 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2502 return $return_code;
2506 * @brief Sends a "share" message
2508 * @param array $owner the array of the item owner
2509 * @param array $contact Target of the communication
2511 * @return int The result of the transmission
2513 public static function send_share($owner,$contact) {
2515 $message = array("sender_handle" => self::my_handle($owner),
2516 "recipient_handle" => $contact["addr"]);
2518 return self::build_and_transmit($owner, $contact, "request", $message);
2522 * @brief sends an "unshare"
2524 * @param array $owner the array of the item owner
2525 * @param array $contact Target of the communication
2527 * @return int The result of the transmission
2529 public static function send_unshare($owner,$contact) {
2531 $message = array("post_guid" => $owner["guid"],
2532 "diaspora_handle" => self::my_handle($owner),
2533 "type" => "Person");
2535 return self::build_and_transmit($owner, $contact, "retraction", $message);
2539 * @brief Checks a message body if it is a reshare
2541 * @param string $body The message body that is to be check
2542 * @param bool $complete Should it be a complete check or a simple check?
2544 * @return array|bool Reshare details or "false" if no reshare
2546 public static function is_reshare($body, $complete = true) {
2547 $body = trim($body);
2549 // Skip if it isn't a pure repeated messages
2550 // Does it start with a share?
2551 if (strpos($body, "[share") > 0)
2554 // Does it end with a share?
2555 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2558 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2559 // Skip if there is no shared message in there
2560 if ($body == $attributes)
2563 // If we don't do the complete check we quit here
2568 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2569 if ($matches[1] != "")
2570 $guid = $matches[1];
2572 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2573 if ($matches[1] != "")
2574 $guid = $matches[1];
2577 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2578 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2581 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2582 $ret["root_guid"] = $guid;
2588 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2589 if ($matches[1] != "")
2590 $profile = $matches[1];
2592 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2593 if ($matches[1] != "")
2594 $profile = $matches[1];
2598 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2599 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2603 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2604 if ($matches[1] != "")
2605 $link = $matches[1];
2607 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2608 if ($matches[1] != "")
2609 $link = $matches[1];
2611 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2612 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2619 * @brief Sends a post
2621 * @param array $item The item that will be exported
2622 * @param array $owner the array of the item owner
2623 * @param array $contact Target of the communication
2624 * @param bool $public_batch Is it a public post?
2626 * @return int The result of the transmission
2628 public static function send_status($item, $owner, $contact, $public_batch = false) {
2630 $myaddr = self::my_handle($owner);
2632 $public = (($item["private"]) ? "false" : "true");
2634 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2636 // Detect a share element and do a reshare
2637 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2638 $message = array("root_diaspora_id" => $ret["root_handle"],
2639 "root_guid" => $ret["root_guid"],
2640 "guid" => $item["guid"],
2641 "diaspora_handle" => $myaddr,
2642 "public" => $public,
2643 "created_at" => $created,
2644 "provider_display_name" => $item["app"]);
2648 $title = $item["title"];
2649 $body = $item["body"];
2651 // convert to markdown
2652 $body = html_entity_decode(bb2diaspora($body));
2656 $body = "## ".html_entity_decode($title)."\n\n".$body;
2658 if ($item["attach"]) {
2659 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2661 $body .= "\n".t("Attachments:")."\n";
2662 foreach($matches as $mtch)
2663 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2667 $location = array();
2669 if ($item["location"] != "")
2670 $location["address"] = $item["location"];
2672 if ($item["coord"] != "") {
2673 $coord = explode(" ", $item["coord"]);
2674 $location["lat"] = $coord[0];
2675 $location["lng"] = $coord[1];
2678 $message = array("raw_message" => $body,
2679 "location" => $location,
2680 "guid" => $item["guid"],
2681 "diaspora_handle" => $myaddr,
2682 "public" => $public,
2683 "created_at" => $created,
2684 "provider_display_name" => $item["app"]);
2686 if (count($location) == 0)
2687 unset($message["location"]);
2689 $type = "status_message";
2692 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2696 * @brief Creates a "like" object
2698 * @param array $item The item that will be exported
2699 * @param array $owner the array of the item owner
2701 * @return array The data for a "like"
2703 private function construct_like($item, $owner) {
2705 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2706 dbesc($item["thr-parent"]));
2712 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2715 return(array("positive" => $positive,
2716 "guid" => $item["guid"],
2717 "target_type" => $target_type,
2718 "parent_guid" => $parent["guid"],
2719 "author_signature" => "",
2720 "diaspora_handle" => self::my_handle($owner)));
2724 * @brief Creates the object for a comment
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 comment
2731 private function construct_comment($item, $owner) {
2733 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2734 intval($item["parent"]),
2735 intval($item["parent"])
2743 $text = html_entity_decode(bb2diaspora($item["body"]));
2745 return(array("guid" => $item["guid"],
2746 "parent_guid" => $parent["guid"],
2747 "author_signature" => "",
2749 "diaspora_handle" => self::my_handle($owner)));
2753 * @brief Send a like or a comment
2755 * @param array $item The item that will be exported
2756 * @param array $owner the array of the item owner
2757 * @param array $contact Target of the communication
2758 * @param bool $public_batch Is it a public post?
2760 * @return int The result of the transmission
2762 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2764 if($item['verb'] === ACTIVITY_LIKE) {
2765 $message = self::construct_like($item, $owner);
2768 $message = self::construct_comment($item, $owner);
2775 $message["author_signature"] = self::signature($owner, $message);
2777 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2781 * @brief Creates a message from a signature record entry
2783 * @param array $item The item that will be exported
2784 * @param array $signature The entry of the "sign" record
2786 * @return string The message
2788 private function message_from_signature($item, $signature) {
2790 // Split the signed text
2791 $signed_parts = explode(";", $signature['signed_text']);
2793 if ($item["deleted"])
2794 $message = array("parent_author_signature" => "",
2795 "target_guid" => $signed_parts[0],
2796 "target_type" => $signed_parts[1],
2797 "sender_handle" => $signature['signer'],
2798 "target_author_signature" => $signature['signature']);
2799 elseif ($item['verb'] === ACTIVITY_LIKE)
2800 $message = array("positive" => $signed_parts[0],
2801 "guid" => $signed_parts[1],
2802 "target_type" => $signed_parts[2],
2803 "parent_guid" => $signed_parts[3],
2804 "parent_author_signature" => "",
2805 "author_signature" => $signature['signature'],
2806 "diaspora_handle" => $signed_parts[4]);
2808 // Remove the comment guid
2809 $guid = array_shift($signed_parts);
2811 // Remove the parent guid
2812 $parent_guid = array_shift($signed_parts);
2814 // Remove the handle
2815 $handle = array_pop($signed_parts);
2817 // Glue the parts together
2818 $text = implode(";", $signed_parts);
2820 $message = array("guid" => $guid,
2821 "parent_guid" => $parent_guid,
2822 "parent_author_signature" => "",
2823 "author_signature" => $signature['signature'],
2824 "text" => implode(";", $signed_parts),
2825 "diaspora_handle" => $handle);
2831 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
2833 * @param array $item The item that will be exported
2834 * @param array $owner the array of the item owner
2835 * @param array $contact Target of the communication
2836 * @param bool $public_batch Is it a public post?
2838 * @return int The result of the transmission
2840 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2842 if ($item["deleted"])
2843 return self::send_retraction($item, $owner, $contact, $public_batch, true);
2844 elseif ($item['verb'] === ACTIVITY_LIKE)
2849 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2851 // fetch the original signature
2853 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
2854 intval($item["id"]));
2857 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2863 // Old way - is used by the internal Friendica functions
2864 /// @todo Change all signatur storing functions to the new format
2865 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2866 $message = self::message_from_signature($item, $signature);
2868 $msg = json_decode($signature['signed_text'], true);
2871 if (is_array($msg)) {
2872 foreach ($msg AS $field => $data) {
2873 if (!$item["deleted"]) {
2874 if ($field == "author")
2875 $field = "diaspora_handle";
2876 if ($field == "parent_type")
2877 $field = "target_type";
2880 $message[$field] = $data;
2883 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2886 $message["parent_author_signature"] = self::signature($owner, $message);
2888 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2890 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2894 * @brief Sends a retraction (deletion) of a message, like or comment
2896 * @param array $item The item that will be exported
2897 * @param array $owner the array of the item owner
2898 * @param array $contact Target of the communication
2899 * @param bool $public_batch Is it a public post?
2900 * @param bool $relay Is the retraction transmitted from a relay?
2902 * @return int The result of the transmission
2904 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
2906 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
2908 // Check whether the retraction is for a top-level post or whether it's a relayable
2909 if ($item["uri"] !== $item["parent-uri"]) {
2910 $msg_type = "relayable_retraction";
2911 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2913 $msg_type = "signed_retraction";
2914 $target_type = "StatusMessage";
2917 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
2918 $signature = "parent_author_signature";
2920 $signature = "target_author_signature";
2922 $signed_text = $item["guid"].";".$target_type;
2924 $message = array("target_guid" => $item['guid'],
2925 "target_type" => $target_type,
2926 "sender_handle" => $itemaddr,
2927 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2929 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2931 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2935 * @brief Sends a mail
2937 * @param array $item The item that will be exported
2938 * @param array $owner The owner
2939 * @param array $contact Target of the communication
2941 * @return int The result of the transmission
2943 public static function send_mail($item, $owner, $contact) {
2945 $myaddr = self::my_handle($owner);
2947 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2948 intval($item["convid"]),
2949 intval($item["uid"])
2953 logger("conversation not found.");
2959 "guid" => $cnv["guid"],
2960 "subject" => $cnv["subject"],
2961 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2962 "diaspora_handle" => $cnv["creator"],
2963 "participant_handles" => $cnv["recips"]
2966 $body = bb2diaspora($item["body"]);
2967 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2969 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2970 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2973 "guid" => $item["guid"],
2974 "parent_guid" => $cnv["guid"],
2975 "parent_author_signature" => $sig,
2976 "author_signature" => $sig,
2978 "created_at" => $created,
2979 "diaspora_handle" => $myaddr,
2980 "conversation_guid" => $cnv["guid"]
2983 if ($item["reply"]) {
2987 $message = array("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'),
2991 "diaspora_handle" => $cnv["creator"],
2992 "participant_handles" => $cnv["recips"]);
2994 $type = "conversation";
2997 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3001 * @brief Sends profile data
3003 * @param int $uid The user id
3005 public static function send_profile($uid) {
3010 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3011 AND `uid` = %d AND `rel` != %d",
3012 dbesc(NETWORK_DIASPORA),
3014 intval(CONTACT_IS_SHARING)
3019 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3021 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3022 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3023 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3032 $handle = $profile["addr"];
3033 $first = ((strpos($profile['name'],' ')
3034 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3035 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3036 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3037 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3038 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3039 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3041 if ($searchable === 'true') {
3042 $dob = '1000-00-00';
3044 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3045 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3047 $about = $profile['about'];
3048 $about = strip_tags(bbcode($about));
3050 $location = formatted_location($profile);
3052 if ($profile['pub_keywords']) {
3053 $kw = str_replace(',',' ',$profile['pub_keywords']);
3054 $kw = str_replace(' ',' ',$kw);
3055 $arr = explode(' ',$profile['pub_keywords']);
3057 for($x = 0; $x < 5; $x ++) {
3059 $tags .= '#'. trim($arr[$x]) .' ';
3063 $tags = trim($tags);
3066 $message = array("diaspora_handle" => $handle,
3067 "first_name" => $first,
3068 "last_name" => $last,
3069 "image_url" => $large,
3070 "image_url_medium" => $medium,
3071 "image_url_small" => $small,
3073 "gender" => $profile['gender'],
3075 "location" => $location,
3076 "searchable" => $searchable,
3077 "tag_string" => $tags);
3079 foreach($recips as $recip)
3080 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3084 * @brief Stores the signature for likes that are created on our system
3086 * @param array $contact The contact array of the "like"
3087 * @param int $post_id The post id of the "like"
3089 * @return bool Success
3091 public static function store_like_signature($contact, $post_id) {
3093 // Is the contact the owner? Then fetch the private key
3094 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3095 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3099 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3103 $contact["uprvkey"] = $r[0]['prvkey'];
3105 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3109 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3112 $message = self::construct_like($r[0], $contact);
3113 $message["author_signature"] = self::signature($contact, $message);
3115 // In the future we will store the signature more flexible to support new fields.
3116 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3117 // (We are transmitting this data here via DFRN)
3119 $signed_text = $message["positive"].";".$message["guid"].";".$message["target_type"].";".
3120 $message["parent_guid"].";".$message["diaspora_handle"];
3122 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3124 dbesc($signed_text),
3125 dbesc($message["author_signature"]),
3126 dbesc($message["diaspora_handle"])
3129 // This here will replace the lines above, once Diaspora changed its protocol
3130 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3131 // intval($message_id),
3132 // dbesc(json_encode($message))
3135 logger('Stored diaspora like signature');
3140 * @brief Stores the signature for comments that are created on our system
3142 * @param array $item The item array of the comment
3143 * @param array $contact The contact array of the item owner
3144 * @param string $uprvkey The private key of the sender
3145 * @param int $message_id The message id of the comment
3147 * @return bool Success
3149 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3151 if ($uprvkey == "") {
3152 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3156 $contact["uprvkey"] = $uprvkey;
3158 $message = self::construct_comment($item, $contact);
3159 $message["author_signature"] = self::signature($contact, $message);
3161 // In the future we will store the signature more flexible to support new fields.
3162 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3163 // (We are transmitting this data here via DFRN)
3164 $signed_text = $message["guid"].";".$message["parent_guid"].";".
3165 $message["text"].";".$message["diaspora_handle"];
3167 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3168 intval($message_id),
3169 dbesc($signed_text),
3170 dbesc($message["author_signature"]),
3171 dbesc($message["diaspora_handle"])
3174 // This here will replace the lines above, once Diaspora changed its protocol
3175 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3176 // intval($message_id),
3177 // dbesc(json_encode($message))
3180 logger('Stored diaspora comment signature');