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 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 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 bool Was the message accepted?
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 $item_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 bool Was the message accepted?
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_conversation($importer, $msg, $fields);
346 return self::receive_like($importer, $sender, $fields);
349 return self::receive_message($importer, $fields);
351 case "participation": // Not implemented
352 return self::receive_participation($importer, $fields);
354 case "photo": // Not implemented
355 return self::receive_photo($importer, $fields);
357 case "poll_participation": // Not implemented
358 return self::receive_poll_participation($importer, $fields);
361 return self::receive_profile($importer, $fields);
364 return self::receive_request($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 $fields = new SimpleXMLElement("<".$type."/>");
425 foreach ($element->children() AS $fieldname => $entry) {
427 // Translation for the old XML structure
428 if ($fieldname == "diaspora_handle")
429 $fieldname = "author";
431 if ($fieldname == "participant_handles")
432 $fieldname = "participants";
434 if (in_array($type, array("like", "participation"))) {
435 if ($fieldname == "target_type")
436 $fieldname = "parent_type";
439 if ($fieldname == "sender_handle")
440 $fieldname = "author";
442 if ($fieldname == "recipient_handle")
443 $fieldname = "recipient";
445 if ($fieldname == "root_diaspora_id")
446 $fieldname = "root_author";
448 if ($type == "retraction") {
449 if ($fieldname == "post_guid")
450 $fieldname = "target_guid";
452 if ($fieldname == "type")
453 $fieldname = "target_type";
457 if ($fieldname == "author_signature")
458 $author_signature = base64_decode($entry);
459 elseif ($fieldname == "parent_author_signature")
460 $parent_author_signature = base64_decode($entry);
461 elseif ($fieldname != "target_author_signature") {
462 if ($signed_data != "") {
464 $signed_data_parent .= ";";
467 $signed_data .= $entry;
469 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
470 ($orig_type == "relayable_retraction"))
471 xml::copy($entry, $fields, $fieldname);
474 // This is something that shouldn't happen at all.
475 if (in_array($type, array("status_message", "reshare", "profile")))
476 if ($msg["author"] != $fields->author) {
477 logger("Message handle is not the same as envelope sender. Quitting this message.");
481 // Only some message types have signatures. So we quit here for the other types.
482 if (!in_array($type, array("comment", "message", "like")))
485 // No author_signature? This is a must, so we quit.
486 if (!isset($author_signature))
489 if (isset($parent_author_signature)) {
490 $key = self::key($msg["author"]);
492 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
496 $key = self::key($fields->author);
498 return rsa_verify($signed_data, $author_signature, $key, "sha256");
502 * @brief Fetches the public key for a given handle
504 * @param string $handle The handle
506 * @return string The public key
508 private function key($handle) {
509 $handle = strval($handle);
511 logger("Fetching diaspora key for: ".$handle);
513 $r = self::person_by_handle($handle);
521 * @brief Fetches data for a given handle
523 * @param string $handle The handle
525 * @return array the queried data
527 private function person_by_handle($handle) {
529 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
530 dbesc(NETWORK_DIASPORA),
535 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
537 // update record occasionally so it doesn't get stale
538 $d = strtotime($person["updated"]." +00:00");
539 if ($d < strtotime("now - 14 days"))
543 if (!$person OR $update) {
544 logger("create or refresh", LOGGER_DEBUG);
545 $r = probe_url($handle, PROBE_DIASPORA);
547 // Note that Friendica contacts will return a "Diaspora person"
548 // if Diaspora connectivity is enabled on their server
549 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
550 self::add_fcontact($r, $update);
558 * @brief Updates the fcontact table
560 * @param array $arr The fcontact data
561 * @param bool $update Update or insert?
563 * @return string The id of the fcontact entry
565 private function add_fcontact($arr, $update = false) {
568 $r = q("UPDATE `fcontact` SET
581 WHERE `url` = '%s' AND `network` = '%s'",
583 dbesc($arr["photo"]),
584 dbesc($arr["request"]),
587 dbesc($arr["batch"]),
588 dbesc($arr["notify"]),
590 dbesc($arr["confirm"]),
591 dbesc($arr["alias"]),
592 dbesc($arr["pubkey"]),
593 dbesc(datetime_convert()),
595 dbesc($arr["network"])
598 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
599 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
600 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
603 dbesc($arr["photo"]),
604 dbesc($arr["request"]),
607 dbesc($arr["batch"]),
608 dbesc($arr["notify"]),
610 dbesc($arr["confirm"]),
611 dbesc($arr["network"]),
612 dbesc($arr["alias"]),
613 dbesc($arr["pubkey"]),
614 dbesc(datetime_convert())
622 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
624 * @param int $contact_id The id in the contact table
625 * @param int $gcontact_id The id in the gcontact table
627 * @return string the handle
629 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
632 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
634 if ($gcontact_id != 0) {
635 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
636 intval($gcontact_id));
638 return $r[0]["addr"];
641 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
642 intval($contact_id));
646 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
648 if($contact['addr'] != "")
649 $handle = $contact['addr'];
650 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
651 $baseurl_start = strpos($contact['url'],'://') + 3;
652 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
653 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
654 $handle = $contact['nick'].'@'.$baseurl;
662 * @brief Get a contact id for a given handle
664 * @param int $uid The user id
665 * @param string $handle The handle in the format user@domain.tld
667 * @return The contact id
669 private function contact_by_handle($uid, $handle) {
670 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
678 $handle_parts = explode("@", $handle);
679 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
680 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
692 * @brief Check if posting is allowed for this contact
694 * @param array $importer Array of the importer user
695 * @param array $contact The contact that is checked
696 * @param bool $is_comment Is the check for a comment?
698 * @return bool is the contact allowed to post?
700 private function post_allow($importer, $contact, $is_comment = false) {
702 // perhaps we were already sharing with this person. Now they're sharing with us.
703 // That makes us friends.
704 // Normally this should have handled by getting a request - but this could get lost
705 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
706 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
707 intval(CONTACT_IS_FRIEND),
708 intval($contact["id"]),
709 intval($importer["uid"])
711 $contact["rel"] = CONTACT_IS_FRIEND;
712 logger("defining user ".$contact["nick"]." as friend");
715 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
717 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
719 if($contact["rel"] == CONTACT_IS_FOLLOWER)
720 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
723 // Messages for the global users are always accepted
724 if ($importer["uid"] == 0)
731 * @brief Fetches the contact id for a handle and checks if posting is allowed
733 * @param array $importer Array of the importer user
734 * @param string $handle The checked handle in the format user@domain.tld
735 * @param bool $is_comment Is the check for a comment?
737 * @return bool is posting allowed?
739 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
740 $contact = self::contact_by_handle($importer["uid"], $handle);
742 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
746 if (!self::post_allow($importer, $contact, $is_comment)) {
747 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
754 * @brief Does the message already exists on the system?
756 * @param int $uid The user id
757 * @param string $guid The guid of the message
759 * @return bool "true" if the message already was stored into the system
761 private function message_exists($uid, $guid) {
762 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
768 logger("message ".$guid." already exists for user ".$uid);
776 * @brief Checks for links to posts in a message
778 * @param array $item The item array
780 private function fetch_guid($item) {
781 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
782 function ($match) use ($item){
783 return(self::fetch_guid_sub($match, $item));
788 * @brief sub function of "fetch_guid" which checks for links in messages
790 * @param array $match array containing a link that has to be checked for a message link
791 * @param array $item The item array
793 private function fetch_guid_sub($match, $item) {
794 if (!self::store_by_guid($match[1], $item["author-link"]))
795 self::store_by_guid($match[1], $item["owner-link"]);
799 * @brief Fetches an item with a given guid from a given server
801 * @param string $guid the message guid
802 * @param string $server The server address
803 * @param int $uid The user id of the user
805 * @return int the message id of the stored message or false
807 private function store_by_guid($guid, $server, $uid = 0) {
808 $serverparts = parse_url($server);
809 $server = $serverparts["scheme"]."://".$serverparts["host"];
811 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
813 $msg = self::message($guid, $server);
818 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
820 // Now call the dispatcher
821 return self::dispatch_public($msg);
825 * @brief Fetches a message from a server
827 * @param string $guid message guid
828 * @param string $server The url of the server
829 * @param int $level Endless loop prevention
832 * 'message' => The message XML
833 * 'author' => The author handle
834 * 'key' => The public key of the author
836 private function message($guid, $server, $level = 0) {
841 // This will work for Diaspora and newer Friendica servers
842 $source_url = $server."/p/".$guid.".xml";
843 $x = fetch_url($source_url);
847 $source_xml = parse_xml_string($x, false);
849 if (!is_object($source_xml))
852 if ($source_xml->post->reshare) {
853 // Reshare of a reshare - old Diaspora version
854 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
855 } elseif ($source_xml->getName() == "reshare") {
856 // Reshare of a reshare - new Diaspora version
857 return self::message($source_xml->root_guid, $server, ++$level);
862 // Fetch the author - for the old and the new Diaspora version
863 if ($source_xml->post->status_message->diaspora_handle)
864 $author = (string)$source_xml->post->status_message->diaspora_handle;
865 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
866 $author = (string)$source_xml->author;
868 // If this isn't a "status_message" then quit
872 $msg = array("message" => $x, "author" => $author);
874 $msg["key"] = self::key($msg["author"]);
880 * @brief Fetches the item record of a given guid
882 * @param int $uid The user id
883 * @param string $guid message guid
884 * @param string $author The handle of the item
885 * @param array $contact The contact of the item owner
887 * @return array the item record
889 private function parent_item($uid, $guid, $author, $contact) {
890 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
891 `author-name`, `author-link`, `author-avatar`,
892 `owner-name`, `owner-link`, `owner-avatar`
893 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
894 intval($uid), dbesc($guid));
897 $result = self::store_by_guid($guid, $contact["url"], $uid);
900 $person = self::person_by_handle($author);
901 $result = self::store_by_guid($guid, $person["url"], $uid);
905 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
907 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
908 `author-name`, `author-link`, `author-avatar`,
909 `owner-name`, `owner-link`, `owner-avatar`
910 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
911 intval($uid), dbesc($guid));
916 logger("parent item not found: parent: ".$guid." - user: ".$uid);
919 logger("parent item found: parent: ".$guid." - user: ".$uid);
925 * @brief returns contact details
927 * @param array $contact The default contact if the person isn't found
928 * @param array $person The record of the person
929 * @param int $uid The user id
931 * @return array of contact id and network type
933 private function author_contact_by_url($contact, $person, $uid) {
935 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
936 dbesc(normalise_link($person["url"])), intval($uid));
939 $network = $r[0]["network"];
941 $cid = $contact["id"];
942 $network = NETWORK_DIASPORA;
945 return (array("cid" => $cid, "network" => $network));
949 * @brief Is the profile a hubzilla profile?
951 * @param string $url The profile link
953 * @return bool is it a hubzilla server?
955 public static function is_redmatrix($url) {
956 return(strstr($url, "/channel/"));
960 * @brief Generate a post link with a given handle and message guid
962 * @param string $addr The user handle
963 * @param string $guid message guid
965 * @return string the post link
967 private function plink($addr, $guid) {
968 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
972 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
974 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
975 // So we try another way as well.
976 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
978 $r[0]["network"] = $s[0]["network"];
980 if ($r[0]["network"] == NETWORK_DFRN)
981 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
983 if (self::is_redmatrix($r[0]["url"]))
984 return $r[0]["url"]."/?f=&mid=".$guid;
986 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
990 * @brief Processes an account deletion
992 * @param array $importer Array of the importer user
993 * @param object $data The message object
995 * @return bool Success
997 private function receive_account_deletion($importer, $data) {
998 $author = notags(unxmlify($data->author));
1000 $contact = self::contact_by_handle($importer["uid"], $author);
1002 logger("cannot find contact for author: ".$author);
1006 // We now remove the contact
1007 contact_remove($contact["id"]);
1012 * @brief Processes an incoming comment
1014 * @param array $importer Array of the importer user
1015 * @param string $sender The sender of the message
1016 * @param object $data The message object
1017 * @param string $xml The original XML of the message
1019 * @return int The message id of the generated comment or "false" if there was an error
1021 private function receive_comment($importer, $sender, $data, $xml) {
1022 $guid = notags(unxmlify($data->guid));
1023 $parent_guid = notags(unxmlify($data->parent_guid));
1024 $text = unxmlify($data->text);
1025 $author = notags(unxmlify($data->author));
1027 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1031 if (self::message_exists($importer["uid"], $guid))
1034 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1038 $person = self::person_by_handle($author);
1039 if (!is_array($person)) {
1040 logger("unable to find author details");
1044 // Fetch the contact id - if we know this contact
1045 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1047 $datarray = array();
1049 $datarray["uid"] = $importer["uid"];
1050 $datarray["contact-id"] = $author_contact["cid"];
1051 $datarray["network"] = $author_contact["network"];
1053 $datarray["author-name"] = $person["name"];
1054 $datarray["author-link"] = $person["url"];
1055 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1057 $datarray["owner-name"] = $contact["name"];
1058 $datarray["owner-link"] = $contact["url"];
1059 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1061 $datarray["guid"] = $guid;
1062 $datarray["uri"] = $author.":".$guid;
1064 $datarray["type"] = "remote-comment";
1065 $datarray["verb"] = ACTIVITY_POST;
1066 $datarray["gravity"] = GRAVITY_COMMENT;
1067 $datarray["parent-uri"] = $parent_item["uri"];
1069 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1070 $datarray["object"] = $xml;
1072 $datarray["body"] = diaspora2bb($text);
1074 self::fetch_guid($datarray);
1076 $message_id = item_store($datarray);
1079 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1081 // If we are the origin of the parent we store the original data and notify our followers
1082 if($message_id AND $parent_item["origin"]) {
1084 // Formerly we stored the signed text, the signature and the author in different fields.
1085 // We now store the raw data so that we are more flexible.
1086 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1087 intval($message_id),
1088 dbesc(json_encode($data))
1092 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1099 * @brief processes and stores private messages
1101 * @param array $importer Array of the importer user
1102 * @param array $contact The contact of the message
1103 * @param object $data The message object
1104 * @param array $msg Array of the processed message, author handle and key
1105 * @param object $mesg The private message
1106 * @param array $conversation The conversation record to which this message belongs
1108 * @return bool "true" if it was successful
1110 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1111 $guid = notags(unxmlify($data->guid));
1112 $subject = notags(unxmlify($data->subject));
1113 $author = notags(unxmlify($data->author));
1117 $msg_guid = notags(unxmlify($mesg->guid));
1118 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1119 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1120 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1121 $msg_text = unxmlify($mesg->text);
1122 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1124 // "diaspora_handle" is the element name from the old version
1125 // "author" is the element name from the new version
1127 $msg_author = notags(unxmlify($mesg->author));
1128 elseif ($mesg->diaspora_handle)
1129 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1133 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1135 if($msg_conversation_guid != $guid) {
1136 logger("message conversation guid does not belong to the current conversation.");
1140 $body = diaspora2bb($msg_text);
1141 $message_uri = $msg_author.":".$msg_guid;
1143 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1145 $author_signature = base64_decode($msg_author_signature);
1147 if(strcasecmp($msg_author,$msg["author"]) == 0) {
1151 $person = self::person_by_handle($msg_author);
1153 if (is_array($person) && x($person, "pubkey"))
1154 $key = $person["pubkey"];
1156 logger("unable to find author details");
1161 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1162 logger("verification failed.");
1166 if($msg_parent_author_signature) {
1167 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1169 $parent_author_signature = base64_decode($msg_parent_author_signature);
1173 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1174 logger("owner verification failed.");
1179 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1183 logger("duplicate message already delivered.", LOGGER_DEBUG);
1187 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1188 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1189 intval($importer["uid"]),
1191 intval($conversation["id"]),
1192 dbesc($person["name"]),
1193 dbesc($person["photo"]),
1194 dbesc($person["url"]),
1195 intval($contact["id"]),
1200 dbesc($message_uri),
1201 dbesc($author.":".$guid),
1202 dbesc($msg_created_at)
1205 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1206 dbesc(datetime_convert()),
1207 intval($conversation["id"])
1211 "type" => NOTIFY_MAIL,
1212 "notify_flags" => $importer["notify-flags"],
1213 "language" => $importer["language"],
1214 "to_name" => $importer["username"],
1215 "to_email" => $importer["email"],
1216 "uid" =>$importer["uid"],
1217 "item" => array("subject" => $subject, "body" => $body),
1218 "source_name" => $person["name"],
1219 "source_link" => $person["url"],
1220 "source_photo" => $person["thumb"],
1221 "verb" => ACTIVITY_POST,
1228 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1230 * @param array $importer Array of the importer user
1231 * @param array $msg Array of the processed message, author handle and key
1232 * @param object $data The message object
1234 * @return bool Success
1236 private function receive_conversation($importer, $msg, $data) {
1237 $guid = notags(unxmlify($data->guid));
1238 $subject = notags(unxmlify($data->subject));
1239 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1240 $author = notags(unxmlify($data->author));
1241 $participants = notags(unxmlify($data->participants));
1243 $messages = $data->message;
1245 if (!count($messages)) {
1246 logger("empty conversation");
1250 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1254 $conversation = null;
1256 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1257 intval($importer["uid"]),
1261 $conversation = $c[0];
1263 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1264 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1265 intval($importer["uid"]),
1268 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1269 dbesc(datetime_convert()),
1271 dbesc($participants)
1274 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1275 intval($importer["uid"]),
1280 $conversation = $c[0];
1282 if (!$conversation) {
1283 logger("unable to create conversation.");
1287 foreach($messages as $mesg)
1288 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1294 * @brief Creates the body for a "like" message
1296 * @param array $contact The contact that send us the "like"
1297 * @param array $parent_item The item array of the parent item
1298 * @param string $guid message guid
1300 * @return string the body
1302 private function construct_like_body($contact, $parent_item, $guid) {
1303 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1305 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1306 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1307 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1309 return sprintf($bodyverb, $ulink, $alink, $plink);
1313 * @brief Creates a XML object for a "like"
1315 * @param array $importer Array of the importer user
1316 * @param array $parent_item The item array of the parent item
1318 * @return string The XML
1320 private function construct_like_object($importer, $parent_item) {
1321 $objtype = ACTIVITY_OBJ_NOTE;
1322 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1323 $parent_body = $parent_item["body"];
1325 $xmldata = array("object" => array("type" => $objtype,
1327 "id" => $parent_item["uri"],
1330 "content" => $parent_body));
1332 return xml::from_array($xmldata, $xml, true);
1336 * @brief Processes "like" messages
1338 * @param array $importer Array of the importer user
1339 * @param string $sender The sender of the message
1340 * @param object $data The message object
1342 * @return int The message id of the generated like or "false" if there was an error
1344 private function receive_like($importer, $sender, $data) {
1345 $positive = notags(unxmlify($data->positive));
1346 $guid = notags(unxmlify($data->guid));
1347 $parent_type = notags(unxmlify($data->parent_type));
1348 $parent_guid = notags(unxmlify($data->parent_guid));
1349 $author = notags(unxmlify($data->author));
1351 // likes on comments aren't supported by Diaspora - only on posts
1352 // But maybe this will be supported in the future, so we will accept it.
1353 if (!in_array($parent_type, array("Post", "Comment")))
1356 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1360 if (self::message_exists($importer["uid"], $guid))
1363 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1367 $person = self::person_by_handle($author);
1368 if (!is_array($person)) {
1369 logger("unable to find author details");
1373 // Fetch the contact id - if we know this contact
1374 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1376 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1377 // We would accept this anyhow.
1378 if ($positive === "true")
1379 $verb = ACTIVITY_LIKE;
1381 $verb = ACTIVITY_DISLIKE;
1383 $datarray = array();
1385 $datarray["uid"] = $importer["uid"];
1386 $datarray["contact-id"] = $author_contact["cid"];
1387 $datarray["network"] = $author_contact["network"];
1389 $datarray["author-name"] = $person["name"];
1390 $datarray["author-link"] = $person["url"];
1391 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1393 $datarray["owner-name"] = $contact["name"];
1394 $datarray["owner-link"] = $contact["url"];
1395 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1397 $datarray["guid"] = $guid;
1398 $datarray["uri"] = $author.":".$guid;
1400 $datarray["type"] = "activity";
1401 $datarray["verb"] = $verb;
1402 $datarray["gravity"] = GRAVITY_LIKE;
1403 $datarray["parent-uri"] = $parent_item["uri"];
1405 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1406 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1408 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1410 $message_id = item_store($datarray);
1413 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1415 // If we are the origin of the parent we store the original data and notify our followers
1416 if($message_id AND $parent_item["origin"]) {
1418 // Formerly we stored the signed text, the signature and the author in different fields.
1419 // We now store the raw data so that we are more flexible.
1420 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1421 intval($message_id),
1422 dbesc(json_encode($data))
1426 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1433 * @brief Processes private messages
1435 * @param array $importer Array of the importer user
1436 * @param object $data The message object
1438 * @return bool Success?
1440 private function receive_message($importer, $data) {
1441 $guid = notags(unxmlify($data->guid));
1442 $parent_guid = notags(unxmlify($data->parent_guid));
1443 $text = unxmlify($data->text);
1444 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1445 $author = notags(unxmlify($data->author));
1446 $conversation_guid = notags(unxmlify($data->conversation_guid));
1448 $contact = self::allowed_contact_by_handle($importer, $author, true);
1452 $conversation = null;
1454 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1455 intval($importer["uid"]),
1456 dbesc($conversation_guid)
1459 $conversation = $c[0];
1461 logger("conversation not available.");
1467 $body = diaspora2bb($text);
1468 $message_uri = $author.":".$guid;
1470 $person = self::person_by_handle($author);
1472 logger("unable to find author details");
1476 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1477 dbesc($message_uri),
1478 intval($importer["uid"])
1481 logger("duplicate message already delivered.", LOGGER_DEBUG);
1485 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1486 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1487 intval($importer["uid"]),
1489 intval($conversation["id"]),
1490 dbesc($person["name"]),
1491 dbesc($person["photo"]),
1492 dbesc($person["url"]),
1493 intval($contact["id"]),
1494 dbesc($conversation["subject"]),
1498 dbesc($message_uri),
1499 dbesc($author.":".$parent_guid),
1503 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1504 dbesc(datetime_convert()),
1505 intval($conversation["id"])
1512 * @brief Processes participations - unsupported by now
1514 * @param array $importer Array of the importer user
1515 * @param object $data The message object
1517 * @return bool always true
1519 private function receive_participation($importer, $data) {
1520 // I'm not sure if we can fully support this message type
1525 * @brief Processes photos - unneeded
1527 * @param array $importer Array of the importer user
1528 * @param object $data The message object
1530 * @return bool always true
1532 private function receive_photo($importer, $data) {
1533 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1538 * @brief Processes poll participations - unssupported
1540 * @param array $importer Array of the importer user
1541 * @param object $data The message object
1543 * @return bool always true
1545 private function receive_poll_participation($importer, $data) {
1546 // We don't support polls by now
1551 * @brief Processes incoming profile updates
1553 * @param array $importer Array of the importer user
1554 * @param object $data The message object
1556 * @return bool Success
1558 private function receive_profile($importer, $data) {
1559 $author = notags(unxmlify($data->author));
1561 $contact = self::contact_by_handle($importer["uid"], $author);
1565 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1566 $image_url = unxmlify($data->image_url);
1567 $birthday = unxmlify($data->birthday);
1568 $location = diaspora2bb(unxmlify($data->location));
1569 $about = diaspora2bb(unxmlify($data->bio));
1570 $gender = unxmlify($data->gender);
1571 $searchable = (unxmlify($data->searchable) == "true");
1572 $nsfw = (unxmlify($data->nsfw) == "true");
1573 $tags = unxmlify($data->tag_string);
1575 $tags = explode("#", $tags);
1577 $keywords = array();
1578 foreach ($tags as $tag) {
1579 $tag = trim(strtolower($tag));
1584 $keywords = implode(", ", $keywords);
1586 $handle_parts = explode("@", $author);
1587 $nick = $handle_parts[0];
1590 $name = $handle_parts[0];
1592 if( preg_match("|^https?://|", $image_url) === 0)
1593 $image_url = "http://".$handle_parts[1].$image_url;
1595 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1597 // Generic birthday. We don't know the timezone. The year is irrelevant.
1599 $birthday = str_replace("1000", "1901", $birthday);
1601 if ($birthday != "")
1602 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1604 // this is to prevent multiple birthday notifications in a single year
1605 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1607 if(substr($birthday,5) === substr($contact["bd"],5))
1608 $birthday = $contact["bd"];
1610 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1611 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1615 dbesc(datetime_convert()),
1621 intval($contact["id"]),
1622 intval($importer["uid"])
1626 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1627 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1630 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1631 "photo" => $image_url, "name" => $name, "location" => $location,
1632 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1633 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1634 "hide" => !$searchable, "nsfw" => $nsfw);
1636 update_gcontact($gcontact);
1638 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1644 * @brief Processes incoming friend requests
1646 * @param array $importer Array of the importer user
1647 * @param array $contact The contact that send the request
1649 private function receive_request_make_friend($importer, $contact) {
1653 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1654 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1655 intval(CONTACT_IS_FRIEND),
1656 intval($contact["id"]),
1657 intval($importer["uid"])
1660 // send notification
1662 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1663 intval($importer["uid"])
1666 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1668 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1669 intval($importer["uid"])
1672 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1674 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1677 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1678 $arr["uid"] = $importer["uid"];
1679 $arr["contact-id"] = $self[0]["id"];
1681 $arr["type"] = 'wall';
1682 $arr["gravity"] = 0;
1684 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1685 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1686 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1687 $arr["verb"] = ACTIVITY_FRIEND;
1688 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1690 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1691 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1692 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1693 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1695 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1696 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1697 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1698 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1699 $arr["object"] .= "</link></object>\n";
1700 $arr["last-child"] = 1;
1702 $arr["allow_cid"] = $user[0]["allow_cid"];
1703 $arr["allow_gid"] = $user[0]["allow_gid"];
1704 $arr["deny_cid"] = $user[0]["deny_cid"];
1705 $arr["deny_gid"] = $user[0]["deny_gid"];
1707 $i = item_store($arr);
1709 proc_run("php", "include/notifier.php", "activity", $i);
1715 * @brief Processes incoming sharing notification
1717 * @param array $importer Array of the importer user
1718 * @param object $data The message object
1720 * @return bool Success
1722 private function receive_request($importer, $data) {
1723 $author = unxmlify($data->author);
1724 $recipient = unxmlify($data->recipient);
1726 if (!$author || !$recipient)
1729 $contact = self::contact_by_handle($importer["uid"],$author);
1733 // perhaps we were already sharing with this person. Now they're sharing with us.
1734 // That makes us friends.
1736 self::receive_request_make_friend($importer, $contact);
1740 $ret = self::person_by_handle($author);
1742 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1743 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1747 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1749 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1750 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1751 intval($importer["uid"]),
1752 dbesc($ret["network"]),
1753 dbesc($ret["addr"]),
1756 dbesc(normalise_link($ret["url"])),
1758 dbesc($ret["name"]),
1759 dbesc($ret["nick"]),
1760 dbesc($ret["photo"]),
1761 dbesc($ret["pubkey"]),
1762 dbesc($ret["notify"]),
1763 dbesc($ret["poll"]),
1768 // find the contact record we just created
1770 $contact_record = self::contact_by_handle($importer["uid"],$author);
1772 if (!$contact_record) {
1773 logger("unable to locate newly created contact record.");
1777 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1778 intval($importer["uid"])
1781 if($g && intval($g[0]["def_gid"]))
1782 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1784 if($importer["page-flags"] == PAGE_NORMAL) {
1786 $hash = random_string().(string)time(); // Generate a confirm_key
1788 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1789 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1790 intval($importer["uid"]),
1791 intval($contact_record["id"]),
1794 dbesc(t("Sharing notification from Diaspora network")),
1796 dbesc(datetime_convert())
1800 // automatic friend approval
1802 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1804 // technically they are sharing with us (CONTACT_IS_SHARING),
1805 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1806 // we are going to change the relationship and make them a follower.
1808 if($importer["page-flags"] == PAGE_FREELOVE)
1809 $new_relation = CONTACT_IS_FRIEND;
1811 $new_relation = CONTACT_IS_FOLLOWER;
1813 $r = q("UPDATE `contact` SET `rel` = %d,
1821 intval($new_relation),
1822 dbesc(datetime_convert()),
1823 dbesc(datetime_convert()),
1824 intval($contact_record["id"])
1827 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1829 $ret = self::send_share($u[0], $contact_record);
1836 * @brief Fetches a message with a given guid
1838 * @param string $guid message guid
1839 * @param string $orig_author handle of the original post
1840 * @param string $author handle of the sharer
1842 * @return array The fetched item
1844 private function original_item($guid, $orig_author, $author) {
1846 // Do we already have this item?
1847 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1848 `author-name`, `author-link`, `author-avatar`
1849 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1853 logger("reshared message ".$guid." already exists on system.");
1855 // Maybe it is already a reshared item?
1856 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1857 if (self::is_reshare($r[0]["body"], false))
1864 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1865 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1866 $item_id = self::store_by_guid($guid, $server);
1869 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1870 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1871 $item_id = self::store_by_guid($guid, $server);
1874 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1876 $server = "https://".substr($author, strpos($author, "@") + 1);
1877 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1878 $item_id = self::store_by_guid($guid, $server);
1881 $server = "http://".substr($author, strpos($author, "@") + 1);
1882 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1883 $item_id = self::store_by_guid($guid, $server);
1887 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1888 `author-name`, `author-link`, `author-avatar`
1889 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1901 * @brief Processes a reshare message
1903 * @param array $importer Array of the importer user
1904 * @param object $data The message object
1905 * @param string $xml The original XML of the message
1907 * @return int the message id
1909 private function receive_reshare($importer, $data, $xml) {
1910 $root_author = notags(unxmlify($data->root_author));
1911 $root_guid = notags(unxmlify($data->root_guid));
1912 $guid = notags(unxmlify($data->guid));
1913 $author = notags(unxmlify($data->author));
1914 $public = notags(unxmlify($data->public));
1915 $created_at = notags(unxmlify($data->created_at));
1917 $contact = self::allowed_contact_by_handle($importer, $author, false);
1921 if (self::message_exists($importer["uid"], $guid))
1924 $original_item = self::original_item($root_guid, $root_author, $author);
1925 if (!$original_item)
1928 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1930 $datarray = array();
1932 $datarray["uid"] = $importer["uid"];
1933 $datarray["contact-id"] = $contact["id"];
1934 $datarray["network"] = NETWORK_DIASPORA;
1936 $datarray["author-name"] = $contact["name"];
1937 $datarray["author-link"] = $contact["url"];
1938 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1940 $datarray["owner-name"] = $datarray["author-name"];
1941 $datarray["owner-link"] = $datarray["author-link"];
1942 $datarray["owner-avatar"] = $datarray["author-avatar"];
1944 $datarray["guid"] = $guid;
1945 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1947 $datarray["verb"] = ACTIVITY_POST;
1948 $datarray["gravity"] = GRAVITY_PARENT;
1950 $datarray["object"] = $xml;
1952 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1953 $original_item["guid"], $original_item["created"], $orig_url);
1954 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1956 $datarray["tag"] = $original_item["tag"];
1957 $datarray["app"] = $original_item["app"];
1959 $datarray["plink"] = self::plink($author, $guid);
1960 $datarray["private"] = (($public == "false") ? 1 : 0);
1961 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1963 $datarray["object-type"] = $original_item["object-type"];
1965 self::fetch_guid($datarray);
1966 $message_id = item_store($datarray);
1969 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1975 * @brief Processes retractions
1977 * @param array $importer Array of the importer user
1978 * @param array $contact The contact of the item owner
1979 * @param object $data The message object
1981 * @return bool success
1983 private function item_retraction($importer, $contact, $data) {
1984 $target_type = notags(unxmlify($data->target_type));
1985 $target_guid = notags(unxmlify($data->target_guid));
1986 $author = notags(unxmlify($data->author));
1988 $person = self::person_by_handle($author);
1989 if (!is_array($person)) {
1990 logger("unable to find author detail for ".$author);
1994 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1995 dbesc($target_guid),
1996 intval($importer["uid"])
2001 // Only delete it if the author really fits
2002 if (!link_compare($r[0]["author-link"], $person["url"])) {
2003 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
2007 // Check if the sender is the thread owner
2008 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2009 intval($r[0]["parent"]));
2011 // Only delete it if the parent author really fits
2012 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2013 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2017 // 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
2018 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2019 dbesc(datetime_convert()),
2020 dbesc(datetime_convert()),
2023 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2025 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2027 // Now check if the retraction needs to be relayed by us
2028 if($p[0]["origin"]) {
2030 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
2037 * @brief Receives retraction messages
2039 * @param array $importer Array of the importer user
2040 * @param string $sender The sender of the message
2041 * @param object $data The message object
2043 * @return bool Success
2045 private function receive_retraction($importer, $sender, $data) {
2046 $target_type = notags(unxmlify($data->target_type));
2048 $contact = self::contact_by_handle($importer["uid"], $sender);
2050 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2054 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2056 switch ($target_type) {
2059 case "Post": // "Post" will be supported in a future version
2061 case "StatusMessage":
2062 return self::item_retraction($importer, $contact, $data);;
2065 /// @todo What should we do with an "unshare"?
2066 // Removing the contact isn't correct since we still can read the public items
2067 //contact_remove($contact["id"]);
2071 logger("Unknown target type ".$target_type);
2078 * @brief Receives status messages
2080 * @param array $importer Array of the importer user
2081 * @param object $data The message object
2082 * @param string $xml The original XML of the message
2084 * @return int The message id of the newly created item
2086 private function receive_status_message($importer, $data, $xml) {
2088 $raw_message = unxmlify($data->raw_message);
2089 $guid = notags(unxmlify($data->guid));
2090 $author = notags(unxmlify($data->author));
2091 $public = notags(unxmlify($data->public));
2092 $created_at = notags(unxmlify($data->created_at));
2093 $provider_display_name = notags(unxmlify($data->provider_display_name));
2095 /// @todo enable support for polls
2096 //if ($data->poll) {
2097 // foreach ($data->poll AS $poll)
2101 $contact = self::allowed_contact_by_handle($importer, $author, false);
2105 if (self::message_exists($importer["uid"], $guid))
2109 if ($data->location)
2110 foreach ($data->location->children() AS $fieldname => $data)
2111 $address[$fieldname] = notags(unxmlify($data));
2113 $body = diaspora2bb($raw_message);
2115 $datarray = array();
2118 foreach ($data->photo AS $photo)
2119 $body = "[img]".unxmlify($photo->remote_photo_path).
2120 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2122 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2124 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2126 // Add OEmbed and other information to the body
2127 if (!self::is_redmatrix($contact["url"]))
2128 $body = add_page_info_to_body($body, false, true);
2131 $datarray["uid"] = $importer["uid"];
2132 $datarray["contact-id"] = $contact["id"];
2133 $datarray["network"] = NETWORK_DIASPORA;
2135 $datarray["author-name"] = $contact["name"];
2136 $datarray["author-link"] = $contact["url"];
2137 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2139 $datarray["owner-name"] = $datarray["author-name"];
2140 $datarray["owner-link"] = $datarray["author-link"];
2141 $datarray["owner-avatar"] = $datarray["author-avatar"];
2143 $datarray["guid"] = $guid;
2144 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
2146 $datarray["verb"] = ACTIVITY_POST;
2147 $datarray["gravity"] = GRAVITY_PARENT;
2149 $datarray["object"] = $xml;
2151 $datarray["body"] = $body;
2153 if ($provider_display_name != "")
2154 $datarray["app"] = $provider_display_name;
2156 $datarray["plink"] = self::plink($author, $guid);
2157 $datarray["private"] = (($public == "false") ? 1 : 0);
2158 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2160 if (isset($address["address"]))
2161 $datarray["location"] = $address["address"];
2163 if (isset($address["lat"]) AND isset($address["lng"]))
2164 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2166 self::fetch_guid($datarray);
2167 $message_id = item_store($datarray);
2170 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2175 /******************************************************************************************
2176 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2177 ******************************************************************************************/
2180 * @brief returnes the handle of a contact
2182 * @param array $me contact array
2184 * @return string the handle in the format user@domain.tld
2186 private function my_handle($contact) {
2187 if ($contact["addr"] != "")
2188 return $contact["addr"];
2190 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2191 // So - just in case - we build the the address here.
2192 if ($contact["nickname"] != "")
2193 $nick = $contact["nickname"];
2195 $nick = $contact["nick"];
2197 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2201 * @brief Creates the envelope for a public message
2203 * @param string $msg The message that is to be transmitted
2204 * @param array $user The record of the sender
2205 * @param array $contact Target of the communication
2206 * @param string $prvkey The private key of the sender
2207 * @param string $pubkey The public key of the receiver
2209 * @return string The envelope
2211 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2213 logger("Message: ".$msg, LOGGER_DATA);
2215 $handle = self::my_handle($user);
2217 $b64url_data = base64url_encode($msg);
2219 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2221 $type = "application/xml";
2222 $encoding = "base64url";
2223 $alg = "RSA-SHA256";
2225 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2227 $signature = rsa_sign($signable_data,$prvkey);
2228 $sig = base64url_encode($signature);
2230 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2231 "me:env" => array("me:encoding" => "base64url",
2232 "me:alg" => "RSA-SHA256",
2234 "@attributes" => array("type" => "application/xml"),
2235 "me:sig" => $sig)));
2237 $namespaces = array("" => "https://joindiaspora.com/protocol",
2238 "me" => "http://salmon-protocol.org/ns/magic-env");
2240 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2242 logger("magic_env: ".$magic_env, LOGGER_DATA);
2247 * @brief Creates the envelope for a private message
2249 * @param string $msg The message that is to be transmitted
2250 * @param array $user The record of the sender
2251 * @param array $contact Target of the communication
2252 * @param string $prvkey The private key of the sender
2253 * @param string $pubkey The public key of the receiver
2255 * @return string The envelope
2257 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2259 logger("Message: ".$msg, LOGGER_DATA);
2261 // without a public key nothing will work
2264 logger("pubkey missing: contact id: ".$contact["id"]);
2268 $inner_aes_key = random_string(32);
2269 $b_inner_aes_key = base64_encode($inner_aes_key);
2270 $inner_iv = random_string(16);
2271 $b_inner_iv = base64_encode($inner_iv);
2273 $outer_aes_key = random_string(32);
2274 $b_outer_aes_key = base64_encode($outer_aes_key);
2275 $outer_iv = random_string(16);
2276 $b_outer_iv = base64_encode($outer_iv);
2278 $handle = self::my_handle($user);
2280 $padded_data = pkcs5_pad($msg,16);
2281 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2283 $b64_data = base64_encode($inner_encrypted);
2286 $b64url_data = base64url_encode($b64_data);
2287 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2289 $type = "application/xml";
2290 $encoding = "base64url";
2291 $alg = "RSA-SHA256";
2293 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2295 $signature = rsa_sign($signable_data,$prvkey);
2296 $sig = base64url_encode($signature);
2298 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2299 "aes_key" => $b_inner_aes_key,
2300 "author_id" => $handle));
2302 $decrypted_header = xml::from_array($xmldata, $xml, true);
2303 $decrypted_header = pkcs5_pad($decrypted_header,16);
2305 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2307 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2309 $encrypted_outer_key_bundle = "";
2310 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2312 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2314 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2316 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2317 "ciphertext" => base64_encode($ciphertext)));
2318 $cipher_json = base64_encode($encrypted_header_json_object);
2320 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2321 "me:env" => array("me:encoding" => "base64url",
2322 "me:alg" => "RSA-SHA256",
2324 "@attributes" => array("type" => "application/xml"),
2325 "me:sig" => $sig)));
2327 $namespaces = array("" => "https://joindiaspora.com/protocol",
2328 "me" => "http://salmon-protocol.org/ns/magic-env");
2330 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2332 logger("magic_env: ".$magic_env, LOGGER_DATA);
2337 * @brief Create the envelope for a message
2339 * @param string $msg The message that is to be transmitted
2340 * @param array $user The record of the sender
2341 * @param array $contact Target of the communication
2342 * @param string $prvkey The private key of the sender
2343 * @param string $pubkey The public key of the receiver
2344 * @param bool $public Is the message public?
2346 * @return string The message that will be transmitted to other servers
2348 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2351 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2353 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2355 // The data that will be transmitted is double encoded via "urlencode", strange ...
2356 $slap = "xml=".urlencode(urlencode($magic_env));
2361 * @brief Creates a signature for a message
2363 * @param array $owner the array of the owner of the message
2364 * @param array $message The message that is to be signed
2366 * @return string The signature
2368 private function signature($owner, $message) {
2370 unset($sigmsg["author_signature"]);
2371 unset($sigmsg["parent_author_signature"]);
2373 $signed_text = implode(";", $sigmsg);
2375 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2379 * @brief Transmit a message to a target server
2381 * @param array $owner the array of the item owner
2382 * @param array $contact Target of the communication
2383 * @param string $slap The message that is to be transmitted
2384 * @param bool $public_batch Is it a public post?
2385 * @param bool $queue_run Is the transmission called from the queue?
2386 * @param string $guid message guid
2388 * @return int Result of the transmission
2390 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2394 $enabled = intval(get_config("system", "diaspora_enabled"));
2398 $logid = random_string(4);
2399 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2401 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2405 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2407 if (!$queue_run && was_recently_delayed($contact["id"])) {
2410 if (!intval(get_config("system", "diaspora_test"))) {
2411 post_url($dest_url."/", $slap);
2412 $return_code = $a->get_curl_code();
2414 logger("test_mode");
2419 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2421 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2422 logger("queue message");
2424 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2425 intval($contact["id"]),
2426 dbesc(NETWORK_DIASPORA),
2428 intval($public_batch)
2431 logger("add_to_queue ignored - identical item already in queue");
2433 // queue message for redelivery
2434 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2438 return(($return_code) ? $return_code : (-1));
2443 * @brief Builds and transmit messages
2445 * @param array $owner the array of the item owner
2446 * @param array $contact Target of the communication
2447 * @param string $type The message type
2448 * @param array $message The message data
2449 * @param bool $public_batch Is it a public post?
2450 * @param string $guid message guid
2451 * @param bool $spool Should the transmission be spooled or transmitted?
2453 * @return int Result of the transmission
2455 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2457 $data = array("XML" => array("post" => array($type => $message)));
2459 $msg = xml::from_array($data, $xml);
2461 logger('message: '.$msg, LOGGER_DATA);
2462 logger('send guid '.$guid, LOGGER_DEBUG);
2464 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2467 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2470 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2472 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2474 return $return_code;
2478 * @brief Sends a "share" message
2480 * @param array $owner the array of the item owner
2481 * @param array $contact Target of the communication
2483 * @return int The result of the transmission
2485 public static function send_share($owner,$contact) {
2487 $message = array("sender_handle" => self::my_handle($owner),
2488 "recipient_handle" => $contact["addr"]);
2490 return self::build_and_transmit($owner, $contact, "request", $message);
2494 * @brief sends an "unshare"
2496 * @param array $owner the array of the item owner
2497 * @param array $contact Target of the communication
2499 * @return int The result of the transmission
2501 public static function send_unshare($owner,$contact) {
2503 $message = array("post_guid" => $owner["guid"],
2504 "diaspora_handle" => self::my_handle($owner),
2505 "type" => "Person");
2507 return self::build_and_transmit($owner, $contact, "retraction", $message);
2511 * @brief Checks a message body if it is a reshare
2513 * @param string $body The message body that is to be check
2514 * @param bool $complete Should it be a complete check or a simple check?
2516 * @return array|bool Reshare details or "false" if no reshare
2518 public static function is_reshare($body, $complete = true) {
2519 $body = trim($body);
2521 // Skip if it isn't a pure repeated messages
2522 // Does it start with a share?
2523 if (strpos($body, "[share") > 0)
2526 // Does it end with a share?
2527 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2530 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2531 // Skip if there is no shared message in there
2532 if ($body == $attributes)
2535 // If we don't do the complete check we quit here
2540 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2541 if ($matches[1] != "")
2542 $guid = $matches[1];
2544 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2545 if ($matches[1] != "")
2546 $guid = $matches[1];
2549 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2550 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2553 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2554 $ret["root_guid"] = $guid;
2560 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2561 if ($matches[1] != "")
2562 $profile = $matches[1];
2564 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2565 if ($matches[1] != "")
2566 $profile = $matches[1];
2570 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2571 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2575 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2576 if ($matches[1] != "")
2577 $link = $matches[1];
2579 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2580 if ($matches[1] != "")
2581 $link = $matches[1];
2583 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2584 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2590 * @brief Sends a post
2592 * @param array $item The item that will be exported
2593 * @param array $owner the array of the item owner
2594 * @param array $contact Target of the communication
2595 * @param bool $public_batch Is it a public post?
2597 * @return int The result of the transmission
2599 public static function send_status($item, $owner, $contact, $public_batch = false) {
2601 $myaddr = self::my_handle($owner);
2603 $public = (($item["private"]) ? "false" : "true");
2605 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2607 // Detect a share element and do a reshare
2608 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2609 $message = array("root_diaspora_id" => $ret["root_handle"],
2610 "root_guid" => $ret["root_guid"],
2611 "guid" => $item["guid"],
2612 "diaspora_handle" => $myaddr,
2613 "public" => $public,
2614 "created_at" => $created,
2615 "provider_display_name" => $item["app"]);
2619 $title = $item["title"];
2620 $body = $item["body"];
2622 // convert to markdown
2623 $body = html_entity_decode(bb2diaspora($body));
2627 $body = "## ".html_entity_decode($title)."\n\n".$body;
2629 if ($item["attach"]) {
2630 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2632 $body .= "\n".t("Attachments:")."\n";
2633 foreach($matches as $mtch)
2634 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2638 $location = array();
2640 if ($item["location"] != "")
2641 $location["address"] = $item["location"];
2643 if ($item["coord"] != "") {
2644 $coord = explode(" ", $item["coord"]);
2645 $location["lat"] = $coord[0];
2646 $location["lng"] = $coord[1];
2649 $message = array("raw_message" => $body,
2650 "location" => $location,
2651 "guid" => $item["guid"],
2652 "diaspora_handle" => $myaddr,
2653 "public" => $public,
2654 "created_at" => $created,
2655 "provider_display_name" => $item["app"]);
2657 if (count($location) == 0)
2658 unset($message["location"]);
2660 $type = "status_message";
2663 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2667 * @brief Creates a "like" object
2669 * @param array $item The item that will be exported
2670 * @param array $owner the array of the item owner
2672 * @return array The data for a "like"
2674 private function construct_like($item, $owner) {
2676 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2677 dbesc($item["thr-parent"]));
2683 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2686 return(array("positive" => $positive,
2687 "guid" => $item["guid"],
2688 "target_type" => $target_type,
2689 "parent_guid" => $parent["guid"],
2690 "author_signature" => "",
2691 "diaspora_handle" => self::my_handle($owner)));
2695 * @brief Creates the object for a comment
2697 * @param array $item The item that will be exported
2698 * @param array $owner the array of the item owner
2700 * @return array The data for a comment
2702 private function construct_comment($item, $owner) {
2704 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2705 intval($item["parent"]),
2706 intval($item["parent"])
2714 $text = html_entity_decode(bb2diaspora($item["body"]));
2716 return(array("guid" => $item["guid"],
2717 "parent_guid" => $parent["guid"],
2718 "author_signature" => "",
2720 "diaspora_handle" => self::my_handle($owner)));
2724 * @brief Send a like or a comment
2726 * @param array $item The item that will be exported
2727 * @param array $owner the array of the item owner
2728 * @param array $contact Target of the communication
2729 * @param bool $public_batch Is it a public post?
2731 * @return int The result of the transmission
2733 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2735 if($item['verb'] === ACTIVITY_LIKE) {
2736 $message = self::construct_like($item, $owner);
2739 $message = self::construct_comment($item, $owner);
2746 $message["author_signature"] = self::signature($owner, $message);
2748 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2752 * @brief Creates a message from a signature record entry
2754 * @param array $item The item that will be exported
2755 * @param array $signature The entry of the "sign" record
2757 * @return string The message
2759 private function message_from_signature($item, $signature) {
2761 // Split the signed text
2762 $signed_parts = explode(";", $signature['signed_text']);
2764 if ($item["deleted"])
2765 $message = array("parent_author_signature" => "",
2766 "target_guid" => $signed_parts[0],
2767 "target_type" => $signed_parts[1],
2768 "sender_handle" => $signature['signer'],
2769 "target_author_signature" => $signature['signature']);
2770 elseif ($item['verb'] === ACTIVITY_LIKE)
2771 $message = array("positive" => $signed_parts[0],
2772 "guid" => $signed_parts[1],
2773 "target_type" => $signed_parts[2],
2774 "parent_guid" => $signed_parts[3],
2775 "parent_author_signature" => "",
2776 "author_signature" => $signature['signature'],
2777 "diaspora_handle" => $signed_parts[4]);
2779 // Remove the comment guid
2780 $guid = array_shift($signed_parts);
2782 // Remove the parent guid
2783 $parent_guid = array_shift($signed_parts);
2785 // Remove the handle
2786 $handle = array_pop($signed_parts);
2788 // Glue the parts together
2789 $text = implode(";", $signed_parts);
2791 $message = array("guid" => $guid,
2792 "parent_guid" => $parent_guid,
2793 "parent_author_signature" => "",
2794 "author_signature" => $signature['signature'],
2795 "text" => implode(";", $signed_parts),
2796 "diaspora_handle" => $handle);
2802 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
2804 * @param array $item The item that will be exported
2805 * @param array $owner the array of the item owner
2806 * @param array $contact Target of the communication
2807 * @param bool $public_batch Is it a public post?
2809 * @return int The result of the transmission
2811 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2813 if ($item["deleted"])
2814 return self::send_retraction($item, $owner, $contact, $public_batch, true);
2815 elseif ($item['verb'] === ACTIVITY_LIKE)
2820 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2822 // fetch the original signature
2824 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
2825 intval($item["id"]));
2828 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2834 // Old way - is used by the internal Friendica functions
2835 /// @todo Change all signatur storing functions to the new format
2836 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2837 $message = self::message_from_signature($item, $signature);
2839 $msg = json_decode($signature['signed_text'], true);
2842 if (is_array($msg)) {
2843 foreach ($msg AS $field => $data) {
2844 if (!$item["deleted"]) {
2845 if ($field == "author")
2846 $field = "diaspora_handle";
2847 if ($field == "parent_type")
2848 $field = "target_type";
2851 $message[$field] = $data;
2854 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2857 $message["parent_author_signature"] = self::signature($owner, $message);
2859 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2861 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2865 * @brief Sends a retraction (deletion) of a message, like or comment
2867 * @param array $item The item that will be exported
2868 * @param array $owner the array of the item owner
2869 * @param array $contact Target of the communication
2870 * @param bool $public_batch Is it a public post?
2871 * @param bool $relay Is the retraction transmitted from a relay?
2873 * @return int The result of the transmission
2875 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
2877 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
2879 // Check whether the retraction is for a top-level post or whether it's a relayable
2880 if ($item["uri"] !== $item["parent-uri"]) {
2881 $msg_type = "relayable_retraction";
2882 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2884 $msg_type = "signed_retraction";
2885 $target_type = "StatusMessage";
2888 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
2889 $signature = "parent_author_signature";
2891 $signature = "target_author_signature";
2893 $signed_text = $item["guid"].";".$target_type;
2895 $message = array("target_guid" => $item['guid'],
2896 "target_type" => $target_type,
2897 "sender_handle" => $itemaddr,
2898 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2900 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2902 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2906 * @brief Sends a mail
2908 * @param array $item The item that will be exported
2909 * @param array $owner The owner
2910 * @param array $contact Target of the communication
2912 * @return int The result of the transmission
2914 public static function send_mail($item, $owner, $contact) {
2916 $myaddr = self::my_handle($owner);
2918 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2919 intval($item["convid"]),
2920 intval($item["uid"])
2924 logger("conversation not found.");
2930 "guid" => $cnv["guid"],
2931 "subject" => $cnv["subject"],
2932 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2933 "diaspora_handle" => $cnv["creator"],
2934 "participant_handles" => $cnv["recips"]
2937 $body = bb2diaspora($item["body"]);
2938 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2940 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2941 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2944 "guid" => $item["guid"],
2945 "parent_guid" => $cnv["guid"],
2946 "parent_author_signature" => $sig,
2947 "author_signature" => $sig,
2949 "created_at" => $created,
2950 "diaspora_handle" => $myaddr,
2951 "conversation_guid" => $cnv["guid"]
2954 if ($item["reply"]) {
2958 $message = array("guid" => $cnv["guid"],
2959 "subject" => $cnv["subject"],
2960 "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"]);
2965 $type = "conversation";
2968 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2972 * @brief Sends profile data
2974 * @param int $uid The user id
2976 public static function send_profile($uid) {
2981 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2982 AND `uid` = %d AND `rel` != %d",
2983 dbesc(NETWORK_DIASPORA),
2985 intval(CONTACT_IS_SHARING)
2990 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2992 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2993 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2994 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3003 $handle = $profile["addr"];
3004 $first = ((strpos($profile['name'],' ')
3005 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3006 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3007 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3008 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3009 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3010 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3012 if ($searchable === 'true') {
3013 $dob = '1000-00-00';
3015 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3016 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3018 $about = $profile['about'];
3019 $about = strip_tags(bbcode($about));
3021 $location = formatted_location($profile);
3023 if ($profile['pub_keywords']) {
3024 $kw = str_replace(',',' ',$profile['pub_keywords']);
3025 $kw = str_replace(' ',' ',$kw);
3026 $arr = explode(' ',$profile['pub_keywords']);
3028 for($x = 0; $x < 5; $x ++) {
3030 $tags .= '#'. trim($arr[$x]) .' ';
3034 $tags = trim($tags);
3037 $message = array("diaspora_handle" => $handle,
3038 "first_name" => $first,
3039 "last_name" => $last,
3040 "image_url" => $large,
3041 "image_url_medium" => $medium,
3042 "image_url_small" => $small,
3044 "gender" => $profile['gender'],
3046 "location" => $location,
3047 "searchable" => $searchable,
3048 "tag_string" => $tags);
3050 foreach($recips as $recip)
3051 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3055 * @brief Stores the signature for likes that are created on our system
3057 * @param array $contact The contact array of the "like"
3058 * @param int $post_id The post id of the "like"
3060 * @return bool Success
3062 function store_like_signature($contact, $post_id) {
3064 $enabled = intval(get_config('system','diaspora_enabled'));
3066 logger('Diaspora support disabled, not storing like signature', LOGGER_DEBUG);
3070 // Is the contact the owner? Then fetch the private key
3071 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3072 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3076 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3080 $contact["uprvkey"] = $r[0]['prvkey'];
3082 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3086 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3089 $message = self::construct_like($r[0], $contact);
3090 $message["author_signature"] = self::signature($contact, $message);
3092 // In the future we will store the signature more flexible to support new fields.
3093 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3094 // (We are transmitting this data here via DFRN)
3096 $signed_text = $message["positive"].";".$message["guid"].";".$message["target_type"].";".
3097 $message["parent_guid"].";".$message["diaspora_handle"];
3099 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3101 dbesc($signed_text),
3102 dbesc($message["author_signature"]),
3103 dbesc($message["diaspora_handle"])
3106 // This here will replace the lines above, once Diaspora changed its protocol
3107 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3108 // intval($message_id),
3109 // dbesc(json_encode($message))
3112 logger('Stored diaspora like signature');
3117 * @brief Stores the signature for comments that are created on our system
3119 * @param array $item The item array of the comment
3120 * @param array $contact The contact array of the item owner
3121 * @param string $uprvkey The private key of the sender
3122 * @param int $message_id The message id of the comment
3124 * @return bool Success
3126 function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3128 if ($uprvkey == "") {
3129 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3133 $enabled = intval(get_config('system','diaspora_enabled'));
3135 logger('Diaspora support disabled, not storing comment signature', LOGGER_DEBUG);
3139 $contact["uprvkey"] = $uprvkey;
3141 $message = self::construct_comment($item, $contact);
3142 $message["author_signature"] = self::signature($contact, $message);
3144 // In the future we will store the signature more flexible to support new fields.
3145 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3146 // (We are transmitting this data here via DFRN)
3147 $signed_text = $message["guid"].";".$message["parent_guid"].";".
3148 $message["text"].";".$message["diaspora_handle"];
3150 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3151 intval($message_id),
3152 dbesc($signed_text),
3153 dbesc($message["author_signature"]),
3154 dbesc($message["diaspora_handle"])
3157 // This here will replace the lines above, once Diaspora changed its protocol
3158 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3159 // intval($message_id),
3160 // dbesc(json_encode($message))
3163 logger('Stored diaspora comment signature');