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: Decodes incoming Diaspora message
166 * @param array $importer Array of the importer user
167 * @param string $xml urldecoded Diaspora salmon
170 * 'message' -> decoded Diaspora XML message
171 * 'author' -> author diaspora handle
172 * 'key' -> author public key (converted to pkcs#8)
174 public static function decode($importer, $xml) {
177 $basedom = parse_xml_string($xml);
179 if (!is_object($basedom))
182 $children = $basedom->children('https://joindiaspora.com/protocol');
184 if($children->header) {
186 $author_link = str_replace('acct:','',$children->header->author_id);
189 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
191 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
192 $ciphertext = base64_decode($encrypted_header->ciphertext);
194 $outer_key_bundle = '';
195 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
197 $j_outer_key_bundle = json_decode($outer_key_bundle);
199 $outer_iv = base64_decode($j_outer_key_bundle->iv);
200 $outer_key = base64_decode($j_outer_key_bundle->key);
202 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
205 $decrypted = pkcs5_unpad($decrypted);
207 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
208 $idom = parse_xml_string($decrypted,false);
210 $inner_iv = base64_decode($idom->iv);
211 $inner_aes_key = base64_decode($idom->aes_key);
213 $author_link = str_replace('acct:','',$idom->author_id);
216 $dom = $basedom->children(NAMESPACE_SALMON_ME);
218 // figure out where in the DOM tree our data is hiding
220 if($dom->provenance->data)
221 $base = $dom->provenance;
222 elseif($dom->env->data)
228 logger('unable to locate salmon data in xml');
229 http_status_exit(400);
233 // Stash the signature away for now. We have to find their key or it won't be good for anything.
234 $signature = base64url_decode($base->sig);
238 // strip whitespace so our data element will return to one big base64 blob
239 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
242 // stash away some other stuff for later
244 $type = $base->data[0]->attributes()->type[0];
245 $keyhash = $base->sig[0]->attributes()->keyhash[0];
246 $encoding = $base->encoding;
250 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
254 $data = base64url_decode($data);
258 $inner_decrypted = $data;
261 // Decode the encrypted blob
263 $inner_encrypted = base64_decode($data);
264 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
265 $inner_decrypted = pkcs5_unpad($inner_decrypted);
269 logger('Could not retrieve author URI.');
270 http_status_exit(400);
272 // Once we have the author URI, go to the web and try to find their public key
273 // (first this will look it up locally if it is in the fcontact cache)
274 // This will also convert diaspora public key from pkcs#1 to pkcs#8
276 logger('Fetching key for '.$author_link);
277 $key = self::key($author_link);
280 logger('Could not retrieve author key.');
281 http_status_exit(400);
284 $verify = rsa_verify($signed_data,$signature,$key);
287 logger('Message did not verify. Discarding.');
288 http_status_exit(400);
291 logger('Message verified.');
293 return array('message' => (string)$inner_decrypted,
294 'author' => unxmlify($author_link),
295 'key' => (string)$key);
300 * @brief Dispatches public messages and find the fitting receivers
302 * @param array $msg The post that will be dispatched
304 * @return int The message id of the generated message, "true" or "false" if there was an error
306 public static function dispatch_public($msg) {
308 $enabled = intval(get_config("system", "diaspora_enabled"));
310 logger("diaspora is disabled");
314 // Now distribute it to the followers
315 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
316 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
317 AND NOT `account_expired` AND NOT `account_removed`",
318 dbesc(NETWORK_DIASPORA),
319 dbesc($msg["author"])
321 if (dbm::is_result($r)) {
322 foreach ($r as $rr) {
323 logger("delivering to: ".$rr["username"]);
324 self::dispatch($rr,$msg);
327 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true), LOGGER_DEBUG);
330 $social_relay = (bool)Config::get('system', 'relay_subscribe', false);
332 // Use a dummy importer to import the data for the public copy
333 if (dbm::is_result($r) OR $social_relay) {
334 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
335 $message_id = self::dispatch($importer,$msg);
342 * @brief Dispatches the different message types to the different functions
344 * @param array $importer Array of the importer user
345 * @param array $msg The post that will be dispatched
347 * @return int The message id of the generated message, "true" or "false" if there was an error
349 public static function dispatch($importer, $msg) {
351 // The sender is the handle of the contact that sent the message.
352 // This will often be different with relayed messages (for example "like" and "comment")
353 $sender = $msg["author"];
355 if (!self::valid_posting($msg, $fields)) {
356 logger("Invalid posting");
360 $type = $fields->getName();
362 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
365 case "account_deletion":
366 return self::receive_account_deletion($importer, $fields);
369 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
372 return self::receive_contact_request($importer, $fields);
375 return self::receive_conversation($importer, $msg, $fields);
378 return self::receive_like($importer, $sender, $fields);
381 return self::receive_message($importer, $fields);
383 case "participation": // Not implemented
384 return self::receive_participation($importer, $fields);
386 case "photo": // Not implemented
387 return self::receive_photo($importer, $fields);
389 case "poll_participation": // Not implemented
390 return self::receive_poll_participation($importer, $fields);
393 return self::receive_profile($importer, $fields);
396 return self::receive_reshare($importer, $fields, $msg["message"]);
399 return self::receive_retraction($importer, $sender, $fields);
401 case "status_message":
402 return self::receive_status_message($importer, $fields, $msg["message"]);
405 logger("Unknown message type ".$type);
413 * @brief Checks if a posting is valid and fetches the data fields.
415 * This function does not only check the signature.
416 * It also does the conversion between the old and the new diaspora format.
418 * @param array $msg Array with the XML, the sender handle and the sender signature
419 * @param object $fields SimpleXML object that contains the posting when it is valid
421 * @return bool Is the posting valid?
423 private static function valid_posting($msg, &$fields) {
425 $data = parse_xml_string($msg["message"], false);
427 if (!is_object($data)) {
428 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
432 $first_child = $data->getName();
434 // Is this the new or the old version?
435 if ($data->getName() == "XML") {
437 foreach ($data->post->children() as $child)
444 $type = $element->getName();
447 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
449 // All retractions are handled identically from now on.
450 // In the new version there will only be "retraction".
451 if (in_array($type, array("signed_retraction", "relayable_retraction")))
452 $type = "retraction";
454 if ($type == "request")
457 $fields = new SimpleXMLElement("<".$type."/>");
461 foreach ($element->children() AS $fieldname => $entry) {
463 // Translation for the old XML structure
464 if ($fieldname == "diaspora_handle")
465 $fieldname = "author";
467 if ($fieldname == "participant_handles")
468 $fieldname = "participants";
470 if (in_array($type, array("like", "participation"))) {
471 if ($fieldname == "target_type")
472 $fieldname = "parent_type";
475 if ($fieldname == "sender_handle")
476 $fieldname = "author";
478 if ($fieldname == "recipient_handle")
479 $fieldname = "recipient";
481 if ($fieldname == "root_diaspora_id")
482 $fieldname = "root_author";
484 if ($type == "retraction") {
485 if ($fieldname == "post_guid")
486 $fieldname = "target_guid";
488 if ($fieldname == "type")
489 $fieldname = "target_type";
493 if (($fieldname == "author_signature") AND ($entry != ""))
494 $author_signature = base64_decode($entry);
495 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
496 $parent_author_signature = base64_decode($entry);
497 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
498 if ($signed_data != "") {
500 $signed_data_parent .= ";";
503 $signed_data .= $entry;
505 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
506 ($orig_type == "relayable_retraction"))
507 xml::copy($entry, $fields, $fieldname);
510 // This is something that shouldn't happen at all.
511 if (in_array($type, array("status_message", "reshare", "profile")))
512 if ($msg["author"] != $fields->author) {
513 logger("Message handle is not the same as envelope sender. Quitting this message.");
517 // Only some message types have signatures. So we quit here for the other types.
518 if (!in_array($type, array("comment", "message", "like")))
521 // No author_signature? This is a must, so we quit.
522 if (!isset($author_signature)) {
523 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
527 if (isset($parent_author_signature)) {
528 $key = self::key($msg["author"]);
530 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
531 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);
536 $key = self::key($fields->author);
538 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
539 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
546 * @brief Fetches the public key for a given handle
548 * @param string $handle The handle
550 * @return string The public key
552 private static function key($handle) {
553 $handle = strval($handle);
555 logger("Fetching diaspora key for: ".$handle);
557 $r = self::person_by_handle($handle);
565 * @brief Fetches data for a given handle
567 * @param string $handle The handle
569 * @return array the queried data
571 private static function person_by_handle($handle) {
573 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
574 dbesc(NETWORK_DIASPORA),
579 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
581 // update record occasionally so it doesn't get stale
582 $d = strtotime($person["updated"]." +00:00");
583 if ($d < strtotime("now - 14 days"))
586 if ($person["guid"] == "")
590 if (!$person OR $update) {
591 logger("create or refresh", LOGGER_DEBUG);
592 $r = probe_url($handle, PROBE_DIASPORA);
594 // Note that Friendica contacts will return a "Diaspora person"
595 // if Diaspora connectivity is enabled on their server
596 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
597 self::add_fcontact($r, $update);
605 * @brief Updates the fcontact table
607 * @param array $arr The fcontact data
608 * @param bool $update Update or insert?
610 * @return string The id of the fcontact entry
612 private static function add_fcontact($arr, $update = false) {
615 $r = q("UPDATE `fcontact` SET
629 WHERE `url` = '%s' AND `network` = '%s'",
631 dbesc($arr["photo"]),
632 dbesc($arr["request"]),
634 dbesc(strtolower($arr["addr"])),
636 dbesc($arr["batch"]),
637 dbesc($arr["notify"]),
639 dbesc($arr["confirm"]),
640 dbesc($arr["alias"]),
641 dbesc($arr["pubkey"]),
642 dbesc(datetime_convert()),
644 dbesc($arr["network"])
647 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
648 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
649 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
652 dbesc($arr["photo"]),
653 dbesc($arr["request"]),
657 dbesc($arr["batch"]),
658 dbesc($arr["notify"]),
660 dbesc($arr["confirm"]),
661 dbesc($arr["network"]),
662 dbesc($arr["alias"]),
663 dbesc($arr["pubkey"]),
664 dbesc(datetime_convert())
672 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
674 * @param int $contact_id The id in the contact table
675 * @param int $gcontact_id The id in the gcontact table
677 * @return string the handle
679 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
682 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
684 if ($gcontact_id != 0) {
685 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
686 intval($gcontact_id));
688 if (dbm::is_result($r)) {
689 return strtolower($r[0]["addr"]);
693 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
694 intval($contact_id));
696 if (dbm::is_result($r)) {
699 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
701 if ($contact['addr'] != "") {
702 $handle = $contact['addr'];
704 $baseurl_start = strpos($contact['url'],'://') + 3;
705 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
706 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
707 $handle = $contact['nick'].'@'.$baseurl;
711 return strtolower($handle);
715 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
718 * @param mixed $fcontact_guid Hexadecimal string guid
720 * @return string the contact url or null
722 public static function url_from_contact_guid($fcontact_guid) {
723 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
725 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
726 dbesc(NETWORK_DIASPORA),
727 dbesc($fcontact_guid)
730 if (dbm::is_result($r)) {
738 * @brief Get a contact id for a given handle
740 * @param int $uid The user id
741 * @param string $handle The handle in the format user@domain.tld
743 * @return The contact id
745 private static function contact_by_handle($uid, $handle) {
747 // First do a direct search on the contact table
748 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
753 if (dbm::is_result($r)) {
756 // We haven't found it?
757 // We use another function for it that will possibly create a contact entry
758 $cid = get_contact($handle, $uid);
761 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
763 if (dbm::is_result($r)) {
769 $handle_parts = explode("@", $handle);
770 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
771 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
776 if (dbm::is_result($r)) {
780 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
785 * @brief Check if posting is allowed for this contact
787 * @param array $importer Array of the importer user
788 * @param array $contact The contact that is checked
789 * @param bool $is_comment Is the check for a comment?
791 * @return bool is the contact allowed to post?
793 private static function post_allow($importer, $contact, $is_comment = false) {
795 // perhaps we were already sharing with this person. Now they're sharing with us.
796 // That makes us friends.
797 // Normally this should have handled by getting a request - but this could get lost
798 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
799 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
800 intval(CONTACT_IS_FRIEND),
801 intval($contact["id"]),
802 intval($importer["uid"])
804 $contact["rel"] = CONTACT_IS_FRIEND;
805 logger("defining user ".$contact["nick"]." as friend");
808 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
810 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
812 if($contact["rel"] == CONTACT_IS_FOLLOWER)
813 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
816 // Messages for the global users are always accepted
817 if ($importer["uid"] == 0)
824 * @brief Fetches the contact id for a handle and checks if posting is allowed
826 * @param array $importer Array of the importer user
827 * @param string $handle The checked handle in the format user@domain.tld
828 * @param bool $is_comment Is the check for a comment?
830 * @return array The contact data
832 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
833 $contact = self::contact_by_handle($importer["uid"], $handle);
835 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
839 if (!self::post_allow($importer, $contact, $is_comment)) {
840 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
847 * @brief Does the message already exists on the system?
849 * @param int $uid The user id
850 * @param string $guid The guid of the message
852 * @return int|bool message id if the message already was stored into the system - or false.
854 private static function message_exists($uid, $guid) {
855 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
860 if (dbm::is_result($r)) {
861 logger("message ".$guid." already exists for user ".$uid);
869 * @brief Checks for links to posts in a message
871 * @param array $item The item array
873 private static function fetch_guid($item) {
874 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
875 function ($match) use ($item){
876 return(self::fetch_guid_sub($match, $item));
881 * @brief Checks for relative /people/* links in an item body to match local
882 * contacts or prepends the remote host taken from the author link.
884 * @param string $body The item body to replace links from
885 * @param string $author_link The author link for missing local contact fallback
887 * @return the replaced string
889 public function replace_people_guid($body, $author_link) {
890 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
891 function ($match) use ($author_link) {
893 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
894 // 1 => '0123456789abcdef'
896 $handle = self::url_from_contact_guid($match[1]);
899 $return = '@[url='.$handle.']'.$match[2].'[/url]';
901 // No local match, restoring absolute remote URL from author scheme and host
902 $author_url = parse_url($author_link);
903 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
913 * @brief sub function of "fetch_guid" which checks for links in messages
915 * @param array $match array containing a link that has to be checked for a message link
916 * @param array $item The item array
918 private static function fetch_guid_sub($match, $item) {
919 if (!self::store_by_guid($match[1], $item["author-link"]))
920 self::store_by_guid($match[1], $item["owner-link"]);
924 * @brief Fetches an item with a given guid from a given server
926 * @param string $guid the message guid
927 * @param string $server The server address
928 * @param int $uid The user id of the user
930 * @return int the message id of the stored message or false
932 private static function store_by_guid($guid, $server, $uid = 0) {
933 $serverparts = parse_url($server);
934 $server = $serverparts["scheme"]."://".$serverparts["host"];
936 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
938 $msg = self::message($guid, $server);
943 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
945 // Now call the dispatcher
946 return self::dispatch_public($msg);
950 * @brief Fetches a message from a server
952 * @param string $guid message guid
953 * @param string $server The url of the server
954 * @param int $level Endless loop prevention
957 * 'message' => The message XML
958 * 'author' => The author handle
959 * 'key' => The public key of the author
961 private static function message($guid, $server, $level = 0) {
966 // This will work for new Diaspora servers and Friendica servers from 3.5
967 $source_url = $server."/fetch/post/".$guid;
968 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
970 $envelope = fetch_url($source_url);
972 logger("Envelope was fetched.", LOGGER_DEBUG);
973 $x = self::verify_magic_envelope($envelope);
975 logger("Envelope could not be verified.", LOGGER_DEBUG);
977 logger("Envelope was verified.", LOGGER_DEBUG);
981 // This will work for older Diaspora and Friendica servers
983 $source_url = $server."/p/".$guid.".xml";
984 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
986 $x = fetch_url($source_url);
991 $source_xml = parse_xml_string($x, false);
993 if (!is_object($source_xml))
996 if ($source_xml->post->reshare) {
997 // Reshare of a reshare - old Diaspora version
998 logger("Message is a reshare", LOGGER_DEBUG);
999 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1000 } elseif ($source_xml->getName() == "reshare") {
1001 // Reshare of a reshare - new Diaspora version
1002 logger("Message is a new reshare", LOGGER_DEBUG);
1003 return self::message($source_xml->root_guid, $server, ++$level);
1008 // Fetch the author - for the old and the new Diaspora version
1009 if ($source_xml->post->status_message->diaspora_handle)
1010 $author = (string)$source_xml->post->status_message->diaspora_handle;
1011 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1012 $author = (string)$source_xml->author;
1014 // If this isn't a "status_message" then quit
1016 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1020 $msg = array("message" => $x, "author" => $author);
1022 $msg["key"] = self::key($msg["author"]);
1028 * @brief Fetches the item record of a given guid
1030 * @param int $uid The user id
1031 * @param string $guid message guid
1032 * @param string $author The handle of the item
1033 * @param array $contact The contact of the item owner
1035 * @return array the item record
1037 private static function parent_item($uid, $guid, $author, $contact) {
1038 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1039 `author-name`, `author-link`, `author-avatar`,
1040 `owner-name`, `owner-link`, `owner-avatar`
1041 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1042 intval($uid), dbesc($guid));
1045 $result = self::store_by_guid($guid, $contact["url"], $uid);
1048 $person = self::person_by_handle($author);
1049 $result = self::store_by_guid($guid, $person["url"], $uid);
1053 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1055 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1056 `author-name`, `author-link`, `author-avatar`,
1057 `owner-name`, `owner-link`, `owner-avatar`
1058 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1059 intval($uid), dbesc($guid));
1064 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1067 logger("parent item found: parent: ".$guid." - user: ".$uid);
1073 * @brief returns contact details
1075 * @param array $contact The default contact if the person isn't found
1076 * @param array $person The record of the person
1077 * @param int $uid The user id
1080 * 'cid' => contact id
1081 * 'network' => network type
1083 private static function author_contact_by_url($contact, $person, $uid) {
1085 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1086 dbesc(normalise_link($person["url"])), intval($uid));
1089 $network = $r[0]["network"];
1091 // We are receiving content from a user that is about to be terminated
1092 // This means the user is vital, so we remove a possible termination date.
1093 unmark_for_death($contact);
1095 $cid = $contact["id"];
1096 $network = NETWORK_DIASPORA;
1099 return array("cid" => $cid, "network" => $network);
1103 * @brief Is the profile a hubzilla profile?
1105 * @param string $url The profile link
1107 * @return bool is it a hubzilla server?
1109 public static function is_redmatrix($url) {
1110 return(strstr($url, "/channel/"));
1114 * @brief Generate a post link with a given handle and message guid
1116 * @param string $addr The user handle
1117 * @param string $guid message guid
1119 * @return string the post link
1121 private static function plink($addr, $guid) {
1122 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1126 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1128 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1129 // So we try another way as well.
1130 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1132 $r[0]["network"] = $s[0]["network"];
1134 if ($r[0]["network"] == NETWORK_DFRN)
1135 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1137 if (self::is_redmatrix($r[0]["url"]))
1138 return $r[0]["url"]."/?f=&mid=".$guid;
1140 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1144 * @brief Processes an account deletion
1146 * @param array $importer Array of the importer user
1147 * @param object $data The message object
1149 * @return bool Success
1151 private static function receive_account_deletion($importer, $data) {
1153 /// @todo Account deletion should remove the contact from the global contacts as well
1155 $author = notags(unxmlify($data->author));
1157 $contact = self::contact_by_handle($importer["uid"], $author);
1159 logger("cannot find contact for author: ".$author);
1163 // We now remove the contact
1164 contact_remove($contact["id"]);
1169 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1171 * @param string $author Author handle
1172 * @param string $guid Message guid
1173 * @param boolean $onlyfound Only return uri when found in the database
1175 * @return string The constructed uri or the one from our database
1177 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1179 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1180 if (dbm::is_result($r)) {
1181 return $r[0]["uri"];
1182 } elseif (!$onlyfound) {
1183 return $author.":".$guid;
1190 * @brief Fetch the guid from our database with a given uri
1192 * @param string $author Author handle
1193 * @param string $uri Message uri
1195 * @return string The post guid
1197 private static function get_guid_from_uri($uri, $uid) {
1199 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1200 if (dbm::is_result($r)) {
1201 return $r[0]["guid"];
1208 * @brief Processes an incoming comment
1210 * @param array $importer Array of the importer user
1211 * @param string $sender The sender of the message
1212 * @param object $data The message object
1213 * @param string $xml The original XML of the message
1215 * @return int The message id of the generated comment or "false" if there was an error
1217 private static function receive_comment($importer, $sender, $data, $xml) {
1218 $guid = notags(unxmlify($data->guid));
1219 $parent_guid = notags(unxmlify($data->parent_guid));
1220 $text = unxmlify($data->text);
1221 $author = notags(unxmlify($data->author));
1223 if (isset($data->created_at)) {
1224 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1226 $created_at = datetime_convert();
1229 if (isset($data->thread_parent_guid)) {
1230 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1231 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1236 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1241 $message_id = self::message_exists($importer["uid"], $guid);
1246 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1247 if (!$parent_item) {
1251 $person = self::person_by_handle($author);
1252 if (!is_array($person)) {
1253 logger("unable to find author details");
1257 // Fetch the contact id - if we know this contact
1258 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1260 $datarray = array();
1262 $datarray["uid"] = $importer["uid"];
1263 $datarray["contact-id"] = $author_contact["cid"];
1264 $datarray["network"] = $author_contact["network"];
1266 $datarray["author-name"] = $person["name"];
1267 $datarray["author-link"] = $person["url"];
1268 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1270 $datarray["owner-name"] = $contact["name"];
1271 $datarray["owner-link"] = $contact["url"];
1272 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1274 $datarray["guid"] = $guid;
1275 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1277 $datarray["type"] = "remote-comment";
1278 $datarray["verb"] = ACTIVITY_POST;
1279 $datarray["gravity"] = GRAVITY_COMMENT;
1281 if ($thr_uri != "") {
1282 $datarray["parent-uri"] = $thr_uri;
1284 $datarray["parent-uri"] = $parent_item["uri"];
1287 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1288 $datarray["object"] = $xml;
1290 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1292 $body = diaspora2bb($text);
1294 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1296 self::fetch_guid($datarray);
1298 $message_id = item_store($datarray);
1301 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1304 // If we are the origin of the parent we store the original data and notify our followers
1305 if($message_id AND $parent_item["origin"]) {
1307 // Formerly we stored the signed text, the signature and the author in different fields.
1308 // We now store the raw data so that we are more flexible.
1309 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1310 intval($message_id),
1311 dbesc(json_encode($data))
1315 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1322 * @brief processes and stores private messages
1324 * @param array $importer Array of the importer user
1325 * @param array $contact The contact of the message
1326 * @param object $data The message object
1327 * @param array $msg Array of the processed message, author handle and key
1328 * @param object $mesg The private message
1329 * @param array $conversation The conversation record to which this message belongs
1331 * @return bool "true" if it was successful
1333 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1334 $guid = notags(unxmlify($data->guid));
1335 $subject = notags(unxmlify($data->subject));
1336 $author = notags(unxmlify($data->author));
1338 $msg_guid = notags(unxmlify($mesg->guid));
1339 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1340 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1341 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1342 $msg_text = unxmlify($mesg->text);
1343 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1345 // "diaspora_handle" is the element name from the old version
1346 // "author" is the element name from the new version
1347 if ($mesg->author) {
1348 $msg_author = notags(unxmlify($mesg->author));
1349 } elseif ($mesg->diaspora_handle) {
1350 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1355 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1357 if ($msg_conversation_guid != $guid) {
1358 logger("message conversation guid does not belong to the current conversation.");
1362 $body = diaspora2bb($msg_text);
1363 $message_uri = $msg_author.":".$msg_guid;
1365 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1367 $author_signature = base64_decode($msg_author_signature);
1369 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1373 $person = self::person_by_handle($msg_author);
1375 if (is_array($person) && x($person, "pubkey")) {
1376 $key = $person["pubkey"];
1378 logger("unable to find author details");
1383 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1384 logger("verification failed.");
1388 if ($msg_parent_author_signature) {
1389 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1391 $parent_author_signature = base64_decode($msg_parent_author_signature);
1395 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1396 logger("owner verification failed.");
1401 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1404 if (dbm::is_result($r)) {
1405 logger("duplicate message already delivered.", LOGGER_DEBUG);
1409 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1410 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1411 intval($importer["uid"]),
1413 intval($conversation["id"]),
1414 dbesc($person["name"]),
1415 dbesc($person["photo"]),
1416 dbesc($person["url"]),
1417 intval($contact["id"]),
1422 dbesc($message_uri),
1423 dbesc($author.":".$guid),
1424 dbesc($msg_created_at)
1427 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1428 dbesc(datetime_convert()),
1429 intval($conversation["id"])
1433 "type" => NOTIFY_MAIL,
1434 "notify_flags" => $importer["notify-flags"],
1435 "language" => $importer["language"],
1436 "to_name" => $importer["username"],
1437 "to_email" => $importer["email"],
1438 "uid" =>$importer["uid"],
1439 "item" => array("subject" => $subject, "body" => $body),
1440 "source_name" => $person["name"],
1441 "source_link" => $person["url"],
1442 "source_photo" => $person["thumb"],
1443 "verb" => ACTIVITY_POST,
1450 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1452 * @param array $importer Array of the importer user
1453 * @param array $msg Array of the processed message, author handle and key
1454 * @param object $data The message object
1456 * @return bool Success
1458 private static function receive_conversation($importer, $msg, $data) {
1459 $guid = notags(unxmlify($data->guid));
1460 $subject = notags(unxmlify($data->subject));
1461 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1462 $author = notags(unxmlify($data->author));
1463 $participants = notags(unxmlify($data->participants));
1465 $messages = $data->message;
1467 if (!count($messages)) {
1468 logger("empty conversation");
1472 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1476 $conversation = null;
1478 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1479 intval($importer["uid"]),
1483 $conversation = $c[0];
1485 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1486 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1487 intval($importer["uid"]),
1491 dbesc(datetime_convert()),
1493 dbesc($participants)
1496 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1497 intval($importer["uid"]),
1502 $conversation = $c[0];
1504 if (!$conversation) {
1505 logger("unable to create conversation.");
1509 foreach($messages as $mesg)
1510 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1516 * @brief Creates the body for a "like" message
1518 * @param array $contact The contact that send us the "like"
1519 * @param array $parent_item The item array of the parent item
1520 * @param string $guid message guid
1522 * @return string the body
1524 private static function construct_like_body($contact, $parent_item, $guid) {
1525 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1527 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1528 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1529 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1531 return sprintf($bodyverb, $ulink, $alink, $plink);
1535 * @brief Creates a XML object for a "like"
1537 * @param array $importer Array of the importer user
1538 * @param array $parent_item The item array of the parent item
1540 * @return string The XML
1542 private static function construct_like_object($importer, $parent_item) {
1543 $objtype = ACTIVITY_OBJ_NOTE;
1544 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1545 $parent_body = $parent_item["body"];
1547 $xmldata = array("object" => array("type" => $objtype,
1549 "id" => $parent_item["uri"],
1552 "content" => $parent_body));
1554 return xml::from_array($xmldata, $xml, true);
1558 * @brief Processes "like" messages
1560 * @param array $importer Array of the importer user
1561 * @param string $sender The sender of the message
1562 * @param object $data The message object
1564 * @return int The message id of the generated like or "false" if there was an error
1566 private static function receive_like($importer, $sender, $data) {
1567 $positive = notags(unxmlify($data->positive));
1568 $guid = notags(unxmlify($data->guid));
1569 $parent_type = notags(unxmlify($data->parent_type));
1570 $parent_guid = notags(unxmlify($data->parent_guid));
1571 $author = notags(unxmlify($data->author));
1573 // likes on comments aren't supported by Diaspora - only on posts
1574 // But maybe this will be supported in the future, so we will accept it.
1575 if (!in_array($parent_type, array("Post", "Comment")))
1578 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1582 $message_id = self::message_exists($importer["uid"], $guid);
1586 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1590 $person = self::person_by_handle($author);
1591 if (!is_array($person)) {
1592 logger("unable to find author details");
1596 // Fetch the contact id - if we know this contact
1597 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1599 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1600 // We would accept this anyhow.
1601 if ($positive == "true")
1602 $verb = ACTIVITY_LIKE;
1604 $verb = ACTIVITY_DISLIKE;
1606 $datarray = array();
1608 $datarray["uid"] = $importer["uid"];
1609 $datarray["contact-id"] = $author_contact["cid"];
1610 $datarray["network"] = $author_contact["network"];
1612 $datarray["author-name"] = $person["name"];
1613 $datarray["author-link"] = $person["url"];
1614 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1616 $datarray["owner-name"] = $contact["name"];
1617 $datarray["owner-link"] = $contact["url"];
1618 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1620 $datarray["guid"] = $guid;
1621 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1623 $datarray["type"] = "activity";
1624 $datarray["verb"] = $verb;
1625 $datarray["gravity"] = GRAVITY_LIKE;
1626 $datarray["parent-uri"] = $parent_item["uri"];
1628 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1629 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1631 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1633 $message_id = item_store($datarray);
1636 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1638 // If we are the origin of the parent we store the original data and notify our followers
1639 if($message_id AND $parent_item["origin"]) {
1641 // Formerly we stored the signed text, the signature and the author in different fields.
1642 // We now store the raw data so that we are more flexible.
1643 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1644 intval($message_id),
1645 dbesc(json_encode($data))
1649 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1656 * @brief Processes private messages
1658 * @param array $importer Array of the importer user
1659 * @param object $data The message object
1661 * @return bool Success?
1663 private static function receive_message($importer, $data) {
1664 $guid = notags(unxmlify($data->guid));
1665 $parent_guid = notags(unxmlify($data->parent_guid));
1666 $text = unxmlify($data->text);
1667 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1668 $author = notags(unxmlify($data->author));
1669 $conversation_guid = notags(unxmlify($data->conversation_guid));
1671 $contact = self::allowed_contact_by_handle($importer, $author, true);
1676 $conversation = null;
1678 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1679 intval($importer["uid"]),
1680 dbesc($conversation_guid)
1683 $conversation = $c[0];
1685 logger("conversation not available.");
1689 $message_uri = $author.":".$guid;
1691 $person = self::person_by_handle($author);
1693 logger("unable to find author details");
1697 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1698 dbesc($message_uri),
1699 intval($importer["uid"])
1701 if (dbm::is_result($r)) {
1702 logger("duplicate message already delivered.", LOGGER_DEBUG);
1706 $body = diaspora2bb($text);
1708 $body = self::replace_people_guid($body, $person["url"]);
1710 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1711 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1712 intval($importer["uid"]),
1714 intval($conversation["id"]),
1715 dbesc($person["name"]),
1716 dbesc($person["photo"]),
1717 dbesc($person["url"]),
1718 intval($contact["id"]),
1719 dbesc($conversation["subject"]),
1723 dbesc($message_uri),
1724 dbesc($author.":".$parent_guid),
1728 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1729 dbesc(datetime_convert()),
1730 intval($conversation["id"])
1737 * @brief Processes participations - unsupported by now
1739 * @param array $importer Array of the importer user
1740 * @param object $data The message object
1742 * @return bool always true
1744 private static function receive_participation($importer, $data) {
1745 // I'm not sure if we can fully support this message type
1750 * @brief Processes photos - unneeded
1752 * @param array $importer Array of the importer user
1753 * @param object $data The message object
1755 * @return bool always true
1757 private static function receive_photo($importer, $data) {
1758 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1763 * @brief Processes poll participations - unssupported
1765 * @param array $importer Array of the importer user
1766 * @param object $data The message object
1768 * @return bool always true
1770 private static function receive_poll_participation($importer, $data) {
1771 // We don't support polls by now
1776 * @brief Processes incoming profile updates
1778 * @param array $importer Array of the importer user
1779 * @param object $data The message object
1781 * @return bool Success
1783 private static function receive_profile($importer, $data) {
1784 $author = strtolower(notags(unxmlify($data->author)));
1786 $contact = self::contact_by_handle($importer["uid"], $author);
1790 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1791 $image_url = unxmlify($data->image_url);
1792 $birthday = unxmlify($data->birthday);
1793 $location = diaspora2bb(unxmlify($data->location));
1794 $about = diaspora2bb(unxmlify($data->bio));
1795 $gender = unxmlify($data->gender);
1796 $searchable = (unxmlify($data->searchable) == "true");
1797 $nsfw = (unxmlify($data->nsfw) == "true");
1798 $tags = unxmlify($data->tag_string);
1800 $tags = explode("#", $tags);
1802 $keywords = array();
1803 foreach ($tags as $tag) {
1804 $tag = trim(strtolower($tag));
1809 $keywords = implode(", ", $keywords);
1811 $handle_parts = explode("@", $author);
1812 $nick = $handle_parts[0];
1815 $name = $handle_parts[0];
1817 if( preg_match("|^https?://|", $image_url) === 0)
1818 $image_url = "http://".$handle_parts[1].$image_url;
1820 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1822 // Generic birthday. We don't know the timezone. The year is irrelevant.
1824 $birthday = str_replace("1000", "1901", $birthday);
1826 if ($birthday != "")
1827 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1829 // this is to prevent multiple birthday notifications in a single year
1830 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1832 if(substr($birthday,5) === substr($contact["bd"],5))
1833 $birthday = $contact["bd"];
1835 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1836 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1840 dbesc(datetime_convert()),
1846 intval($contact["id"]),
1847 intval($importer["uid"])
1851 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1852 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1855 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1856 "photo" => $image_url, "name" => $name, "location" => $location,
1857 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1858 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1859 "hide" => !$searchable, "nsfw" => $nsfw);
1861 update_gcontact($gcontact);
1863 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1869 * @brief Processes incoming friend requests
1871 * @param array $importer Array of the importer user
1872 * @param array $contact The contact that send the request
1874 private static function receive_request_make_friend($importer, $contact) {
1878 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1879 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1880 intval(CONTACT_IS_FRIEND),
1881 intval($contact["id"]),
1882 intval($importer["uid"])
1885 // send notification
1887 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1888 intval($importer["uid"])
1891 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1893 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1894 intval($importer["uid"])
1897 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1899 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1902 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1903 $arr["uid"] = $importer["uid"];
1904 $arr["contact-id"] = $self[0]["id"];
1906 $arr["type"] = 'wall';
1907 $arr["gravity"] = 0;
1909 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1910 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1911 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1912 $arr["verb"] = ACTIVITY_FRIEND;
1913 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1915 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1916 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1917 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1918 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1920 $arr["object"] = self::construct_new_friend_object($contact);
1922 $arr["last-child"] = 1;
1924 $arr["allow_cid"] = $user[0]["allow_cid"];
1925 $arr["allow_gid"] = $user[0]["allow_gid"];
1926 $arr["deny_cid"] = $user[0]["deny_cid"];
1927 $arr["deny_gid"] = $user[0]["deny_gid"];
1929 $i = item_store($arr);
1931 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
1937 * @brief Creates a XML object for a "new friend" message
1939 * @param array $contact Array of the contact
1941 * @return string The XML
1943 private static function construct_new_friend_object($contact) {
1944 $objtype = ACTIVITY_OBJ_PERSON;
1945 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1946 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1948 $xmldata = array("object" => array("type" => $objtype,
1949 "title" => $contact["name"],
1950 "id" => $contact["url"]."/".$contact["name"],
1953 return xml::from_array($xmldata, $xml, true);
1957 * @brief Processes incoming sharing notification
1959 * @param array $importer Array of the importer user
1960 * @param object $data The message object
1962 * @return bool Success
1964 private static function receive_contact_request($importer, $data) {
1965 $author = unxmlify($data->author);
1966 $recipient = unxmlify($data->recipient);
1968 if (!$author || !$recipient) {
1972 // the current protocol version doesn't know these fields
1973 // That means that we will assume their existance
1974 if (isset($data->following)) {
1975 $following = (unxmlify($data->following) == "true");
1980 if (isset($data->sharing)) {
1981 $sharing = (unxmlify($data->sharing) == "true");
1986 $contact = self::contact_by_handle($importer["uid"],$author);
1988 // perhaps we were already sharing with this person. Now they're sharing with us.
1989 // That makes us friends.
1991 if ($following AND $sharing) {
1992 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
1993 self::receive_request_make_friend($importer, $contact);
1995 // refetch the contact array
1996 $contact = self::contact_by_handle($importer["uid"],$author);
1998 // If we are now friends, we are sending a share message.
1999 // Normally we needn't to do so, but the first message could have been vanished.
2000 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
2001 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2003 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2004 $ret = self::send_share($u[0], $contact);
2008 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2009 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2014 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2015 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2017 } elseif (!$following AND !$sharing) {
2018 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2020 } elseif (!$following AND $sharing) {
2021 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2022 } elseif ($following AND $sharing) {
2023 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2024 } elseif ($following AND !$sharing) {
2025 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2028 $ret = self::person_by_handle($author);
2030 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2031 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2035 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2037 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2038 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2039 intval($importer["uid"]),
2040 dbesc($ret["network"]),
2041 dbesc($ret["addr"]),
2044 dbesc(normalise_link($ret["url"])),
2046 dbesc($ret["name"]),
2047 dbesc($ret["nick"]),
2048 dbesc($ret["photo"]),
2049 dbesc($ret["pubkey"]),
2050 dbesc($ret["notify"]),
2051 dbesc($ret["poll"]),
2056 // find the contact record we just created
2058 $contact_record = self::contact_by_handle($importer["uid"],$author);
2060 if (!$contact_record) {
2061 logger("unable to locate newly created contact record.");
2065 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2067 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2069 if(intval($def_gid))
2070 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2072 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2074 if($importer["page-flags"] == PAGE_NORMAL) {
2076 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2078 $hash = random_string().(string)time(); // Generate a confirm_key
2080 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2081 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2082 intval($importer["uid"]),
2083 intval($contact_record["id"]),
2086 dbesc(t("Sharing notification from Diaspora network")),
2088 dbesc(datetime_convert())
2092 // automatic friend approval
2094 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2096 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2098 // technically they are sharing with us (CONTACT_IS_SHARING),
2099 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2100 // we are going to change the relationship and make them a follower.
2102 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2103 $new_relation = CONTACT_IS_FRIEND;
2104 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2105 $new_relation = CONTACT_IS_SHARING;
2107 $new_relation = CONTACT_IS_FOLLOWER;
2109 $r = q("UPDATE `contact` SET `rel` = %d,
2117 intval($new_relation),
2118 dbesc(datetime_convert()),
2119 dbesc(datetime_convert()),
2120 intval($contact_record["id"])
2123 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2125 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2126 $ret = self::send_share($u[0], $contact_record);
2128 // Send the profile data, maybe it weren't transmitted before
2129 self::send_profile($importer["uid"], array($contact_record));
2137 * @brief Fetches a message with a given guid
2139 * @param string $guid message guid
2140 * @param string $orig_author handle of the original post
2141 * @param string $author handle of the sharer
2143 * @return array The fetched item
2145 private static function original_item($guid, $orig_author, $author) {
2147 // Do we already have this item?
2148 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2149 `author-name`, `author-link`, `author-avatar`
2150 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2153 if (dbm::is_result($r)) {
2154 logger("reshared message ".$guid." already exists on system.");
2156 // Maybe it is already a reshared item?
2157 // Then refetch the content, if it is a reshare from a reshare.
2158 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2159 if (self::is_reshare($r[0]["body"], true)) {
2161 } elseif (self::is_reshare($r[0]["body"], false)) {
2162 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2164 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2166 // Add OEmbed and other information to the body
2167 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2175 if (!dbm::is_result($r)) {
2176 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2177 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2178 $item_id = self::store_by_guid($guid, $server);
2181 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2182 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2183 $item_id = self::store_by_guid($guid, $server);
2187 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2188 `author-name`, `author-link`, `author-avatar`
2189 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2192 if (dbm::is_result($r)) {
2193 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2194 if (self::is_reshare($r[0]["body"], false)) {
2195 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2196 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2208 * @brief Processes a reshare message
2210 * @param array $importer Array of the importer user
2211 * @param object $data The message object
2212 * @param string $xml The original XML of the message
2214 * @return int the message id
2216 private static function receive_reshare($importer, $data, $xml) {
2217 $root_author = notags(unxmlify($data->root_author));
2218 $root_guid = notags(unxmlify($data->root_guid));
2219 $guid = notags(unxmlify($data->guid));
2220 $author = notags(unxmlify($data->author));
2221 $public = notags(unxmlify($data->public));
2222 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2224 $contact = self::allowed_contact_by_handle($importer, $author, false);
2229 $message_id = self::message_exists($importer["uid"], $guid);
2234 $original_item = self::original_item($root_guid, $root_author, $author);
2235 if (!$original_item) {
2239 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2241 $datarray = array();
2243 $datarray["uid"] = $importer["uid"];
2244 $datarray["contact-id"] = $contact["id"];
2245 $datarray["network"] = NETWORK_DIASPORA;
2247 $datarray["author-name"] = $contact["name"];
2248 $datarray["author-link"] = $contact["url"];
2249 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2251 $datarray["owner-name"] = $datarray["author-name"];
2252 $datarray["owner-link"] = $datarray["author-link"];
2253 $datarray["owner-avatar"] = $datarray["author-avatar"];
2255 $datarray["guid"] = $guid;
2256 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2258 $datarray["verb"] = ACTIVITY_POST;
2259 $datarray["gravity"] = GRAVITY_PARENT;
2261 $datarray["object"] = $xml;
2263 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2264 $original_item["guid"], $original_item["created"], $orig_url);
2265 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2267 $datarray["tag"] = $original_item["tag"];
2268 $datarray["app"] = $original_item["app"];
2270 $datarray["plink"] = self::plink($author, $guid);
2271 $datarray["private"] = (($public == "false") ? 1 : 0);
2272 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2274 $datarray["object-type"] = $original_item["object-type"];
2276 self::fetch_guid($datarray);
2277 $message_id = item_store($datarray);
2280 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2287 * @brief Processes retractions
2289 * @param array $importer Array of the importer user
2290 * @param array $contact The contact of the item owner
2291 * @param object $data The message object
2293 * @return bool success
2295 private static function item_retraction($importer, $contact, $data) {
2296 $target_type = notags(unxmlify($data->target_type));
2297 $target_guid = notags(unxmlify($data->target_guid));
2298 $author = notags(unxmlify($data->author));
2300 $person = self::person_by_handle($author);
2301 if (!is_array($person)) {
2302 logger("unable to find author detail for ".$author);
2306 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2307 dbesc($target_guid),
2308 intval($importer["uid"])
2314 // Check if the sender is the thread owner
2315 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2316 intval($r[0]["parent"]));
2318 // Only delete it if the parent author really fits
2319 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2320 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2324 // 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
2325 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2326 dbesc(datetime_convert()),
2327 dbesc(datetime_convert()),
2330 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2332 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2334 // Now check if the retraction needs to be relayed by us
2335 if ($p[0]["origin"]) {
2337 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2344 * @brief Receives retraction messages
2346 * @param array $importer Array of the importer user
2347 * @param string $sender The sender of the message
2348 * @param object $data The message object
2350 * @return bool Success
2352 private static function receive_retraction($importer, $sender, $data) {
2353 $target_type = notags(unxmlify($data->target_type));
2355 $contact = self::contact_by_handle($importer["uid"], $sender);
2357 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2361 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2363 switch ($target_type) {
2366 case "Post": // "Post" will be supported in a future version
2368 case "StatusMessage":
2369 return self::item_retraction($importer, $contact, $data);;
2373 /// @todo What should we do with an "unshare"?
2374 // Removing the contact isn't correct since we still can read the public items
2375 contact_remove($contact["id"]);
2379 logger("Unknown target type ".$target_type);
2386 * @brief Receives status messages
2388 * @param array $importer Array of the importer user
2389 * @param object $data The message object
2390 * @param string $xml The original XML of the message
2392 * @return int The message id of the newly created item
2394 private static function receive_status_message($importer, $data, $xml) {
2395 $raw_message = unxmlify($data->raw_message);
2396 $guid = notags(unxmlify($data->guid));
2397 $author = notags(unxmlify($data->author));
2398 $public = notags(unxmlify($data->public));
2399 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2400 $provider_display_name = notags(unxmlify($data->provider_display_name));
2402 /// @todo enable support for polls
2403 //if ($data->poll) {
2404 // foreach ($data->poll AS $poll)
2408 $contact = self::allowed_contact_by_handle($importer, $author, false);
2413 $message_id = self::message_exists($importer["uid"], $guid);
2419 if ($data->location) {
2420 foreach ($data->location->children() AS $fieldname => $data) {
2421 $address[$fieldname] = notags(unxmlify($data));
2425 $body = diaspora2bb($raw_message);
2427 $datarray = array();
2429 // Attach embedded pictures to the body
2431 foreach ($data->photo AS $photo) {
2432 $body = "[img]".unxmlify($photo->remote_photo_path).
2433 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2436 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2438 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2440 // Add OEmbed and other information to the body
2441 if (!self::is_redmatrix($contact["url"])) {
2442 $body = add_page_info_to_body($body, false, true);
2446 $datarray["uid"] = $importer["uid"];
2447 $datarray["contact-id"] = $contact["id"];
2448 $datarray["network"] = NETWORK_DIASPORA;
2450 $datarray["author-name"] = $contact["name"];
2451 $datarray["author-link"] = $contact["url"];
2452 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2454 $datarray["owner-name"] = $datarray["author-name"];
2455 $datarray["owner-link"] = $datarray["author-link"];
2456 $datarray["owner-avatar"] = $datarray["author-avatar"];
2458 $datarray["guid"] = $guid;
2459 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2461 $datarray["verb"] = ACTIVITY_POST;
2462 $datarray["gravity"] = GRAVITY_PARENT;
2464 $datarray["object"] = $xml;
2466 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2468 if ($provider_display_name != "") {
2469 $datarray["app"] = $provider_display_name;
2472 $datarray["plink"] = self::plink($author, $guid);
2473 $datarray["private"] = (($public == "false") ? 1 : 0);
2474 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2476 if (isset($address["address"])) {
2477 $datarray["location"] = $address["address"];
2480 if (isset($address["lat"]) AND isset($address["lng"])) {
2481 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2484 self::fetch_guid($datarray);
2485 $message_id = item_store($datarray);
2488 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2494 /* ************************************************************************************** *
2495 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2496 * ************************************************************************************** */
2499 * @brief returnes the handle of a contact
2501 * @param array $me contact array
2503 * @return string the handle in the format user@domain.tld
2505 private static function my_handle($contact) {
2506 if ($contact["addr"] != "") {
2507 return $contact["addr"];
2510 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2511 // So - just in case - we build the the address here.
2512 if ($contact["nickname"] != "") {
2513 $nick = $contact["nickname"];
2515 $nick = $contact["nick"];
2518 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2522 * @brief Creates the envelope for the "fetch" endpoint
2524 * @param string $msg The message that is to be transmitted
2525 * @param array $user The record of the sender
2527 * @return string The envelope
2530 public static function build_magic_envelope($msg, $user) {
2532 $b64url_data = base64url_encode($msg);
2533 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2535 $key_id = base64url_encode(self::my_handle($user));
2536 $type = "application/xml";
2537 $encoding = "base64url";
2538 $alg = "RSA-SHA256";
2539 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2540 $signature = rsa_sign($signable_data, $user["prvkey"]);
2541 $sig = base64url_encode($signature);
2543 $xmldata = array("me:env" => array("me:data" => $data,
2544 "@attributes" => array("type" => $type),
2545 "me:encoding" => $encoding,
2548 "@attributes2" => array("key_id" => $key_id)));
2550 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2552 return xml::from_array($xmldata, $xml, false, $namespaces);
2556 * @brief Creates the envelope for a public message
2558 * @param string $msg The message that is to be transmitted
2559 * @param array $user The record of the sender
2560 * @param array $contact Target of the communication
2561 * @param string $prvkey The private key of the sender
2562 * @param string $pubkey The public key of the receiver
2564 * @return string The envelope
2566 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2568 logger("Message: ".$msg, LOGGER_DATA);
2570 $handle = self::my_handle($user);
2572 $b64url_data = base64url_encode($msg);
2574 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2576 $type = "application/xml";
2577 $encoding = "base64url";
2578 $alg = "RSA-SHA256";
2580 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2582 $signature = rsa_sign($signable_data,$prvkey);
2583 $sig = base64url_encode($signature);
2585 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2586 "me:env" => array("me:encoding" => $encoding,
2589 "@attributes" => array("type" => $type),
2590 "me:sig" => $sig)));
2592 $namespaces = array("" => "https://joindiaspora.com/protocol",
2593 "me" => "http://salmon-protocol.org/ns/magic-env");
2595 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2597 logger("magic_env: ".$magic_env, LOGGER_DATA);
2602 * @brief Creates the envelope for a private message
2604 * @param string $msg The message that is to be transmitted
2605 * @param array $user The record of the sender
2606 * @param array $contact Target of the communication
2607 * @param string $prvkey The private key of the sender
2608 * @param string $pubkey The public key of the receiver
2610 * @return string The envelope
2612 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2614 logger("Message: ".$msg, LOGGER_DATA);
2616 // without a public key nothing will work
2619 logger("pubkey missing: contact id: ".$contact["id"]);
2623 $inner_aes_key = random_string(32);
2624 $b_inner_aes_key = base64_encode($inner_aes_key);
2625 $inner_iv = random_string(16);
2626 $b_inner_iv = base64_encode($inner_iv);
2628 $outer_aes_key = random_string(32);
2629 $b_outer_aes_key = base64_encode($outer_aes_key);
2630 $outer_iv = random_string(16);
2631 $b_outer_iv = base64_encode($outer_iv);
2633 $handle = self::my_handle($user);
2635 $padded_data = pkcs5_pad($msg,16);
2636 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2638 $b64_data = base64_encode($inner_encrypted);
2641 $b64url_data = base64url_encode($b64_data);
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("decrypted_header" => array("iv" => $b_inner_iv,
2654 "aes_key" => $b_inner_aes_key,
2655 "author_id" => $handle));
2657 $decrypted_header = xml::from_array($xmldata, $xml, true);
2658 $decrypted_header = pkcs5_pad($decrypted_header,16);
2660 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2662 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2664 $encrypted_outer_key_bundle = "";
2665 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2667 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2669 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2671 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2672 "ciphertext" => base64_encode($ciphertext)));
2673 $cipher_json = base64_encode($encrypted_header_json_object);
2675 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2676 "me:env" => array("me:encoding" => $encoding,
2679 "@attributes" => array("type" => $type),
2680 "me:sig" => $sig)));
2682 $namespaces = array("" => "https://joindiaspora.com/protocol",
2683 "me" => "http://salmon-protocol.org/ns/magic-env");
2685 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2687 logger("magic_env: ".$magic_env, LOGGER_DATA);
2692 * @brief Create the envelope for a message
2694 * @param string $msg The message that is to be transmitted
2695 * @param array $user The record of the sender
2696 * @param array $contact Target of the communication
2697 * @param string $prvkey The private key of the sender
2698 * @param string $pubkey The public key of the receiver
2699 * @param bool $public Is the message public?
2701 * @return string The message that will be transmitted to other servers
2703 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2706 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2708 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2710 // The data that will be transmitted is double encoded via "urlencode", strange ...
2711 $slap = "xml=".urlencode(urlencode($magic_env));
2716 * @brief Creates a signature for a message
2718 * @param array $owner the array of the owner of the message
2719 * @param array $message The message that is to be signed
2721 * @return string The signature
2723 private static function signature($owner, $message) {
2725 unset($sigmsg["author_signature"]);
2726 unset($sigmsg["parent_author_signature"]);
2728 $signed_text = implode(";", $sigmsg);
2730 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2734 * @brief Transmit a message to a target server
2736 * @param array $owner the array of the item owner
2737 * @param array $contact Target of the communication
2738 * @param string $slap The message that is to be transmitted
2739 * @param bool $public_batch Is it a public post?
2740 * @param bool $queue_run Is the transmission called from the queue?
2741 * @param string $guid message guid
2743 * @return int Result of the transmission
2745 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2749 $enabled = intval(get_config("system", "diaspora_enabled"));
2753 $logid = random_string(4);
2754 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2756 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2760 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2762 if (!$queue_run && was_recently_delayed($contact["id"])) {
2765 if (!intval(get_config("system", "diaspora_test"))) {
2766 post_url($dest_url."/", $slap);
2767 $return_code = $a->get_curl_code();
2769 logger("test_mode");
2774 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2776 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2777 logger("queue message");
2779 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2780 intval($contact["id"]),
2781 dbesc(NETWORK_DIASPORA),
2783 intval($public_batch)
2786 logger("add_to_queue ignored - identical item already in queue");
2788 // queue message for redelivery
2789 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2791 // The message could not be delivered. We mark the contact as "dead"
2792 mark_for_death($contact);
2794 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2795 // We successfully delivered a message, the contact is alive
2796 unmark_for_death($contact);
2799 return(($return_code) ? $return_code : (-1));
2804 * @brief Build the post xml
2806 * @param string $type The message type
2807 * @param array $message The message data
2809 * @return string The post XML
2811 public static function build_post_xml($type, $message) {
2813 $data = array("XML" => array("post" => array($type => $message)));
2814 return xml::from_array($data, $xml);
2818 * @brief Builds and transmit messages
2820 * @param array $owner the array of the item owner
2821 * @param array $contact Target of the communication
2822 * @param string $type The message type
2823 * @param array $message The message data
2824 * @param bool $public_batch Is it a public post?
2825 * @param string $guid message guid
2826 * @param bool $spool Should the transmission be spooled or transmitted?
2828 * @return int Result of the transmission
2830 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2832 $msg = self::build_post_xml($type, $message);
2834 logger('message: '.$msg, LOGGER_DATA);
2835 logger('send guid '.$guid, LOGGER_DEBUG);
2837 // Fallback if the private key wasn't transmitted in the expected field
2838 if ($owner['uprvkey'] == "")
2839 $owner['uprvkey'] = $owner['prvkey'];
2841 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2844 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2847 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2849 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2851 return $return_code;
2855 * @brief Sends a "share" message
2857 * @param array $owner the array of the item owner
2858 * @param array $contact Target of the communication
2860 * @return int The result of the transmission
2862 public static function send_share($owner,$contact) {
2864 $message = array("sender_handle" => self::my_handle($owner),
2865 "recipient_handle" => $contact["addr"]);
2867 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2869 return self::build_and_transmit($owner, $contact, "request", $message);
2873 * @brief sends an "unshare"
2875 * @param array $owner the array of the item owner
2876 * @param array $contact Target of the communication
2878 * @return int The result of the transmission
2880 public static function send_unshare($owner,$contact) {
2882 $message = array("post_guid" => $owner["guid"],
2883 "diaspora_handle" => self::my_handle($owner),
2884 "type" => "Person");
2886 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2888 return self::build_and_transmit($owner, $contact, "retraction", $message);
2892 * @brief Checks a message body if it is a reshare
2894 * @param string $body The message body that is to be check
2895 * @param bool $complete Should it be a complete check or a simple check?
2897 * @return array|bool Reshare details or "false" if no reshare
2899 public static function is_reshare($body, $complete = true) {
2900 $body = trim($body);
2902 // Skip if it isn't a pure repeated messages
2903 // Does it start with a share?
2904 if ((strpos($body, "[share") > 0) AND $complete)
2907 // Does it end with a share?
2908 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2911 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2912 // Skip if there is no shared message in there
2913 if ($body == $attributes)
2916 // If we don't do the complete check we quit here
2921 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2922 if ($matches[1] != "")
2923 $guid = $matches[1];
2925 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2926 if ($matches[1] != "")
2927 $guid = $matches[1];
2930 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2931 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2934 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2935 $ret["root_guid"] = $guid;
2941 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2942 if ($matches[1] != "")
2943 $profile = $matches[1];
2945 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2946 if ($matches[1] != "")
2947 $profile = $matches[1];
2951 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2952 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2956 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2957 if ($matches[1] != "")
2958 $link = $matches[1];
2960 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2961 if ($matches[1] != "")
2962 $link = $matches[1];
2964 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2965 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2972 * @brief Create an event array
2974 * @param integer $event_id The id of the event
2976 * @return array with event data
2978 private static function build_event($event_id) {
2980 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
2981 if (!dbm::is_result($r)) {
2987 $eventdata = array();
2989 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
2990 if (!dbm::is_result($r)) {
2996 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
2997 if (!dbm::is_result($r)) {
3003 $eventdata['author'] = self::my_handle($owner);
3005 if ($event['guid']) {
3006 $eventdata['guid'] = $event['guid'];
3009 $mask = 'Y-m-d\TH:i:s\Z';
3011 /// @todo - establish "all day" events in Friendica
3012 $eventdata["all_day"] = "false";
3014 if (!$event['adjust']) {
3015 $eventdata['timezone'] = $user['timezone'];
3017 if ($eventdata['timezone'] == "") {
3018 $eventdata['timezone'] = 'UTC';
3022 if ($event['start']) {
3023 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3025 if ($event['finish'] AND !$event['nofinish']) {
3026 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3028 if ($event['summary']) {
3029 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3031 if ($event['desc']) {
3032 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3034 if ($event['location']) {
3035 $location = array();
3036 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3037 $location["lat"] = 0;
3038 $location["lng"] = 0;
3039 $eventdata['location'] = $location;
3046 * @brief Create a post (status message or reshare)
3048 * @param array $item The item that will be exported
3049 * @param array $owner the array of the item owner
3052 * 'type' -> Message type ("status_message" or "reshare")
3053 * 'message' -> Array of XML elements of the status
3055 public static function build_status($item, $owner) {
3057 $cachekey = "diaspora:build_status:".$item['guid'];
3059 $result = Cache::get($cachekey);
3060 if (!is_null($result)) {
3064 $myaddr = self::my_handle($owner);
3066 $public = (($item["private"]) ? "false" : "true");
3068 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3070 // Detect a share element and do a reshare
3071 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3072 $message = array("root_diaspora_id" => $ret["root_handle"],
3073 "root_guid" => $ret["root_guid"],
3074 "guid" => $item["guid"],
3075 "diaspora_handle" => $myaddr,
3076 "public" => $public,
3077 "created_at" => $created,
3078 "provider_display_name" => $item["app"]);
3082 $title = $item["title"];
3083 $body = $item["body"];
3085 // convert to markdown
3086 $body = html_entity_decode(bb2diaspora($body));
3090 $body = "## ".html_entity_decode($title)."\n\n".$body;
3092 if ($item["attach"]) {
3093 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3095 $body .= "\n".t("Attachments:")."\n";
3096 foreach($matches as $mtch)
3097 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3101 $location = array();
3103 if ($item["location"] != "")
3104 $location["address"] = $item["location"];
3106 if ($item["coord"] != "") {
3107 $coord = explode(" ", $item["coord"]);
3108 $location["lat"] = $coord[0];
3109 $location["lng"] = $coord[1];
3112 $message = array("raw_message" => $body,
3113 "location" => $location,
3114 "guid" => $item["guid"],
3115 "diaspora_handle" => $myaddr,
3116 "public" => $public,
3117 "created_at" => $created,
3118 "provider_display_name" => $item["app"]);
3120 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3121 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3122 unset($message["location"]);
3125 if ($item['event-id'] > 0) {
3126 $event = self::build_event($item['event-id']);
3127 if (count($event)) {
3128 $message['event'] = $event;
3130 /// @todo Once Diaspora supports it, we will remove the body
3131 // $message['raw_message'] = '';
3135 $type = "status_message";
3138 $msg = array("type" => $type, "message" => $message);
3140 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3146 * @brief Sends a post
3148 * @param array $item The item that will be exported
3149 * @param array $owner the array of the item owner
3150 * @param array $contact Target of the communication
3151 * @param bool $public_batch Is it a public post?
3153 * @return int The result of the transmission
3155 public static function send_status($item, $owner, $contact, $public_batch = false) {
3157 $status = self::build_status($item, $owner);
3159 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3163 * @brief Creates a "like" object
3165 * @param array $item The item that will be exported
3166 * @param array $owner the array of the item owner
3168 * @return array The data for a "like"
3170 private static function construct_like($item, $owner) {
3172 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3173 dbesc($item["thr-parent"]));
3174 if (!dbm::is_result($p))
3179 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3180 if ($item['verb'] === ACTIVITY_LIKE) {
3182 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3183 $positive = "false";
3186 return(array("positive" => $positive,
3187 "guid" => $item["guid"],
3188 "target_type" => $target_type,
3189 "parent_guid" => $parent["guid"],
3190 "author_signature" => "",
3191 "diaspora_handle" => self::my_handle($owner)));
3195 * @brief Creates an "EventParticipation" object
3197 * @param array $item The item that will be exported
3198 * @param array $owner the array of the item owner
3200 * @return array The data for an "EventParticipation"
3202 private static function construct_attend($item, $owner) {
3204 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3205 dbesc($item["thr-parent"]));
3206 if (!dbm::is_result($p))
3211 switch ($item['verb']) {
3212 case ACTIVITY_ATTEND:
3213 $attend_answer = 'accepted';
3215 case ACTIVITY_ATTENDNO:
3216 $attend_answer = 'declined';
3218 case ACTIVITY_ATTENDMAYBE:
3219 $attend_answer = 'tentative';
3222 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3226 return(array("author" => self::my_handle($owner),
3227 "guid" => $item["guid"],
3228 "parent_guid" => $parent["guid"],
3229 "status" => $attend_answer,
3230 "author_signature" => ""));
3234 * @brief Creates the object for a comment
3236 * @param array $item The item that will be exported
3237 * @param array $owner the array of the item owner
3239 * @return array The data for a comment
3241 private static function construct_comment($item, $owner) {
3243 $cachekey = "diaspora:construct_comment:".$item['guid'];
3245 $result = Cache::get($cachekey);
3246 if (!is_null($result)) {
3250 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3251 intval($item["parent"]),
3252 intval($item["parent"])
3255 if (!dbm::is_result($p))
3260 $text = html_entity_decode(bb2diaspora($item["body"]));
3261 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3263 $comment = array("guid" => $item["guid"],
3264 "parent_guid" => $parent["guid"],
3265 "author_signature" => "",
3267 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3268 "diaspora_handle" => self::my_handle($owner));
3270 // Send the thread parent guid only if it is a threaded comment
3271 if ($item['thr-parent'] != $item['parent-uri']) {
3272 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3275 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3281 * @brief Send a like or a comment
3283 * @param array $item The item that will be exported
3284 * @param array $owner the array of the item owner
3285 * @param array $contact Target of the communication
3286 * @param bool $public_batch Is it a public post?
3288 * @return int The result of the transmission
3290 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3292 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3293 $message = self::construct_attend($item, $owner);
3294 $type = "event_participation";
3295 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3296 $message = self::construct_like($item, $owner);
3299 $message = self::construct_comment($item, $owner);
3306 $message["author_signature"] = self::signature($owner, $message);
3308 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3312 * @brief Creates a message from a signature record entry
3314 * @param array $item The item that will be exported
3315 * @param array $signature The entry of the "sign" record
3317 * @return string The message
3319 private static function message_from_signature($item, $signature) {
3321 // Split the signed text
3322 $signed_parts = explode(";", $signature['signed_text']);
3324 if ($item["deleted"])
3325 $message = array("parent_author_signature" => "",
3326 "target_guid" => $signed_parts[0],
3327 "target_type" => $signed_parts[1],
3328 "sender_handle" => $signature['signer'],
3329 "target_author_signature" => $signature['signature']);
3330 elseif ($item['verb'] === ACTIVITY_LIKE)
3331 $message = array("positive" => $signed_parts[0],
3332 "guid" => $signed_parts[1],
3333 "target_type" => $signed_parts[2],
3334 "parent_guid" => $signed_parts[3],
3335 "parent_author_signature" => "",
3336 "author_signature" => $signature['signature'],
3337 "diaspora_handle" => $signed_parts[4]);
3339 // Remove the comment guid
3340 $guid = array_shift($signed_parts);
3342 // Remove the parent guid
3343 $parent_guid = array_shift($signed_parts);
3345 // Remove the handle
3346 $handle = array_pop($signed_parts);
3348 // Glue the parts together
3349 $text = implode(";", $signed_parts);
3351 $message = array("guid" => $guid,
3352 "parent_guid" => $parent_guid,
3353 "parent_author_signature" => "",
3354 "author_signature" => $signature['signature'],
3355 "text" => implode(";", $signed_parts),
3356 "diaspora_handle" => $handle);
3362 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3364 * @param array $item The item that will be exported
3365 * @param array $owner the array of the item owner
3366 * @param array $contact Target of the communication
3367 * @param bool $public_batch Is it a public post?
3369 * @return int The result of the transmission
3371 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3373 if ($item["deleted"])
3374 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3375 elseif ($item['verb'] === ACTIVITY_LIKE)
3380 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3382 // fetch the original signature
3384 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3385 intval($item["id"]));
3388 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3394 // Old way - is used by the internal Friendica functions
3395 /// @todo Change all signatur storing functions to the new format
3396 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3397 $message = self::message_from_signature($item, $signature);
3399 $msg = json_decode($signature['signed_text'], true);
3402 if (is_array($msg)) {
3403 foreach ($msg AS $field => $data) {
3404 if (!$item["deleted"]) {
3405 if ($field == "author")
3406 $field = "diaspora_handle";
3407 if ($field == "parent_type")
3408 $field = "target_type";
3411 $message[$field] = $data;
3414 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3417 $message["parent_author_signature"] = self::signature($owner, $message);
3419 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3421 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3425 * @brief Sends a retraction (deletion) of a message, like or comment
3427 * @param array $item The item that will be exported
3428 * @param array $owner the array of the item owner
3429 * @param array $contact Target of the communication
3430 * @param bool $public_batch Is it a public post?
3431 * @param bool $relay Is the retraction transmitted from a relay?
3433 * @return int The result of the transmission
3435 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3437 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3439 // Check whether the retraction is for a top-level post or whether it's a relayable
3440 if ($item["uri"] !== $item["parent-uri"]) {
3441 $msg_type = "relayable_retraction";
3442 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3444 $msg_type = "signed_retraction";
3445 $target_type = "StatusMessage";
3448 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3449 $signature = "parent_author_signature";
3451 $signature = "target_author_signature";
3453 $signed_text = $item["guid"].";".$target_type;
3455 $message = array("target_guid" => $item['guid'],
3456 "target_type" => $target_type,
3457 "sender_handle" => $itemaddr,
3458 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3460 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3462 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3466 * @brief Sends a mail
3468 * @param array $item The item that will be exported
3469 * @param array $owner The owner
3470 * @param array $contact Target of the communication
3472 * @return int The result of the transmission
3474 public static function send_mail($item, $owner, $contact) {
3476 $myaddr = self::my_handle($owner);
3478 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3479 intval($item["convid"]),
3480 intval($item["uid"])
3483 if (!dbm::is_result($r)) {
3484 logger("conversation not found.");
3490 "guid" => $cnv["guid"],
3491 "subject" => $cnv["subject"],
3492 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3493 "diaspora_handle" => $cnv["creator"],
3494 "participant_handles" => $cnv["recips"]
3497 $body = bb2diaspora($item["body"]);
3498 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3500 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3501 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3504 "guid" => $item["guid"],
3505 "parent_guid" => $cnv["guid"],
3506 "parent_author_signature" => $sig,
3507 "author_signature" => $sig,
3509 "created_at" => $created,
3510 "diaspora_handle" => $myaddr,
3511 "conversation_guid" => $cnv["guid"]
3514 if ($item["reply"]) {
3518 $message = array("guid" => $cnv["guid"],
3519 "subject" => $cnv["subject"],
3520 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3522 "diaspora_handle" => $cnv["creator"],
3523 "participant_handles" => $cnv["recips"]);
3525 $type = "conversation";
3528 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3532 * @brief Sends profile data
3534 * @param int $uid The user id
3536 public static function send_profile($uid, $recips = false) {
3542 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3543 AND `uid` = %d AND `rel` != %d",
3544 dbesc(NETWORK_DIASPORA),
3546 intval(CONTACT_IS_SHARING)
3551 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3553 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3554 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3555 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3564 $handle = $profile["addr"];
3565 $first = ((strpos($profile['name'],' ')
3566 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3567 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3568 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3569 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3570 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3571 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3573 if ($searchable === 'true') {
3574 $dob = '1000-00-00';
3576 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3577 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3579 $about = $profile['about'];
3580 $about = strip_tags(bbcode($about));
3582 $location = formatted_location($profile);
3584 if ($profile['pub_keywords']) {
3585 $kw = str_replace(',',' ',$profile['pub_keywords']);
3586 $kw = str_replace(' ',' ',$kw);
3587 $arr = explode(' ',$profile['pub_keywords']);
3589 for($x = 0; $x < 5; $x ++) {
3591 $tags .= '#'. trim($arr[$x]) .' ';
3595 $tags = trim($tags);
3598 $message = array("diaspora_handle" => $handle,
3599 "first_name" => $first,
3600 "last_name" => $last,
3601 "image_url" => $large,
3602 "image_url_medium" => $medium,
3603 "image_url_small" => $small,
3605 "gender" => $profile['gender'],
3607 "location" => $location,
3608 "searchable" => $searchable,
3609 "tag_string" => $tags);
3611 foreach($recips as $recip) {
3612 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3613 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3618 * @brief Stores the signature for likes that are created on our system
3620 * @param array $contact The contact array of the "like"
3621 * @param int $post_id The post id of the "like"
3623 * @return bool Success
3625 public static function store_like_signature($contact, $post_id) {
3627 // Is the contact the owner? Then fetch the private key
3628 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3629 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3633 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3637 $contact["uprvkey"] = $r[0]['prvkey'];
3639 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3643 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3646 $message = self::construct_like($r[0], $contact);
3647 $message["author_signature"] = self::signature($contact, $message);
3649 // We now store the signature more flexible to dynamically support new fields.
3650 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3651 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3652 intval($message_id),
3653 dbesc(json_encode($message))
3656 logger('Stored diaspora like signature');
3661 * @brief Stores the signature for comments that are created on our system
3663 * @param array $item The item array of the comment
3664 * @param array $contact The contact array of the item owner
3665 * @param string $uprvkey The private key of the sender
3666 * @param int $message_id The message id of the comment
3668 * @return bool Success
3670 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3672 if ($uprvkey == "") {
3673 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3677 $contact["uprvkey"] = $uprvkey;
3679 $message = self::construct_comment($item, $contact);
3680 $message["author_signature"] = self::signature($contact, $message);
3682 // We now store the signature more flexible to dynamically support new fields.
3683 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3684 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3685 intval($message_id),
3686 dbesc(json_encode($message))
3689 logger('Stored diaspora comment signature');