3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * Currently this implementation here interprets the old and the new protocol and sends the old one.
8 * This will change in the future.
11 use \Friendica\Core\Config;
13 require_once 'include/items.php';
14 require_once 'include/bb2diaspora.php';
15 require_once 'include/Scrape.php';
16 require_once 'include/Contact.php';
17 require_once 'include/Photo.php';
18 require_once 'include/socgraph.php';
19 require_once 'include/group.php';
20 require_once 'include/xml.php';
21 require_once 'include/datetime.php';
22 require_once 'include/queue_fn.php';
23 require_once 'include/cache.php';
26 * @brief This class contain functions to create and send Diaspora XML files
32 * @brief Return a list of relay servers
34 * This is an experimental Diaspora feature.
36 * @return array of relay servers
38 public static function relay_list() {
40 $serverdata = get_config("system", "relay_server");
41 if ($serverdata == "")
46 $servers = explode(",", $serverdata);
48 foreach ($servers AS $server) {
49 $server = trim($server);
50 $addr = "relay@".str_replace("http://", "", normalise_link($server));
51 $batch = $server."/receive/public";
53 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
54 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
57 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
58 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
63 dbesc(normalise_link($server)),
65 dbesc(NETWORK_DIASPORA),
66 intval(CONTACT_IS_FOLLOWER),
67 dbesc(datetime_convert()),
68 dbesc(datetime_convert()),
69 dbesc(datetime_convert())
72 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
74 $relay[] = $relais[0];
76 $relay[] = $relais[0];
83 * @brief repairs a signature that was double encoded
85 * The function is unused at the moment. It was copied from the old implementation.
87 * @param string $signature The signature
88 * @param string $handle The handle of the signature owner
89 * @param integer $level This value is only set inside this function to avoid endless loops
91 * @return string the repaired signature
93 private static function repair_signature($signature, $handle = "", $level = 1) {
98 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
99 $signature = base64_decode($signature);
100 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
102 // Do a recursive call to be able to fix even multiple levels
104 $signature = self::repair_signature($signature, $handle, ++$level);
111 * @brief verify the envelope and return the verified data
113 * @param string $envelope The magic envelope
115 * @return string verified data
117 private static function verify_magic_envelope($envelope) {
119 $basedom = parse_xml_string($envelope, false);
121 if (!is_object($basedom)) {
122 logger("Envelope is no XML file");
126 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
128 if (sizeof($children) == 0) {
129 logger("XML has no children");
135 $data = base64url_decode($children->data);
136 $type = $children->data->attributes()->type[0];
138 $encoding = $children->encoding;
140 $alg = $children->alg;
142 $sig = base64url_decode($children->sig);
143 $key_id = $children->sig->attributes()->key_id[0];
145 $handle = base64url_decode($key_id);
147 $b64url_data = base64url_encode($data);
148 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
150 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
152 $key = self::key($handle);
154 $verify = rsa_verify($signable_data, $sig, $key);
156 logger('Message did not verify. Discarding.');
164 * @brief encrypts data via AES
166 * @param string $key The AES key
167 * @param string $iv The IV (is used for CBC encoding)
168 * @param string $data The data that is to be encrypted
170 * @return string encrypted data
172 private static function aes_encrypt($key, $iv, $data) {
173 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
177 * @brief decrypts data via AES
179 * @param string $key The AES key
180 * @param string $iv The IV (is used for CBC encoding)
181 * @param string $encrypted The encrypted data
183 * @return string decrypted data
185 private static function aes_decrypt($key, $iv, $encrypted) {
186 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
190 * @brief: Decodes incoming Diaspora message
192 * @param array $importer Array of the importer user
193 * @param string $xml urldecoded Diaspora salmon
196 * 'message' -> decoded Diaspora XML message
197 * 'author' -> author diaspora handle
198 * 'key' -> author public key (converted to pkcs#8)
200 public static function decode($importer, $xml) {
203 $basedom = parse_xml_string($xml);
205 if (!is_object($basedom))
208 $children = $basedom->children('https://joindiaspora.com/protocol');
210 if ($children->header) {
212 $author_link = str_replace('acct:','',$children->header->author_id);
215 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
217 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
218 $ciphertext = base64_decode($encrypted_header->ciphertext);
220 $outer_key_bundle = '';
221 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
223 $j_outer_key_bundle = json_decode($outer_key_bundle);
225 $outer_iv = base64_decode($j_outer_key_bundle->iv);
226 $outer_key = base64_decode($j_outer_key_bundle->key);
228 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
230 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
231 $idom = parse_xml_string($decrypted,false);
233 $inner_iv = base64_decode($idom->iv);
234 $inner_aes_key = base64_decode($idom->aes_key);
236 $author_link = str_replace('acct:','',$idom->author_id);
239 $dom = $basedom->children(NAMESPACE_SALMON_ME);
241 // figure out where in the DOM tree our data is hiding
243 if ($dom->provenance->data)
244 $base = $dom->provenance;
245 elseif ($dom->env->data)
251 logger('unable to locate salmon data in xml');
252 http_status_exit(400);
256 // Stash the signature away for now. We have to find their key or it won't be good for anything.
257 $signature = base64url_decode($base->sig);
261 // strip whitespace so our data element will return to one big base64 blob
262 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
265 // stash away some other stuff for later
267 $type = $base->data[0]->attributes()->type[0];
268 $keyhash = $base->sig[0]->attributes()->keyhash[0];
269 $encoding = $base->encoding;
273 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
277 $data = base64url_decode($data);
281 $inner_decrypted = $data;
284 // Decode the encrypted blob
286 $inner_encrypted = base64_decode($data);
287 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
291 logger('Could not retrieve author URI.');
292 http_status_exit(400);
294 // Once we have the author URI, go to the web and try to find their public key
295 // (first this will look it up locally if it is in the fcontact cache)
296 // This will also convert diaspora public key from pkcs#1 to pkcs#8
298 logger('Fetching key for '.$author_link);
299 $key = self::key($author_link);
302 logger('Could not retrieve author key.');
303 http_status_exit(400);
306 $verify = rsa_verify($signed_data,$signature,$key);
309 logger('Message did not verify. Discarding.');
310 http_status_exit(400);
313 logger('Message verified.');
315 return array('message' => (string)$inner_decrypted,
316 'author' => unxmlify($author_link),
317 'key' => (string)$key);
322 * @brief Dispatches public messages and find the fitting receivers
324 * @param array $msg The post that will be dispatched
326 * @return int The message id of the generated message, "true" or "false" if there was an error
328 public static function dispatch_public($msg) {
330 $enabled = intval(get_config("system", "diaspora_enabled"));
332 logger("diaspora is disabled");
336 if (!self::valid_posting($msg, $fields)) {
337 logger("Invalid posting");
341 // Is it a an action (comment, like, ...) for our own post?
342 if (isset($fields->parent_guid)) {
343 $guid = notags(unxmlify($fields->parent_guid));
345 $importer = self::importer_for_guid($guid);
346 if (is_array($importer)) {
347 logger("delivering to origin: ".$importer["name"]);
348 $message_id = self::dispatch($importer, $msg);
353 // Now distribute it to the followers
354 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
355 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
356 AND NOT `account_expired` AND NOT `account_removed`",
357 dbesc(NETWORK_DIASPORA),
358 dbesc($msg["author"])
361 if (dbm::is_result($r)) {
362 foreach ($r as $rr) {
363 logger("delivering to: ".$rr["username"]);
364 self::dispatch($rr, $msg);
366 } elseif (!Config::get('system', 'relay_subscribe', false)) {
367 logger("Unwanted message from ".$sender." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
369 // Use a dummy importer to import the data for the public copy
370 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
371 $message_id = self::dispatch($importer, $msg);
378 * @brief Dispatches the different message types to the different functions
380 * @param array $importer Array of the importer user
381 * @param array $msg The post that will be dispatched
383 * @return int The message id of the generated message, "true" or "false" if there was an error
385 public static function dispatch($importer, $msg) {
387 // The sender is the handle of the contact that sent the message.
388 // This will often be different with relayed messages (for example "like" and "comment")
389 $sender = $msg["author"];
391 if (!self::valid_posting($msg, $fields)) {
392 logger("Invalid posting");
396 $type = $fields->getName();
398 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
401 case "account_deletion":
402 return self::receive_account_deletion($importer, $fields);
405 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
408 return self::receive_contact_request($importer, $fields);
411 return self::receive_conversation($importer, $msg, $fields);
414 return self::receive_like($importer, $sender, $fields);
417 return self::receive_message($importer, $fields);
419 case "participation": // Not implemented
420 return self::receive_participation($importer, $fields);
422 case "photo": // Not implemented
423 return self::receive_photo($importer, $fields);
425 case "poll_participation": // Not implemented
426 return self::receive_poll_participation($importer, $fields);
429 return self::receive_profile($importer, $fields);
432 return self::receive_reshare($importer, $fields, $msg["message"]);
435 return self::receive_retraction($importer, $sender, $fields);
437 case "status_message":
438 return self::receive_status_message($importer, $fields, $msg["message"]);
441 logger("Unknown message type ".$type);
449 * @brief Checks if a posting is valid and fetches the data fields.
451 * This function does not only check the signature.
452 * It also does the conversion between the old and the new diaspora format.
454 * @param array $msg Array with the XML, the sender handle and the sender signature
455 * @param object $fields SimpleXML object that contains the posting when it is valid
457 * @return bool Is the posting valid?
459 private static function valid_posting($msg, &$fields) {
461 $data = parse_xml_string($msg["message"], false);
463 if (!is_object($data)) {
464 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
468 $first_child = $data->getName();
470 // Is this the new or the old version?
471 if ($data->getName() == "XML") {
473 foreach ($data->post->children() as $child)
480 $type = $element->getName();
483 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
485 // All retractions are handled identically from now on.
486 // In the new version there will only be "retraction".
487 if (in_array($type, array("signed_retraction", "relayable_retraction")))
488 $type = "retraction";
490 if ($type == "request")
493 $fields = new SimpleXMLElement("<".$type."/>");
497 foreach ($element->children() AS $fieldname => $entry) {
499 // Translation for the old XML structure
500 if ($fieldname == "diaspora_handle")
501 $fieldname = "author";
503 if ($fieldname == "participant_handles")
504 $fieldname = "participants";
506 if (in_array($type, array("like", "participation"))) {
507 if ($fieldname == "target_type")
508 $fieldname = "parent_type";
511 if ($fieldname == "sender_handle")
512 $fieldname = "author";
514 if ($fieldname == "recipient_handle")
515 $fieldname = "recipient";
517 if ($fieldname == "root_diaspora_id")
518 $fieldname = "root_author";
520 if ($type == "retraction") {
521 if ($fieldname == "post_guid")
522 $fieldname = "target_guid";
524 if ($fieldname == "type")
525 $fieldname = "target_type";
529 if (($fieldname == "author_signature") AND ($entry != ""))
530 $author_signature = base64_decode($entry);
531 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
532 $parent_author_signature = base64_decode($entry);
533 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
534 if ($signed_data != "") {
536 $signed_data_parent .= ";";
539 $signed_data .= $entry;
541 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
542 ($orig_type == "relayable_retraction"))
543 xml::copy($entry, $fields, $fieldname);
546 // This is something that shouldn't happen at all.
547 if (in_array($type, array("status_message", "reshare", "profile")))
548 if ($msg["author"] != $fields->author) {
549 logger("Message handle is not the same as envelope sender. Quitting this message.");
553 // Only some message types have signatures. So we quit here for the other types.
554 if (!in_array($type, array("comment", "message", "like")))
557 // No author_signature? This is a must, so we quit.
558 if (!isset($author_signature)) {
559 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
563 if (isset($parent_author_signature)) {
564 $key = self::key($msg["author"]);
566 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
567 logger("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
572 $key = self::key($fields->author);
574 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
575 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
582 * @brief Fetches the public key for a given handle
584 * @param string $handle The handle
586 * @return string The public key
588 private static function key($handle) {
589 $handle = strval($handle);
591 logger("Fetching diaspora key for: ".$handle);
593 $r = self::person_by_handle($handle);
601 * @brief Fetches data for a given handle
603 * @param string $handle The handle
605 * @return array the queried data
607 private static function person_by_handle($handle) {
609 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
610 dbesc(NETWORK_DIASPORA),
615 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
617 // update record occasionally so it doesn't get stale
618 $d = strtotime($person["updated"]." +00:00");
619 if ($d < strtotime("now - 14 days"))
622 if ($person["guid"] == "")
626 if (!$person OR $update) {
627 logger("create or refresh", LOGGER_DEBUG);
628 $r = probe_url($handle, PROBE_DIASPORA);
630 // Note that Friendica contacts will return a "Diaspora person"
631 // if Diaspora connectivity is enabled on their server
632 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
633 self::add_fcontact($r, $update);
641 * @brief Updates the fcontact table
643 * @param array $arr The fcontact data
644 * @param bool $update Update or insert?
646 * @return string The id of the fcontact entry
648 private static function add_fcontact($arr, $update = false) {
651 $r = q("UPDATE `fcontact` SET
665 WHERE `url` = '%s' AND `network` = '%s'",
667 dbesc($arr["photo"]),
668 dbesc($arr["request"]),
670 dbesc(strtolower($arr["addr"])),
672 dbesc($arr["batch"]),
673 dbesc($arr["notify"]),
675 dbesc($arr["confirm"]),
676 dbesc($arr["alias"]),
677 dbesc($arr["pubkey"]),
678 dbesc(datetime_convert()),
680 dbesc($arr["network"])
683 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
684 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
685 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
688 dbesc($arr["photo"]),
689 dbesc($arr["request"]),
693 dbesc($arr["batch"]),
694 dbesc($arr["notify"]),
696 dbesc($arr["confirm"]),
697 dbesc($arr["network"]),
698 dbesc($arr["alias"]),
699 dbesc($arr["pubkey"]),
700 dbesc(datetime_convert())
708 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
710 * @param int $contact_id The id in the contact table
711 * @param int $gcontact_id The id in the gcontact table
713 * @return string the handle
715 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
718 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
720 if ($gcontact_id != 0) {
721 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
722 intval($gcontact_id));
724 if (dbm::is_result($r)) {
725 return strtolower($r[0]["addr"]);
729 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
730 intval($contact_id));
732 if (dbm::is_result($r)) {
735 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
737 if ($contact['addr'] != "") {
738 $handle = $contact['addr'];
740 $baseurl_start = strpos($contact['url'],'://') + 3;
741 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
742 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
743 $handle = $contact['nick'].'@'.$baseurl;
747 return strtolower($handle);
751 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
754 * @param mixed $fcontact_guid Hexadecimal string guid
756 * @return string the contact url or null
758 public static function url_from_contact_guid($fcontact_guid) {
759 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
761 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
762 dbesc(NETWORK_DIASPORA),
763 dbesc($fcontact_guid)
766 if (dbm::is_result($r)) {
774 * @brief Get a contact id for a given handle
776 * @param int $uid The user id
777 * @param string $handle The handle in the format user@domain.tld
779 * @return The contact id
781 private static function contact_by_handle($uid, $handle) {
783 // First do a direct search on the contact table
784 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
789 if (dbm::is_result($r)) {
792 // We haven't found it?
793 // We use another function for it that will possibly create a contact entry
794 $cid = get_contact($handle, $uid);
797 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
799 if (dbm::is_result($r)) {
805 $handle_parts = explode("@", $handle);
806 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
807 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
812 if (dbm::is_result($r)) {
816 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
821 * @brief Check if posting is allowed for this contact
823 * @param array $importer Array of the importer user
824 * @param array $contact The contact that is checked
825 * @param bool $is_comment Is the check for a comment?
827 * @return bool is the contact allowed to post?
829 private static function post_allow($importer, $contact, $is_comment = false) {
831 // perhaps we were already sharing with this person. Now they're sharing with us.
832 // That makes us friends.
833 // Normally this should have handled by getting a request - but this could get lost
834 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
835 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
836 intval(CONTACT_IS_FRIEND),
837 intval($contact["id"]),
838 intval($importer["uid"])
840 $contact["rel"] = CONTACT_IS_FRIEND;
841 logger("defining user ".$contact["nick"]." as friend");
844 // We don't seem to like that person
845 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
847 // We are following this person? Then it is okay
848 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
850 // Is it a post to a community? That's good
851 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
854 // Messages for the global users and comments are always accepted
855 if (($importer["uid"] == 0) || $is_comment) {
863 * @brief Fetches the contact id for a handle and checks if posting is allowed
865 * @param array $importer Array of the importer user
866 * @param string $handle The checked handle in the format user@domain.tld
867 * @param bool $is_comment Is the check for a comment?
869 * @return array The contact data
871 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
872 $contact = self::contact_by_handle($importer["uid"], $handle);
874 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
875 // If a contact isn't found, we accept it anyway if it is a comment
883 if (!self::post_allow($importer, $contact, $is_comment)) {
884 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
891 * @brief Does the message already exists on the system?
893 * @param int $uid The user id
894 * @param string $guid The guid of the message
896 * @return int|bool message id if the message already was stored into the system - or false.
898 private static function message_exists($uid, $guid) {
899 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
904 if (dbm::is_result($r)) {
905 logger("message ".$guid." already exists for user ".$uid);
913 * @brief Checks for links to posts in a message
915 * @param array $item The item array
917 private static function fetch_guid($item) {
918 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
919 function ($match) use ($item){
920 return(self::fetch_guid_sub($match, $item));
925 * @brief Checks for relative /people/* links in an item body to match local
926 * contacts or prepends the remote host taken from the author link.
928 * @param string $body The item body to replace links from
929 * @param string $author_link The author link for missing local contact fallback
931 * @return the replaced string
933 public function replace_people_guid($body, $author_link) {
934 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
935 function ($match) use ($author_link) {
937 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
938 // 1 => '0123456789abcdef'
940 $handle = self::url_from_contact_guid($match[1]);
943 $return = '@[url='.$handle.']'.$match[2].'[/url]';
945 // No local match, restoring absolute remote URL from author scheme and host
946 $author_url = parse_url($author_link);
947 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
957 * @brief sub function of "fetch_guid" which checks for links in messages
959 * @param array $match array containing a link that has to be checked for a message link
960 * @param array $item The item array
962 private static function fetch_guid_sub($match, $item) {
963 if (!self::store_by_guid($match[1], $item["author-link"]))
964 self::store_by_guid($match[1], $item["owner-link"]);
968 * @brief Fetches an item with a given guid from a given server
970 * @param string $guid the message guid
971 * @param string $server The server address
972 * @param int $uid The user id of the user
974 * @return int the message id of the stored message or false
976 private static function store_by_guid($guid, $server, $uid = 0) {
977 $serverparts = parse_url($server);
978 $server = $serverparts["scheme"]."://".$serverparts["host"];
980 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
982 $msg = self::message($guid, $server);
987 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
989 // Now call the dispatcher
990 return self::dispatch_public($msg);
994 * @brief Fetches a message from a server
996 * @param string $guid message guid
997 * @param string $server The url of the server
998 * @param int $level Endless loop prevention
1001 * 'message' => The message XML
1002 * 'author' => The author handle
1003 * 'key' => The public key of the author
1005 private static function message($guid, $server, $level = 0) {
1010 // This will work for new Diaspora servers and Friendica servers from 3.5
1011 $source_url = $server."/fetch/post/".$guid;
1012 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1014 $envelope = fetch_url($source_url);
1016 logger("Envelope was fetched.", LOGGER_DEBUG);
1017 $x = self::verify_magic_envelope($envelope);
1019 logger("Envelope could not be verified.", LOGGER_DEBUG);
1021 logger("Envelope was verified.", LOGGER_DEBUG);
1025 // This will work for older Diaspora and Friendica servers
1027 $source_url = $server."/p/".$guid.".xml";
1028 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1030 $x = fetch_url($source_url);
1035 $source_xml = parse_xml_string($x, false);
1037 if (!is_object($source_xml))
1040 if ($source_xml->post->reshare) {
1041 // Reshare of a reshare - old Diaspora version
1042 logger("Message is a reshare", LOGGER_DEBUG);
1043 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1044 } elseif ($source_xml->getName() == "reshare") {
1045 // Reshare of a reshare - new Diaspora version
1046 logger("Message is a new reshare", LOGGER_DEBUG);
1047 return self::message($source_xml->root_guid, $server, ++$level);
1052 // Fetch the author - for the old and the new Diaspora version
1053 if ($source_xml->post->status_message->diaspora_handle)
1054 $author = (string)$source_xml->post->status_message->diaspora_handle;
1055 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1056 $author = (string)$source_xml->author;
1058 // If this isn't a "status_message" then quit
1060 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1064 $msg = array("message" => $x, "author" => $author);
1066 $msg["key"] = self::key($msg["author"]);
1072 * @brief Fetches the item record of a given guid
1074 * @param int $uid The user id
1075 * @param string $guid message guid
1076 * @param string $author The handle of the item
1077 * @param array $contact The contact of the item owner
1079 * @return array the item record
1081 private static function parent_item($uid, $guid, $author, $contact) {
1082 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1083 `author-name`, `author-link`, `author-avatar`,
1084 `owner-name`, `owner-link`, `owner-avatar`
1085 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1086 intval($uid), dbesc($guid));
1089 $result = self::store_by_guid($guid, $contact["url"], $uid);
1092 $person = self::person_by_handle($author);
1093 $result = self::store_by_guid($guid, $person["url"], $uid);
1097 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1099 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1100 `author-name`, `author-link`, `author-avatar`,
1101 `owner-name`, `owner-link`, `owner-avatar`
1102 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1103 intval($uid), dbesc($guid));
1108 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1111 logger("parent item found: parent: ".$guid." - user: ".$uid);
1117 * @brief returns contact details
1119 * @param array $contact The default contact if the person isn't found
1120 * @param array $person The record of the person
1121 * @param int $uid The user id
1124 * 'cid' => contact id
1125 * 'network' => network type
1127 private static function author_contact_by_url($contact, $person, $uid) {
1129 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1130 dbesc(normalise_link($person["url"])), intval($uid));
1133 $network = $r[0]["network"];
1135 // We are receiving content from a user that possibly is about to be terminated
1136 // This means the user is vital, so we remove a possible termination date.
1137 unmark_for_death($r[0]);
1139 $cid = $contact["id"];
1140 $network = NETWORK_DIASPORA;
1143 return array("cid" => $cid, "network" => $network);
1147 * @brief Is the profile a hubzilla profile?
1149 * @param string $url The profile link
1151 * @return bool is it a hubzilla server?
1153 public static function is_redmatrix($url) {
1154 return(strstr($url, "/channel/"));
1158 * @brief Generate a post link with a given handle and message guid
1160 * @param string $addr The user handle
1161 * @param string $guid message guid
1163 * @return string the post link
1165 private static function plink($addr, $guid) {
1166 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1170 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1172 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1173 // So we try another way as well.
1174 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1176 $r[0]["network"] = $s[0]["network"];
1178 if ($r[0]["network"] == NETWORK_DFRN)
1179 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1181 if (self::is_redmatrix($r[0]["url"]))
1182 return $r[0]["url"]."/?f=&mid=".$guid;
1184 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1188 * @brief Processes an account deletion
1190 * @param array $importer Array of the importer user
1191 * @param object $data The message object
1193 * @return bool Success
1195 private static function receive_account_deletion($importer, $data) {
1197 /// @todo Account deletion should remove the contact from the global contacts as well
1199 $author = notags(unxmlify($data->author));
1201 $contact = self::contact_by_handle($importer["uid"], $author);
1203 logger("cannot find contact for author: ".$author);
1207 // We now remove the contact
1208 contact_remove($contact["id"]);
1213 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1215 * @param string $author Author handle
1216 * @param string $guid Message guid
1217 * @param boolean $onlyfound Only return uri when found in the database
1219 * @return string The constructed uri or the one from our database
1221 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1223 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1224 if (dbm::is_result($r)) {
1225 return $r[0]["uri"];
1226 } elseif (!$onlyfound) {
1227 return $author.":".$guid;
1234 * @brief Fetch the guid from our database with a given uri
1236 * @param string $author Author handle
1237 * @param string $uri Message uri
1239 * @return string The post guid
1241 private static function get_guid_from_uri($uri, $uid) {
1243 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1244 if (dbm::is_result($r)) {
1245 return $r[0]["guid"];
1252 * @brief Find the best importer for a comment, like, ...
1254 * @param string $guid The guid of the item
1256 * @return array|boolean the origin owner of that post - or false
1258 private static function importer_for_guid($guid) {
1259 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1261 if (dbm::is_result($item)) {
1262 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1263 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1264 if (dbm::is_result($contact)) {
1272 * @brief Processes an incoming comment
1274 * @param array $importer Array of the importer user
1275 * @param string $sender The sender of the message
1276 * @param object $data The message object
1277 * @param string $xml The original XML of the message
1279 * @return int The message id of the generated comment or "false" if there was an error
1281 private static function receive_comment($importer, $sender, $data, $xml) {
1282 $guid = notags(unxmlify($data->guid));
1283 $parent_guid = notags(unxmlify($data->parent_guid));
1284 $text = unxmlify($data->text);
1285 $author = notags(unxmlify($data->author));
1287 if (isset($data->created_at)) {
1288 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1290 $created_at = datetime_convert();
1293 if (isset($data->thread_parent_guid)) {
1294 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1295 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1300 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1305 $message_id = self::message_exists($importer["uid"], $guid);
1310 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1311 if (!$parent_item) {
1315 $person = self::person_by_handle($author);
1316 if (!is_array($person)) {
1317 logger("unable to find author details");
1321 // Fetch the contact id - if we know this contact
1322 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1324 $datarray = array();
1326 $datarray["uid"] = $importer["uid"];
1327 $datarray["contact-id"] = $author_contact["cid"];
1328 $datarray["network"] = $author_contact["network"];
1330 $datarray["author-name"] = $person["name"];
1331 $datarray["author-link"] = $person["url"];
1332 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1334 $datarray["owner-name"] = $contact["name"];
1335 $datarray["owner-link"] = $contact["url"];
1336 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1338 $datarray["guid"] = $guid;
1339 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1341 $datarray["type"] = "remote-comment";
1342 $datarray["verb"] = ACTIVITY_POST;
1343 $datarray["gravity"] = GRAVITY_COMMENT;
1345 if ($thr_uri != "") {
1346 $datarray["parent-uri"] = $thr_uri;
1348 $datarray["parent-uri"] = $parent_item["uri"];
1351 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1353 $datarray["protocol"] = PROTOCOL_DIASPORA;
1354 $datarray["source"] = $xml;
1356 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1358 $body = diaspora2bb($text);
1360 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1362 self::fetch_guid($datarray);
1364 $message_id = item_store($datarray);
1367 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1370 // If we are the origin of the parent we store the original data and notify our followers
1371 if ($message_id AND $parent_item["origin"]) {
1373 // Formerly we stored the signed text, the signature and the author in different fields.
1374 // We now store the raw data so that we are more flexible.
1375 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1376 intval($message_id),
1377 dbesc(json_encode($data))
1381 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1388 * @brief processes and stores private messages
1390 * @param array $importer Array of the importer user
1391 * @param array $contact The contact of the message
1392 * @param object $data The message object
1393 * @param array $msg Array of the processed message, author handle and key
1394 * @param object $mesg The private message
1395 * @param array $conversation The conversation record to which this message belongs
1397 * @return bool "true" if it was successful
1399 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1400 $guid = notags(unxmlify($data->guid));
1401 $subject = notags(unxmlify($data->subject));
1402 $author = notags(unxmlify($data->author));
1404 $msg_guid = notags(unxmlify($mesg->guid));
1405 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1406 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1407 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1408 $msg_text = unxmlify($mesg->text);
1409 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1411 // "diaspora_handle" is the element name from the old version
1412 // "author" is the element name from the new version
1413 if ($mesg->author) {
1414 $msg_author = notags(unxmlify($mesg->author));
1415 } elseif ($mesg->diaspora_handle) {
1416 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1421 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1423 if ($msg_conversation_guid != $guid) {
1424 logger("message conversation guid does not belong to the current conversation.");
1428 $body = diaspora2bb($msg_text);
1429 $message_uri = $msg_author.":".$msg_guid;
1431 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1433 $author_signature = base64_decode($msg_author_signature);
1435 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1439 $person = self::person_by_handle($msg_author);
1441 if (is_array($person) && x($person, "pubkey")) {
1442 $key = $person["pubkey"];
1444 logger("unable to find author details");
1449 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1450 logger("verification failed.");
1454 if ($msg_parent_author_signature) {
1455 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1457 $parent_author_signature = base64_decode($msg_parent_author_signature);
1461 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1462 logger("owner verification failed.");
1467 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1470 if (dbm::is_result($r)) {
1471 logger("duplicate message already delivered.", LOGGER_DEBUG);
1475 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1476 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1477 intval($importer["uid"]),
1479 intval($conversation["id"]),
1480 dbesc($person["name"]),
1481 dbesc($person["photo"]),
1482 dbesc($person["url"]),
1483 intval($contact["id"]),
1488 dbesc($message_uri),
1489 dbesc($author.":".$guid),
1490 dbesc($msg_created_at)
1493 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1494 dbesc(datetime_convert()),
1495 intval($conversation["id"])
1499 "type" => NOTIFY_MAIL,
1500 "notify_flags" => $importer["notify-flags"],
1501 "language" => $importer["language"],
1502 "to_name" => $importer["username"],
1503 "to_email" => $importer["email"],
1504 "uid" =>$importer["uid"],
1505 "item" => array("subject" => $subject, "body" => $body),
1506 "source_name" => $person["name"],
1507 "source_link" => $person["url"],
1508 "source_photo" => $person["thumb"],
1509 "verb" => ACTIVITY_POST,
1516 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1518 * @param array $importer Array of the importer user
1519 * @param array $msg Array of the processed message, author handle and key
1520 * @param object $data The message object
1522 * @return bool Success
1524 private static function receive_conversation($importer, $msg, $data) {
1525 $guid = notags(unxmlify($data->guid));
1526 $subject = notags(unxmlify($data->subject));
1527 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1528 $author = notags(unxmlify($data->author));
1529 $participants = notags(unxmlify($data->participants));
1531 $messages = $data->message;
1533 if (!count($messages)) {
1534 logger("empty conversation");
1538 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1542 $conversation = null;
1544 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1545 intval($importer["uid"]),
1549 $conversation = $c[0];
1551 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1552 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1553 intval($importer["uid"]),
1557 dbesc(datetime_convert()),
1559 dbesc($participants)
1562 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1563 intval($importer["uid"]),
1568 $conversation = $c[0];
1570 if (!$conversation) {
1571 logger("unable to create conversation.");
1575 foreach ($messages as $mesg)
1576 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1582 * @brief Creates the body for a "like" message
1584 * @param array $contact The contact that send us the "like"
1585 * @param array $parent_item The item array of the parent item
1586 * @param string $guid message guid
1588 * @return string the body
1590 private static function construct_like_body($contact, $parent_item, $guid) {
1591 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1593 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1594 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1595 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1597 return sprintf($bodyverb, $ulink, $alink, $plink);
1601 * @brief Creates a XML object for a "like"
1603 * @param array $importer Array of the importer user
1604 * @param array $parent_item The item array of the parent item
1606 * @return string The XML
1608 private static function construct_like_object($importer, $parent_item) {
1609 $objtype = ACTIVITY_OBJ_NOTE;
1610 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1611 $parent_body = $parent_item["body"];
1613 $xmldata = array("object" => array("type" => $objtype,
1615 "id" => $parent_item["uri"],
1618 "content" => $parent_body));
1620 return xml::from_array($xmldata, $xml, true);
1624 * @brief Processes "like" messages
1626 * @param array $importer Array of the importer user
1627 * @param string $sender The sender of the message
1628 * @param object $data The message object
1630 * @return int The message id of the generated like or "false" if there was an error
1632 private static function receive_like($importer, $sender, $data) {
1633 $positive = notags(unxmlify($data->positive));
1634 $guid = notags(unxmlify($data->guid));
1635 $parent_type = notags(unxmlify($data->parent_type));
1636 $parent_guid = notags(unxmlify($data->parent_guid));
1637 $author = notags(unxmlify($data->author));
1639 // likes on comments aren't supported by Diaspora - only on posts
1640 // But maybe this will be supported in the future, so we will accept it.
1641 if (!in_array($parent_type, array("Post", "Comment")))
1644 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1648 $message_id = self::message_exists($importer["uid"], $guid);
1652 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1656 $person = self::person_by_handle($author);
1657 if (!is_array($person)) {
1658 logger("unable to find author details");
1662 // Fetch the contact id - if we know this contact
1663 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1665 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1666 // We would accept this anyhow.
1667 if ($positive == "true")
1668 $verb = ACTIVITY_LIKE;
1670 $verb = ACTIVITY_DISLIKE;
1672 $datarray = array();
1674 $datarray["protocol"] = PROTOCOL_DIASPORA;
1676 $datarray["uid"] = $importer["uid"];
1677 $datarray["contact-id"] = $author_contact["cid"];
1678 $datarray["network"] = $author_contact["network"];
1680 $datarray["author-name"] = $person["name"];
1681 $datarray["author-link"] = $person["url"];
1682 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1684 $datarray["owner-name"] = $contact["name"];
1685 $datarray["owner-link"] = $contact["url"];
1686 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1688 $datarray["guid"] = $guid;
1689 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1691 $datarray["type"] = "activity";
1692 $datarray["verb"] = $verb;
1693 $datarray["gravity"] = GRAVITY_LIKE;
1694 $datarray["parent-uri"] = $parent_item["uri"];
1696 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1697 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1699 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1701 $message_id = item_store($datarray);
1704 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1706 // If we are the origin of the parent we store the original data and notify our followers
1707 if ($message_id AND $parent_item["origin"]) {
1709 // Formerly we stored the signed text, the signature and the author in different fields.
1710 // We now store the raw data so that we are more flexible.
1711 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1712 intval($message_id),
1713 dbesc(json_encode($data))
1717 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1724 * @brief Processes private messages
1726 * @param array $importer Array of the importer user
1727 * @param object $data The message object
1729 * @return bool Success?
1731 private static function receive_message($importer, $data) {
1732 $guid = notags(unxmlify($data->guid));
1733 $parent_guid = notags(unxmlify($data->parent_guid));
1734 $text = unxmlify($data->text);
1735 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1736 $author = notags(unxmlify($data->author));
1737 $conversation_guid = notags(unxmlify($data->conversation_guid));
1739 $contact = self::allowed_contact_by_handle($importer, $author, true);
1744 $conversation = null;
1746 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1747 intval($importer["uid"]),
1748 dbesc($conversation_guid)
1751 $conversation = $c[0];
1753 logger("conversation not available.");
1757 $message_uri = $author.":".$guid;
1759 $person = self::person_by_handle($author);
1761 logger("unable to find author details");
1765 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1766 dbesc($message_uri),
1767 intval($importer["uid"])
1769 if (dbm::is_result($r)) {
1770 logger("duplicate message already delivered.", LOGGER_DEBUG);
1774 $body = diaspora2bb($text);
1776 $body = self::replace_people_guid($body, $person["url"]);
1778 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1779 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1780 intval($importer["uid"]),
1782 intval($conversation["id"]),
1783 dbesc($person["name"]),
1784 dbesc($person["photo"]),
1785 dbesc($person["url"]),
1786 intval($contact["id"]),
1787 dbesc($conversation["subject"]),
1791 dbesc($message_uri),
1792 dbesc($author.":".$parent_guid),
1796 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1797 dbesc(datetime_convert()),
1798 intval($conversation["id"])
1805 * @brief Processes participations - unsupported by now
1807 * @param array $importer Array of the importer user
1808 * @param object $data The message object
1810 * @return bool always true
1812 private static function receive_participation($importer, $data) {
1813 // I'm not sure if we can fully support this message type
1818 * @brief Processes photos - unneeded
1820 * @param array $importer Array of the importer user
1821 * @param object $data The message object
1823 * @return bool always true
1825 private static function receive_photo($importer, $data) {
1826 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1831 * @brief Processes poll participations - unssupported
1833 * @param array $importer Array of the importer user
1834 * @param object $data The message object
1836 * @return bool always true
1838 private static function receive_poll_participation($importer, $data) {
1839 // We don't support polls by now
1844 * @brief Processes incoming profile updates
1846 * @param array $importer Array of the importer user
1847 * @param object $data The message object
1849 * @return bool Success
1851 private static function receive_profile($importer, $data) {
1852 $author = strtolower(notags(unxmlify($data->author)));
1854 $contact = self::contact_by_handle($importer["uid"], $author);
1858 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1859 $image_url = unxmlify($data->image_url);
1860 $birthday = unxmlify($data->birthday);
1861 $location = diaspora2bb(unxmlify($data->location));
1862 $about = diaspora2bb(unxmlify($data->bio));
1863 $gender = unxmlify($data->gender);
1864 $searchable = (unxmlify($data->searchable) == "true");
1865 $nsfw = (unxmlify($data->nsfw) == "true");
1866 $tags = unxmlify($data->tag_string);
1868 $tags = explode("#", $tags);
1870 $keywords = array();
1871 foreach ($tags as $tag) {
1872 $tag = trim(strtolower($tag));
1877 $keywords = implode(", ", $keywords);
1879 $handle_parts = explode("@", $author);
1880 $nick = $handle_parts[0];
1883 $name = $handle_parts[0];
1885 if ( preg_match("|^https?://|", $image_url) === 0)
1886 $image_url = "http://".$handle_parts[1].$image_url;
1888 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1890 // Generic birthday. We don't know the timezone. The year is irrelevant.
1892 $birthday = str_replace("1000", "1901", $birthday);
1894 if ($birthday != "")
1895 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1897 // this is to prevent multiple birthday notifications in a single year
1898 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1900 if (substr($birthday,5) === substr($contact["bd"],5))
1901 $birthday = $contact["bd"];
1903 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1904 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1908 dbesc(datetime_convert()),
1914 intval($contact["id"]),
1915 intval($importer["uid"])
1918 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1919 "photo" => $image_url, "name" => $name, "location" => $location,
1920 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1921 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1922 "hide" => !$searchable, "nsfw" => $nsfw);
1924 $gcid = update_gcontact($gcontact);
1926 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1928 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1934 * @brief Processes incoming friend requests
1936 * @param array $importer Array of the importer user
1937 * @param array $contact The contact that send the request
1939 private static function receive_request_make_friend($importer, $contact) {
1943 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1944 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1945 intval(CONTACT_IS_FRIEND),
1946 intval($contact["id"]),
1947 intval($importer["uid"])
1950 // send notification
1952 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1953 intval($importer["uid"])
1956 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1958 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1959 intval($importer["uid"])
1962 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1964 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1967 $arr["protocol"] = PROTOCOL_DIASPORA;
1968 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1969 $arr["uid"] = $importer["uid"];
1970 $arr["contact-id"] = $self[0]["id"];
1972 $arr["type"] = 'wall';
1973 $arr["gravity"] = 0;
1975 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1976 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1977 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1978 $arr["verb"] = ACTIVITY_FRIEND;
1979 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1981 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1982 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1983 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1984 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1986 $arr["object"] = self::construct_new_friend_object($contact);
1988 $arr["last-child"] = 1;
1990 $arr["allow_cid"] = $user[0]["allow_cid"];
1991 $arr["allow_gid"] = $user[0]["allow_gid"];
1992 $arr["deny_cid"] = $user[0]["deny_cid"];
1993 $arr["deny_gid"] = $user[0]["deny_gid"];
1995 $i = item_store($arr);
1997 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
2003 * @brief Creates a XML object for a "new friend" message
2005 * @param array $contact Array of the contact
2007 * @return string The XML
2009 private static function construct_new_friend_object($contact) {
2010 $objtype = ACTIVITY_OBJ_PERSON;
2011 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2012 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2014 $xmldata = array("object" => array("type" => $objtype,
2015 "title" => $contact["name"],
2016 "id" => $contact["url"]."/".$contact["name"],
2019 return xml::from_array($xmldata, $xml, true);
2023 * @brief Processes incoming sharing notification
2025 * @param array $importer Array of the importer user
2026 * @param object $data The message object
2028 * @return bool Success
2030 private static function receive_contact_request($importer, $data) {
2031 $author = unxmlify($data->author);
2032 $recipient = unxmlify($data->recipient);
2034 if (!$author || !$recipient) {
2038 // the current protocol version doesn't know these fields
2039 // That means that we will assume their existance
2040 if (isset($data->following)) {
2041 $following = (unxmlify($data->following) == "true");
2046 if (isset($data->sharing)) {
2047 $sharing = (unxmlify($data->sharing) == "true");
2052 $contact = self::contact_by_handle($importer["uid"],$author);
2054 // perhaps we were already sharing with this person. Now they're sharing with us.
2055 // That makes us friends.
2057 if ($following AND $sharing) {
2058 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
2059 self::receive_request_make_friend($importer, $contact);
2061 // refetch the contact array
2062 $contact = self::contact_by_handle($importer["uid"],$author);
2064 // If we are now friends, we are sending a share message.
2065 // Normally we needn't to do so, but the first message could have been vanished.
2066 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
2067 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2069 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2070 $ret = self::send_share($u[0], $contact);
2074 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2075 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2080 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2081 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2083 } elseif (!$following AND !$sharing) {
2084 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2086 } elseif (!$following AND $sharing) {
2087 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2088 } elseif ($following AND $sharing) {
2089 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2090 } elseif ($following AND !$sharing) {
2091 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2094 $ret = self::person_by_handle($author);
2096 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2097 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2101 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2103 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2104 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2105 intval($importer["uid"]),
2106 dbesc($ret["network"]),
2107 dbesc($ret["addr"]),
2110 dbesc(normalise_link($ret["url"])),
2112 dbesc($ret["name"]),
2113 dbesc($ret["nick"]),
2114 dbesc($ret["photo"]),
2115 dbesc($ret["pubkey"]),
2116 dbesc($ret["notify"]),
2117 dbesc($ret["poll"]),
2122 // find the contact record we just created
2124 $contact_record = self::contact_by_handle($importer["uid"],$author);
2126 if (!$contact_record) {
2127 logger("unable to locate newly created contact record.");
2131 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2133 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2135 if (intval($def_gid))
2136 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2138 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2140 if ($importer["page-flags"] == PAGE_NORMAL) {
2142 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2144 $hash = random_string().(string)time(); // Generate a confirm_key
2146 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2147 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2148 intval($importer["uid"]),
2149 intval($contact_record["id"]),
2152 dbesc(t("Sharing notification from Diaspora network")),
2154 dbesc(datetime_convert())
2158 // automatic friend approval
2160 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2162 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2164 // technically they are sharing with us (CONTACT_IS_SHARING),
2165 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2166 // we are going to change the relationship and make them a follower.
2168 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2169 $new_relation = CONTACT_IS_FRIEND;
2170 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2171 $new_relation = CONTACT_IS_SHARING;
2173 $new_relation = CONTACT_IS_FOLLOWER;
2175 $r = q("UPDATE `contact` SET `rel` = %d,
2183 intval($new_relation),
2184 dbesc(datetime_convert()),
2185 dbesc(datetime_convert()),
2186 intval($contact_record["id"])
2189 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2191 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2192 $ret = self::send_share($u[0], $contact_record);
2194 // Send the profile data, maybe it weren't transmitted before
2195 self::send_profile($importer["uid"], array($contact_record));
2203 * @brief Fetches a message with a given guid
2205 * @param string $guid message guid
2206 * @param string $orig_author handle of the original post
2207 * @param string $author handle of the sharer
2209 * @return array The fetched item
2211 private static function original_item($guid, $orig_author, $author) {
2213 // Do we already have this item?
2214 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2215 `author-name`, `author-link`, `author-avatar`
2216 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2219 if (dbm::is_result($r)) {
2220 logger("reshared message ".$guid." already exists on system.");
2222 // Maybe it is already a reshared item?
2223 // Then refetch the content, if it is a reshare from a reshare.
2224 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2225 if (self::is_reshare($r[0]["body"], true)) {
2227 } elseif (self::is_reshare($r[0]["body"], false)) {
2228 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2230 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2232 // Add OEmbed and other information to the body
2233 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2241 if (!dbm::is_result($r)) {
2242 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2243 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2244 $item_id = self::store_by_guid($guid, $server);
2247 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2248 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2249 $item_id = self::store_by_guid($guid, $server);
2253 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2254 `author-name`, `author-link`, `author-avatar`
2255 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2258 if (dbm::is_result($r)) {
2259 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2260 if (self::is_reshare($r[0]["body"], false)) {
2261 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2262 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2274 * @brief Processes a reshare message
2276 * @param array $importer Array of the importer user
2277 * @param object $data The message object
2278 * @param string $xml The original XML of the message
2280 * @return int the message id
2282 private static function receive_reshare($importer, $data, $xml) {
2283 $root_author = notags(unxmlify($data->root_author));
2284 $root_guid = notags(unxmlify($data->root_guid));
2285 $guid = notags(unxmlify($data->guid));
2286 $author = notags(unxmlify($data->author));
2287 $public = notags(unxmlify($data->public));
2288 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2290 $contact = self::allowed_contact_by_handle($importer, $author, false);
2295 $message_id = self::message_exists($importer["uid"], $guid);
2300 $original_item = self::original_item($root_guid, $root_author, $author);
2301 if (!$original_item) {
2305 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2307 $datarray = array();
2309 $datarray["uid"] = $importer["uid"];
2310 $datarray["contact-id"] = $contact["id"];
2311 $datarray["network"] = NETWORK_DIASPORA;
2313 $datarray["author-name"] = $contact["name"];
2314 $datarray["author-link"] = $contact["url"];
2315 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2317 $datarray["owner-name"] = $datarray["author-name"];
2318 $datarray["owner-link"] = $datarray["author-link"];
2319 $datarray["owner-avatar"] = $datarray["author-avatar"];
2321 $datarray["guid"] = $guid;
2322 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2324 $datarray["verb"] = ACTIVITY_POST;
2325 $datarray["gravity"] = GRAVITY_PARENT;
2327 $datarray["protocol"] = PROTOCOL_DIASPORA;
2328 $datarray["source"] = $xml;
2330 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2331 $original_item["guid"], $original_item["created"], $orig_url);
2332 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2334 $datarray["tag"] = $original_item["tag"];
2335 $datarray["app"] = $original_item["app"];
2337 $datarray["plink"] = self::plink($author, $guid);
2338 $datarray["private"] = (($public == "false") ? 1 : 0);
2339 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2341 $datarray["object-type"] = $original_item["object-type"];
2343 self::fetch_guid($datarray);
2344 $message_id = item_store($datarray);
2347 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2354 * @brief Processes retractions
2356 * @param array $importer Array of the importer user
2357 * @param array $contact The contact of the item owner
2358 * @param object $data The message object
2360 * @return bool success
2362 private static function item_retraction($importer, $contact, $data) {
2363 $target_type = notags(unxmlify($data->target_type));
2364 $target_guid = notags(unxmlify($data->target_guid));
2365 $author = notags(unxmlify($data->author));
2367 $person = self::person_by_handle($author);
2368 if (!is_array($person)) {
2369 logger("unable to find author detail for ".$author);
2373 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2374 dbesc($target_guid),
2375 intval($importer["uid"])
2381 // Check if the sender is the thread owner
2382 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2383 intval($r[0]["parent"]));
2385 // Only delete it if the parent author really fits
2386 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2387 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2391 // 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
2392 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2393 dbesc(datetime_convert()),
2394 dbesc(datetime_convert()),
2397 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2399 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2401 // Now check if the retraction needs to be relayed by us
2402 if ($p[0]["origin"]) {
2404 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2411 * @brief Receives retraction messages
2413 * @param array $importer Array of the importer user
2414 * @param string $sender The sender of the message
2415 * @param object $data The message object
2417 * @return bool Success
2419 private static function receive_retraction($importer, $sender, $data) {
2420 $target_type = notags(unxmlify($data->target_type));
2422 $contact = self::contact_by_handle($importer["uid"], $sender);
2424 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2428 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2430 switch ($target_type) {
2433 case "Post": // "Post" will be supported in a future version
2435 case "StatusMessage":
2436 return self::item_retraction($importer, $contact, $data);;
2440 /// @todo What should we do with an "unshare"?
2441 // Removing the contact isn't correct since we still can read the public items
2442 contact_remove($contact["id"]);
2446 logger("Unknown target type ".$target_type);
2453 * @brief Receives status messages
2455 * @param array $importer Array of the importer user
2456 * @param object $data The message object
2457 * @param string $xml The original XML of the message
2459 * @return int The message id of the newly created item
2461 private static function receive_status_message($importer, $data, $xml) {
2462 $raw_message = unxmlify($data->raw_message);
2463 $guid = notags(unxmlify($data->guid));
2464 $author = notags(unxmlify($data->author));
2465 $public = notags(unxmlify($data->public));
2466 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2467 $provider_display_name = notags(unxmlify($data->provider_display_name));
2469 /// @todo enable support for polls
2470 //if ($data->poll) {
2471 // foreach ($data->poll AS $poll)
2475 $contact = self::allowed_contact_by_handle($importer, $author, false);
2480 $message_id = self::message_exists($importer["uid"], $guid);
2486 if ($data->location) {
2487 foreach ($data->location->children() AS $fieldname => $data) {
2488 $address[$fieldname] = notags(unxmlify($data));
2492 $body = diaspora2bb($raw_message);
2494 $datarray = array();
2496 // Attach embedded pictures to the body
2498 foreach ($data->photo AS $photo) {
2499 $body = "[img]".unxmlify($photo->remote_photo_path).
2500 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2503 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2505 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2507 // Add OEmbed and other information to the body
2508 if (!self::is_redmatrix($contact["url"])) {
2509 $body = add_page_info_to_body($body, false, true);
2513 $datarray["uid"] = $importer["uid"];
2514 $datarray["contact-id"] = $contact["id"];
2515 $datarray["network"] = NETWORK_DIASPORA;
2517 $datarray["author-name"] = $contact["name"];
2518 $datarray["author-link"] = $contact["url"];
2519 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2521 $datarray["owner-name"] = $datarray["author-name"];
2522 $datarray["owner-link"] = $datarray["author-link"];
2523 $datarray["owner-avatar"] = $datarray["author-avatar"];
2525 $datarray["guid"] = $guid;
2526 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2528 $datarray["verb"] = ACTIVITY_POST;
2529 $datarray["gravity"] = GRAVITY_PARENT;
2531 $datarray["protocol"] = PROTOCOL_DIASPORA;
2532 $datarray["source"] = $xml;
2534 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2536 if ($provider_display_name != "") {
2537 $datarray["app"] = $provider_display_name;
2540 $datarray["plink"] = self::plink($author, $guid);
2541 $datarray["private"] = (($public == "false") ? 1 : 0);
2542 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2544 if (isset($address["address"])) {
2545 $datarray["location"] = $address["address"];
2548 if (isset($address["lat"]) AND isset($address["lng"])) {
2549 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2552 self::fetch_guid($datarray);
2553 $message_id = item_store($datarray);
2556 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2562 /* ************************************************************************************** *
2563 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2564 * ************************************************************************************** */
2567 * @brief returnes the handle of a contact
2569 * @param array $me contact array
2571 * @return string the handle in the format user@domain.tld
2573 private static function my_handle($contact) {
2574 if ($contact["addr"] != "") {
2575 return $contact["addr"];
2578 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2579 // So - just in case - we build the the address here.
2580 if ($contact["nickname"] != "") {
2581 $nick = $contact["nickname"];
2583 $nick = $contact["nick"];
2586 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2590 * @brief Creates the envelope for the "fetch" endpoint
2592 * @param string $msg The message that is to be transmitted
2593 * @param array $user The record of the sender
2595 * @return string The envelope
2598 public static function build_magic_envelope($msg, $user) {
2600 $b64url_data = base64url_encode($msg);
2601 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2603 $key_id = base64url_encode(self::my_handle($user));
2604 $type = "application/xml";
2605 $encoding = "base64url";
2606 $alg = "RSA-SHA256";
2607 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2608 $signature = rsa_sign($signable_data, $user["prvkey"]);
2609 $sig = base64url_encode($signature);
2611 $xmldata = array("me:env" => array("me:data" => $data,
2612 "@attributes" => array("type" => $type),
2613 "me:encoding" => $encoding,
2616 "@attributes2" => array("key_id" => $key_id)));
2618 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2620 return xml::from_array($xmldata, $xml, false, $namespaces);
2624 * @brief Creates the envelope for a public message
2626 * @param string $msg The message that is to be transmitted
2627 * @param array $user The record of the sender
2628 * @param array $contact Target of the communication
2629 * @param string $prvkey The private key of the sender
2630 * @param string $pubkey The public key of the receiver
2632 * @return string The envelope
2634 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2636 logger("Message: ".$msg, LOGGER_DATA);
2638 $handle = self::my_handle($user);
2640 $b64url_data = base64url_encode($msg);
2642 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2644 $type = "application/xml";
2645 $encoding = "base64url";
2646 $alg = "RSA-SHA256";
2648 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2650 $signature = rsa_sign($signable_data,$prvkey);
2651 $sig = base64url_encode($signature);
2653 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2654 "me:env" => array("me:encoding" => $encoding,
2657 "@attributes" => array("type" => $type),
2658 "me:sig" => $sig)));
2660 $namespaces = array("" => "https://joindiaspora.com/protocol",
2661 "me" => "http://salmon-protocol.org/ns/magic-env");
2663 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2665 logger("magic_env: ".$magic_env, LOGGER_DATA);
2670 * @brief Creates the envelope for a private message
2672 * @param string $msg The message that is to be transmitted
2673 * @param array $user The record of the sender
2674 * @param array $contact Target of the communication
2675 * @param string $prvkey The private key of the sender
2676 * @param string $pubkey The public key of the receiver
2678 * @return string The envelope
2680 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2682 logger("Message: ".$msg, LOGGER_DATA);
2684 // without a public key nothing will work
2687 logger("pubkey missing: contact id: ".$contact["id"]);
2691 $inner_aes_key = openssl_random_pseudo_bytes(32);
2692 $b_inner_aes_key = base64_encode($inner_aes_key);
2693 $inner_iv = openssl_random_pseudo_bytes(16);
2694 $b_inner_iv = base64_encode($inner_iv);
2696 $outer_aes_key = openssl_random_pseudo_bytes(32);
2697 $b_outer_aes_key = base64_encode($outer_aes_key);
2698 $outer_iv = openssl_random_pseudo_bytes(16);
2699 $b_outer_iv = base64_encode($outer_iv);
2701 $handle = self::my_handle($user);
2703 $inner_encrypted = self::aes_encrypt($inner_aes_key, $inner_iv, $msg);
2705 $b64_data = base64_encode($inner_encrypted);
2708 $b64url_data = base64url_encode($b64_data);
2709 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2711 $type = "application/xml";
2712 $encoding = "base64url";
2713 $alg = "RSA-SHA256";
2715 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2717 $signature = rsa_sign($signable_data,$prvkey);
2718 $sig = base64url_encode($signature);
2720 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2721 "aes_key" => $b_inner_aes_key,
2722 "author_id" => $handle));
2724 $decrypted_header = xml::from_array($xmldata, $xml, true);
2726 $ciphertext = self::aes_encrypt($outer_aes_key, $outer_iv, $decrypted_header);
2728 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2730 $encrypted_outer_key_bundle = "";
2731 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2733 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2735 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2737 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2738 "ciphertext" => base64_encode($ciphertext)));
2739 $cipher_json = base64_encode($encrypted_header_json_object);
2741 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2742 "me:env" => array("me:encoding" => $encoding,
2745 "@attributes" => array("type" => $type),
2746 "me:sig" => $sig)));
2748 $namespaces = array("" => "https://joindiaspora.com/protocol",
2749 "me" => "http://salmon-protocol.org/ns/magic-env");
2751 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2753 logger("magic_env: ".$magic_env, LOGGER_DATA);
2758 * @brief Create the envelope for a message
2760 * @param string $msg The message that is to be transmitted
2761 * @param array $user The record of the sender
2762 * @param array $contact Target of the communication
2763 * @param string $prvkey The private key of the sender
2764 * @param string $pubkey The public key of the receiver
2765 * @param bool $public Is the message public?
2767 * @return string The message that will be transmitted to other servers
2769 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2772 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2774 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2776 // The data that will be transmitted is double encoded via "urlencode", strange ...
2777 $slap = "xml=".urlencode(urlencode($magic_env));
2782 * @brief Creates a signature for a message
2784 * @param array $owner the array of the owner of the message
2785 * @param array $message The message that is to be signed
2787 * @return string The signature
2789 private static function signature($owner, $message) {
2791 unset($sigmsg["author_signature"]);
2792 unset($sigmsg["parent_author_signature"]);
2794 $signed_text = implode(";", $sigmsg);
2796 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2800 * @brief Transmit a message to a target server
2802 * @param array $owner the array of the item owner
2803 * @param array $contact Target of the communication
2804 * @param string $slap The message that is to be transmitted
2805 * @param bool $public_batch Is it a public post?
2806 * @param bool $queue_run Is the transmission called from the queue?
2807 * @param string $guid message guid
2809 * @return int Result of the transmission
2811 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2815 $enabled = intval(get_config("system", "diaspora_enabled"));
2819 $logid = random_string(4);
2820 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2822 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2826 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2828 if (!$queue_run && was_recently_delayed($contact["id"])) {
2831 if (!intval(get_config("system", "diaspora_test"))) {
2832 post_url($dest_url."/", $slap);
2833 $return_code = $a->get_curl_code();
2835 logger("test_mode");
2840 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2842 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2843 logger("queue message");
2845 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2846 intval($contact["id"]),
2847 dbesc(NETWORK_DIASPORA),
2849 intval($public_batch)
2852 logger("add_to_queue ignored - identical item already in queue");
2854 // queue message for redelivery
2855 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2857 // The message could not be delivered. We mark the contact as "dead"
2858 mark_for_death($contact);
2860 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2861 // We successfully delivered a message, the contact is alive
2862 unmark_for_death($contact);
2865 return(($return_code) ? $return_code : (-1));
2870 * @brief Build the post xml
2872 * @param string $type The message type
2873 * @param array $message The message data
2875 * @return string The post XML
2877 public static function build_post_xml($type, $message) {
2879 $data = array("XML" => array("post" => array($type => $message)));
2880 return xml::from_array($data, $xml);
2884 * @brief Builds and transmit messages
2886 * @param array $owner the array of the item owner
2887 * @param array $contact Target of the communication
2888 * @param string $type The message type
2889 * @param array $message The message data
2890 * @param bool $public_batch Is it a public post?
2891 * @param string $guid message guid
2892 * @param bool $spool Should the transmission be spooled or transmitted?
2894 * @return int Result of the transmission
2896 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2898 $msg = self::build_post_xml($type, $message);
2900 logger('message: '.$msg, LOGGER_DATA);
2901 logger('send guid '.$guid, LOGGER_DEBUG);
2903 // Fallback if the private key wasn't transmitted in the expected field
2904 if ($owner['uprvkey'] == "")
2905 $owner['uprvkey'] = $owner['prvkey'];
2907 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2910 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2913 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2915 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2917 return $return_code;
2921 * @brief Sends a "share" message
2923 * @param array $owner the array of the item owner
2924 * @param array $contact Target of the communication
2926 * @return int The result of the transmission
2928 public static function send_share($owner,$contact) {
2930 $message = array("sender_handle" => self::my_handle($owner),
2931 "recipient_handle" => $contact["addr"]);
2933 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2935 return self::build_and_transmit($owner, $contact, "request", $message);
2939 * @brief sends an "unshare"
2941 * @param array $owner the array of the item owner
2942 * @param array $contact Target of the communication
2944 * @return int The result of the transmission
2946 public static function send_unshare($owner,$contact) {
2948 $message = array("post_guid" => $owner["guid"],
2949 "diaspora_handle" => self::my_handle($owner),
2950 "type" => "Person");
2952 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2954 return self::build_and_transmit($owner, $contact, "retraction", $message);
2958 * @brief Checks a message body if it is a reshare
2960 * @param string $body The message body that is to be check
2961 * @param bool $complete Should it be a complete check or a simple check?
2963 * @return array|bool Reshare details or "false" if no reshare
2965 public static function is_reshare($body, $complete = true) {
2966 $body = trim($body);
2968 // Skip if it isn't a pure repeated messages
2969 // Does it start with a share?
2970 if ((strpos($body, "[share") > 0) AND $complete)
2973 // Does it end with a share?
2974 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2977 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2978 // Skip if there is no shared message in there
2979 if ($body == $attributes)
2982 // If we don't do the complete check we quit here
2987 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2988 if ($matches[1] != "")
2989 $guid = $matches[1];
2991 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2992 if ($matches[1] != "")
2993 $guid = $matches[1];
2996 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2997 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3000 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3001 $ret["root_guid"] = $guid;
3007 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3008 if ($matches[1] != "")
3009 $profile = $matches[1];
3011 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3012 if ($matches[1] != "")
3013 $profile = $matches[1];
3017 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3018 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
3022 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3023 if ($matches[1] != "")
3024 $link = $matches[1];
3026 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3027 if ($matches[1] != "")
3028 $link = $matches[1];
3030 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3031 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
3038 * @brief Create an event array
3040 * @param integer $event_id The id of the event
3042 * @return array with event data
3044 private static function build_event($event_id) {
3046 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3047 if (!dbm::is_result($r)) {
3053 $eventdata = array();
3055 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3056 if (!dbm::is_result($r)) {
3062 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3063 if (!dbm::is_result($r)) {
3069 $eventdata['author'] = self::my_handle($owner);
3071 if ($event['guid']) {
3072 $eventdata['guid'] = $event['guid'];
3075 $mask = 'Y-m-d\TH:i:s\Z';
3077 /// @todo - establish "all day" events in Friendica
3078 $eventdata["all_day"] = "false";
3080 if (!$event['adjust']) {
3081 $eventdata['timezone'] = $user['timezone'];
3083 if ($eventdata['timezone'] == "") {
3084 $eventdata['timezone'] = 'UTC';
3088 if ($event['start']) {
3089 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3091 if ($event['finish'] AND !$event['nofinish']) {
3092 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3094 if ($event['summary']) {
3095 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3097 if ($event['desc']) {
3098 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3100 if ($event['location']) {
3101 $location = array();
3102 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3103 $location["lat"] = 0;
3104 $location["lng"] = 0;
3105 $eventdata['location'] = $location;
3112 * @brief Create a post (status message or reshare)
3114 * @param array $item The item that will be exported
3115 * @param array $owner the array of the item owner
3118 * 'type' -> Message type ("status_message" or "reshare")
3119 * 'message' -> Array of XML elements of the status
3121 public static function build_status($item, $owner) {
3123 $cachekey = "diaspora:build_status:".$item['guid'];
3125 $result = Cache::get($cachekey);
3126 if (!is_null($result)) {
3130 $myaddr = self::my_handle($owner);
3132 $public = (($item["private"]) ? "false" : "true");
3134 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3136 // Detect a share element and do a reshare
3137 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3138 $message = array("root_diaspora_id" => $ret["root_handle"],
3139 "root_guid" => $ret["root_guid"],
3140 "guid" => $item["guid"],
3141 "diaspora_handle" => $myaddr,
3142 "public" => $public,
3143 "created_at" => $created,
3144 "provider_display_name" => $item["app"]);
3148 $title = $item["title"];
3149 $body = $item["body"];
3151 // convert to markdown
3152 $body = html_entity_decode(bb2diaspora($body));
3156 $body = "## ".html_entity_decode($title)."\n\n".$body;
3158 if ($item["attach"]) {
3159 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3161 $body .= "\n".t("Attachments:")."\n";
3162 foreach ($matches as $mtch)
3163 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3167 $location = array();
3169 if ($item["location"] != "")
3170 $location["address"] = $item["location"];
3172 if ($item["coord"] != "") {
3173 $coord = explode(" ", $item["coord"]);
3174 $location["lat"] = $coord[0];
3175 $location["lng"] = $coord[1];
3178 $message = array("raw_message" => $body,
3179 "location" => $location,
3180 "guid" => $item["guid"],
3181 "diaspora_handle" => $myaddr,
3182 "public" => $public,
3183 "created_at" => $created,
3184 "provider_display_name" => $item["app"]);
3186 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3187 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3188 unset($message["location"]);
3191 if ($item['event-id'] > 0) {
3192 $event = self::build_event($item['event-id']);
3193 if (count($event)) {
3194 $message['event'] = $event;
3196 /// @todo Once Diaspora supports it, we will remove the body
3197 // $message['raw_message'] = '';
3201 $type = "status_message";
3204 $msg = array("type" => $type, "message" => $message);
3206 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3212 * @brief Sends a post
3214 * @param array $item The item that will be exported
3215 * @param array $owner the array of the item owner
3216 * @param array $contact Target of the communication
3217 * @param bool $public_batch Is it a public post?
3219 * @return int The result of the transmission
3221 public static function send_status($item, $owner, $contact, $public_batch = false) {
3223 $status = self::build_status($item, $owner);
3225 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3229 * @brief Creates a "like" object
3231 * @param array $item The item that will be exported
3232 * @param array $owner the array of the item owner
3234 * @return array The data for a "like"
3236 private static function construct_like($item, $owner) {
3238 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3239 dbesc($item["thr-parent"]));
3240 if (!dbm::is_result($p))
3245 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3246 if ($item['verb'] === ACTIVITY_LIKE) {
3248 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3249 $positive = "false";
3252 return(array("positive" => $positive,
3253 "guid" => $item["guid"],
3254 "target_type" => $target_type,
3255 "parent_guid" => $parent["guid"],
3256 "author_signature" => "",
3257 "diaspora_handle" => self::my_handle($owner)));
3261 * @brief Creates an "EventParticipation" object
3263 * @param array $item The item that will be exported
3264 * @param array $owner the array of the item owner
3266 * @return array The data for an "EventParticipation"
3268 private static function construct_attend($item, $owner) {
3270 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3271 dbesc($item["thr-parent"]));
3272 if (!dbm::is_result($p))
3277 switch ($item['verb']) {
3278 case ACTIVITY_ATTEND:
3279 $attend_answer = 'accepted';
3281 case ACTIVITY_ATTENDNO:
3282 $attend_answer = 'declined';
3284 case ACTIVITY_ATTENDMAYBE:
3285 $attend_answer = 'tentative';
3288 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3292 return(array("author" => self::my_handle($owner),
3293 "guid" => $item["guid"],
3294 "parent_guid" => $parent["guid"],
3295 "status" => $attend_answer,
3296 "author_signature" => ""));
3300 * @brief Creates the object for a comment
3302 * @param array $item The item that will be exported
3303 * @param array $owner the array of the item owner
3305 * @return array The data for a comment
3307 private static function construct_comment($item, $owner) {
3309 $cachekey = "diaspora:construct_comment:".$item['guid'];
3311 $result = Cache::get($cachekey);
3312 if (!is_null($result)) {
3316 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3317 intval($item["parent"]),
3318 intval($item["parent"])
3321 if (!dbm::is_result($p))
3326 $text = html_entity_decode(bb2diaspora($item["body"]));
3327 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3329 $comment = array("guid" => $item["guid"],
3330 "parent_guid" => $parent["guid"],
3331 "author_signature" => "",
3333 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3334 "diaspora_handle" => self::my_handle($owner));
3336 // Send the thread parent guid only if it is a threaded comment
3337 if ($item['thr-parent'] != $item['parent-uri']) {
3338 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3341 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3347 * @brief Send a like or a comment
3349 * @param array $item The item that will be exported
3350 * @param array $owner the array of the item owner
3351 * @param array $contact Target of the communication
3352 * @param bool $public_batch Is it a public post?
3354 * @return int The result of the transmission
3356 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3358 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3359 $message = self::construct_attend($item, $owner);
3360 $type = "event_participation";
3361 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3362 $message = self::construct_like($item, $owner);
3365 $message = self::construct_comment($item, $owner);
3372 $message["author_signature"] = self::signature($owner, $message);
3374 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3378 * @brief Creates a message from a signature record entry
3380 * @param array $item The item that will be exported
3381 * @param array $signature The entry of the "sign" record
3383 * @return string The message
3385 private static function message_from_signature($item, $signature) {
3387 // Split the signed text
3388 $signed_parts = explode(";", $signature['signed_text']);
3390 if ($item["deleted"])
3391 $message = array("parent_author_signature" => "",
3392 "target_guid" => $signed_parts[0],
3393 "target_type" => $signed_parts[1],
3394 "sender_handle" => $signature['signer'],
3395 "target_author_signature" => $signature['signature']);
3396 elseif ($item['verb'] === ACTIVITY_LIKE)
3397 $message = array("positive" => $signed_parts[0],
3398 "guid" => $signed_parts[1],
3399 "target_type" => $signed_parts[2],
3400 "parent_guid" => $signed_parts[3],
3401 "parent_author_signature" => "",
3402 "author_signature" => $signature['signature'],
3403 "diaspora_handle" => $signed_parts[4]);
3405 // Remove the comment guid
3406 $guid = array_shift($signed_parts);
3408 // Remove the parent guid
3409 $parent_guid = array_shift($signed_parts);
3411 // Remove the handle
3412 $handle = array_pop($signed_parts);
3414 // Glue the parts together
3415 $text = implode(";", $signed_parts);
3417 $message = array("guid" => $guid,
3418 "parent_guid" => $parent_guid,
3419 "parent_author_signature" => "",
3420 "author_signature" => $signature['signature'],
3421 "text" => implode(";", $signed_parts),
3422 "diaspora_handle" => $handle);
3428 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3430 * @param array $item The item that will be exported
3431 * @param array $owner the array of the item owner
3432 * @param array $contact Target of the communication
3433 * @param bool $public_batch Is it a public post?
3435 * @return int The result of the transmission
3437 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3439 if ($item["deleted"])
3440 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3441 elseif ($item['verb'] === ACTIVITY_LIKE)
3446 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3448 // fetch the original signature
3450 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3451 intval($item["id"]));
3454 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3460 // Old way - is used by the internal Friendica functions
3461 /// @todo Change all signatur storing functions to the new format
3462 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3463 $message = self::message_from_signature($item, $signature);
3465 $msg = json_decode($signature['signed_text'], true);
3468 if (is_array($msg)) {
3469 foreach ($msg AS $field => $data) {
3470 if (!$item["deleted"]) {
3471 if ($field == "author")
3472 $field = "diaspora_handle";
3473 if ($field == "parent_type")
3474 $field = "target_type";
3477 $message[$field] = $data;
3480 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3483 $message["parent_author_signature"] = self::signature($owner, $message);
3485 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3487 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3491 * @brief Sends a retraction (deletion) of a message, like or comment
3493 * @param array $item The item that will be exported
3494 * @param array $owner the array of the item owner
3495 * @param array $contact Target of the communication
3496 * @param bool $public_batch Is it a public post?
3497 * @param bool $relay Is the retraction transmitted from a relay?
3499 * @return int The result of the transmission
3501 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3503 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3505 // Check whether the retraction is for a top-level post or whether it's a relayable
3506 if ($item["uri"] !== $item["parent-uri"]) {
3507 $msg_type = "relayable_retraction";
3508 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3510 $msg_type = "signed_retraction";
3511 $target_type = "StatusMessage";
3514 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3515 $signature = "parent_author_signature";
3517 $signature = "target_author_signature";
3519 $signed_text = $item["guid"].";".$target_type;
3521 $message = array("target_guid" => $item['guid'],
3522 "target_type" => $target_type,
3523 "sender_handle" => $itemaddr,
3524 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3526 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3528 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3532 * @brief Sends a mail
3534 * @param array $item The item that will be exported
3535 * @param array $owner The owner
3536 * @param array $contact Target of the communication
3538 * @return int The result of the transmission
3540 public static function send_mail($item, $owner, $contact) {
3542 $myaddr = self::my_handle($owner);
3544 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3545 intval($item["convid"]),
3546 intval($item["uid"])
3549 if (!dbm::is_result($r)) {
3550 logger("conversation not found.");
3556 "guid" => $cnv["guid"],
3557 "subject" => $cnv["subject"],
3558 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3559 "diaspora_handle" => $cnv["creator"],
3560 "participant_handles" => $cnv["recips"]
3563 $body = bb2diaspora($item["body"]);
3564 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3566 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3567 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3570 "guid" => $item["guid"],
3571 "parent_guid" => $cnv["guid"],
3572 "parent_author_signature" => $sig,
3573 "author_signature" => $sig,
3575 "created_at" => $created,
3576 "diaspora_handle" => $myaddr,
3577 "conversation_guid" => $cnv["guid"]
3580 if ($item["reply"]) {
3584 $message = array("guid" => $cnv["guid"],
3585 "subject" => $cnv["subject"],
3586 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3588 "diaspora_handle" => $cnv["creator"],
3589 "participant_handles" => $cnv["recips"]);
3591 $type = "conversation";
3594 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3598 * @brief Sends profile data
3600 * @param int $uid The user id
3602 public static function send_profile($uid, $recips = false) {
3608 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3609 AND `uid` = %d AND `rel` != %d",
3610 dbesc(NETWORK_DIASPORA),
3612 intval(CONTACT_IS_SHARING)
3617 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3619 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3620 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3621 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3630 $handle = $profile["addr"];
3631 $first = ((strpos($profile['name'],' ')
3632 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3633 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3634 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3635 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3636 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3637 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3639 if ($searchable === 'true') {
3640 $dob = '1000-00-00';
3642 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3643 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3645 $about = $profile['about'];
3646 $about = strip_tags(bbcode($about));
3648 $location = formatted_location($profile);
3650 if ($profile['pub_keywords']) {
3651 $kw = str_replace(',',' ',$profile['pub_keywords']);
3652 $kw = str_replace(' ',' ',$kw);
3653 $arr = explode(' ',$profile['pub_keywords']);
3655 for ($x = 0; $x < 5; $x ++) {
3657 $tags .= '#'. trim($arr[$x]) .' ';
3661 $tags = trim($tags);
3664 $message = array("diaspora_handle" => $handle,
3665 "first_name" => $first,
3666 "last_name" => $last,
3667 "image_url" => $large,
3668 "image_url_medium" => $medium,
3669 "image_url_small" => $small,
3671 "gender" => $profile['gender'],
3673 "location" => $location,
3674 "searchable" => $searchable,
3675 "tag_string" => $tags);
3677 foreach ($recips as $recip) {
3678 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3679 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3684 * @brief Stores the signature for likes that are created on our system
3686 * @param array $contact The contact array of the "like"
3687 * @param int $post_id The post id of the "like"
3689 * @return bool Success
3691 public static function store_like_signature($contact, $post_id) {
3693 // Is the contact the owner? Then fetch the private key
3694 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3695 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3699 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3700 if (!dbm::is_result($r)) {
3704 $contact["uprvkey"] = $r[0]['prvkey'];
3706 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3707 if (!dbm::is_result($r)) {
3711 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3715 $message = self::construct_like($r[0], $contact);
3716 $message["author_signature"] = self::signature($contact, $message);
3718 // We now store the signature more flexible to dynamically support new fields.
3719 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3720 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3721 intval($message_id),
3722 dbesc(json_encode($message))
3725 logger('Stored diaspora like signature');
3730 * @brief Stores the signature for comments that are created on our system
3732 * @param array $item The item array of the comment
3733 * @param array $contact The contact array of the item owner
3734 * @param string $uprvkey The private key of the sender
3735 * @param int $message_id The message id of the comment
3737 * @return bool Success
3739 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3741 if ($uprvkey == "") {
3742 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3746 $contact["uprvkey"] = $uprvkey;
3748 $message = self::construct_comment($item, $contact);
3749 $message["author_signature"] = self::signature($contact, $message);
3751 // We now store the signature more flexible to dynamically support new fields.
3752 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3753 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3754 intval($message_id),
3755 dbesc(json_encode($message))
3758 logger('Stored diaspora comment signature');