3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * Currently this implementation here interprets the old and the new protocol and sends the old one.
8 * This will change in the future.
11 use \Friendica\Core\Config;
13 require_once 'include/items.php';
14 require_once 'include/bb2diaspora.php';
15 require_once 'include/Scrape.php';
16 require_once 'include/Contact.php';
17 require_once 'include/Photo.php';
18 require_once 'include/socgraph.php';
19 require_once 'include/group.php';
20 require_once 'include/xml.php';
21 require_once 'include/datetime.php';
22 require_once 'include/queue_fn.php';
23 require_once 'include/cache.php';
26 * @brief This class contain functions to create and send Diaspora XML files
32 * @brief Return a list of relay servers
34 * This is an experimental Diaspora feature.
36 * @return array of relay servers
38 public static function relay_list() {
40 $serverdata = get_config("system", "relay_server");
41 if ($serverdata == "")
46 $servers = explode(",", $serverdata);
48 foreach ($servers AS $server) {
49 $server = trim($server);
50 $addr = "relay@".str_replace("http://", "", normalise_link($server));
51 $batch = $server."/receive/public";
53 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
54 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
57 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
58 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
63 dbesc(normalise_link($server)),
65 dbesc(NETWORK_DIASPORA),
66 intval(CONTACT_IS_FOLLOWER),
67 dbesc(datetime_convert()),
68 dbesc(datetime_convert()),
69 dbesc(datetime_convert())
72 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
74 $relay[] = $relais[0];
76 $relay[] = $relais[0];
83 * @brief repairs a signature that was double encoded
85 * The function is unused at the moment. It was copied from the old implementation.
87 * @param string $signature The signature
88 * @param string $handle The handle of the signature owner
89 * @param integer $level This value is only set inside this function to avoid endless loops
91 * @return string the repaired signature
93 private static function repair_signature($signature, $handle = "", $level = 1) {
98 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
99 $signature = base64_decode($signature);
100 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
102 // Do a recursive call to be able to fix even multiple levels
104 $signature = self::repair_signature($signature, $handle, ++$level);
111 * @brief verify the envelope and return the verified data
113 * @param string $envelope The magic envelope
115 * @return string verified data
117 private static function verify_magic_envelope($envelope) {
119 $basedom = parse_xml_string($envelope, false);
121 if (!is_object($basedom)) {
122 logger("Envelope is no XML file");
126 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
128 if (sizeof($children) == 0) {
129 logger("XML has no children");
135 $data = base64url_decode($children->data);
136 $type = $children->data->attributes()->type[0];
138 $encoding = $children->encoding;
140 $alg = $children->alg;
142 $sig = base64url_decode($children->sig);
143 $key_id = $children->sig->attributes()->key_id[0];
145 $handle = base64url_decode($key_id);
147 $b64url_data = base64url_encode($data);
148 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
150 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
152 $key = self::key($handle);
154 $verify = rsa_verify($signable_data, $sig, $key);
156 logger('Message did not verify. Discarding.');
164 * @brief encrypts data via AES
166 * @param string $key The AES key
167 * @param string $iv The IV (is used for CBC encoding)
168 * @param string $data The data that is to be encrypted
170 * @return string encrypted data
172 private static function aes_encrypt($key, $iv, $data) {
173 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
177 * @brief decrypts data via AES
179 * @param string $key The AES key
180 * @param string $iv The IV (is used for CBC encoding)
181 * @param string $encrypted The encrypted data
183 * @return string decrypted data
185 private static function aes_decrypt($key, $iv, $encrypted) {
186 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
190 * @brief: Decodes incoming Diaspora message
192 * @param array $importer Array of the importer user
193 * @param string $xml urldecoded Diaspora salmon
196 * 'message' -> decoded Diaspora XML message
197 * 'author' -> author diaspora handle
198 * 'key' -> author public key (converted to pkcs#8)
200 public static function decode($importer, $xml) {
203 $basedom = parse_xml_string($xml);
205 if (!is_object($basedom))
208 $children = $basedom->children('https://joindiaspora.com/protocol');
210 if ($children->header) {
212 $author_link = str_replace('acct:','',$children->header->author_id);
215 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
217 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
218 $ciphertext = base64_decode($encrypted_header->ciphertext);
220 $outer_key_bundle = '';
221 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
223 $j_outer_key_bundle = json_decode($outer_key_bundle);
225 $outer_iv = base64_decode($j_outer_key_bundle->iv);
226 $outer_key = base64_decode($j_outer_key_bundle->key);
228 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
230 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
231 $idom = parse_xml_string($decrypted,false);
233 $inner_iv = base64_decode($idom->iv);
234 $inner_aes_key = base64_decode($idom->aes_key);
236 $author_link = str_replace('acct:','',$idom->author_id);
239 $dom = $basedom->children(NAMESPACE_SALMON_ME);
241 // figure out where in the DOM tree our data is hiding
243 if ($dom->provenance->data)
244 $base = $dom->provenance;
245 elseif ($dom->env->data)
251 logger('unable to locate salmon data in xml');
252 http_status_exit(400);
256 // Stash the signature away for now. We have to find their key or it won't be good for anything.
257 $signature = base64url_decode($base->sig);
261 // strip whitespace so our data element will return to one big base64 blob
262 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
265 // stash away some other stuff for later
267 $type = $base->data[0]->attributes()->type[0];
268 $keyhash = $base->sig[0]->attributes()->keyhash[0];
269 $encoding = $base->encoding;
273 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
277 $data = base64url_decode($data);
281 $inner_decrypted = $data;
284 // Decode the encrypted blob
286 $inner_encrypted = base64_decode($data);
287 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
291 logger('Could not retrieve author URI.');
292 http_status_exit(400);
294 // Once we have the author URI, go to the web and try to find their public key
295 // (first this will look it up locally if it is in the fcontact cache)
296 // This will also convert diaspora public key from pkcs#1 to pkcs#8
298 logger('Fetching key for '.$author_link);
299 $key = self::key($author_link);
302 logger('Could not retrieve author key.');
303 http_status_exit(400);
306 $verify = rsa_verify($signed_data,$signature,$key);
309 logger('Message did not verify. Discarding.');
310 http_status_exit(400);
313 logger('Message verified.');
315 return array('message' => (string)$inner_decrypted,
316 'author' => unxmlify($author_link),
317 'key' => (string)$key);
322 * @brief Dispatches public messages and find the fitting receivers
324 * @param array $msg The post that will be dispatched
326 * @return int The message id of the generated message, "true" or "false" if there was an error
328 public static function dispatch_public($msg) {
330 $enabled = intval(get_config("system", "diaspora_enabled"));
332 logger("diaspora is disabled");
336 if (!($postdata = self::valid_posting($msg))) {
337 logger("Invalid posting");
341 $fields = $postdata['fields'];
343 // Is it a an action (comment, like, ...) for our own post?
344 if (isset($fields->parent_guid) AND !$postdata["relayed"]) {
345 $guid = notags(unxmlify($fields->parent_guid));
346 $importer = self::importer_for_guid($guid);
347 if (is_array($importer)) {
348 logger("delivering to origin: ".$importer["name"]);
349 $message_id = self::dispatch($importer, $msg, $fields);
354 // Now distribute it to the followers
355 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
356 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
357 AND NOT `account_expired` AND NOT `account_removed`",
358 dbesc(NETWORK_DIASPORA),
359 dbesc($msg["author"])
362 if (dbm::is_result($r)) {
363 foreach ($r as $rr) {
364 logger("delivering to: ".$rr["username"]);
365 self::dispatch($rr, $msg, $fields);
367 } elseif (!Config::get('system', 'relay_subscribe', false)) {
368 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
370 // Use a dummy importer to import the data for the public copy
371 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
372 $message_id = self::dispatch($importer, $msg, $fields);
379 * @brief Dispatches the different message types to the different functions
381 * @param array $importer Array of the importer user
382 * @param array $msg The post that will be dispatched
383 * @param object $fields SimpleXML object that contains the message
385 * @return int The message id of the generated message, "true" or "false" if there was an error
387 public static function dispatch($importer, $msg, $fields = null) {
389 // The sender is the handle of the contact that sent the message.
390 // This will often be different with relayed messages (for example "like" and "comment")
391 $sender = $msg["author"];
393 // This is only needed for private postings since this is already done for public ones before
394 if (is_null($fields)) {
395 if (!($postdata = self::valid_posting($msg))) {
396 logger("Invalid posting");
399 $fields = $postdata['fields'];
402 $type = $fields->getName();
404 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
407 case "account_deletion":
408 return self::receive_account_deletion($importer, $fields);
411 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
414 return self::receive_contact_request($importer, $fields);
417 return self::receive_conversation($importer, $msg, $fields);
420 return self::receive_like($importer, $sender, $fields);
423 return self::receive_message($importer, $fields);
425 case "participation": // Not implemented
426 return self::receive_participation($importer, $fields);
428 case "photo": // Not implemented
429 return self::receive_photo($importer, $fields);
431 case "poll_participation": // Not implemented
432 return self::receive_poll_participation($importer, $fields);
435 return self::receive_profile($importer, $fields);
438 return self::receive_reshare($importer, $fields, $msg["message"]);
441 return self::receive_retraction($importer, $sender, $fields);
443 case "status_message":
444 return self::receive_status_message($importer, $fields, $msg["message"]);
447 logger("Unknown message type ".$type);
455 * @brief Checks if a posting is valid and fetches the data fields.
457 * This function does not only check the signature.
458 * It also does the conversion between the old and the new diaspora format.
460 * @param array $msg Array with the XML, the sender handle and the sender signature
462 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
464 private static function valid_posting($msg) {
466 $data = parse_xml_string($msg["message"], false);
468 if (!is_object($data)) {
469 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
473 $first_child = $data->getName();
475 // Is this the new or the old version?
476 if ($data->getName() == "XML") {
478 foreach ($data->post->children() as $child)
485 $type = $element->getName();
488 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
490 // All retractions are handled identically from now on.
491 // In the new version there will only be "retraction".
492 if (in_array($type, array("signed_retraction", "relayable_retraction")))
493 $type = "retraction";
495 if ($type == "request")
498 $fields = new SimpleXMLElement("<".$type."/>");
502 foreach ($element->children() AS $fieldname => $entry) {
504 // Translation for the old XML structure
505 if ($fieldname == "diaspora_handle")
506 $fieldname = "author";
508 if ($fieldname == "participant_handles")
509 $fieldname = "participants";
511 if (in_array($type, array("like", "participation"))) {
512 if ($fieldname == "target_type")
513 $fieldname = "parent_type";
516 if ($fieldname == "sender_handle")
517 $fieldname = "author";
519 if ($fieldname == "recipient_handle")
520 $fieldname = "recipient";
522 if ($fieldname == "root_diaspora_id")
523 $fieldname = "root_author";
525 if ($type == "retraction") {
526 if ($fieldname == "post_guid")
527 $fieldname = "target_guid";
529 if ($fieldname == "type")
530 $fieldname = "target_type";
534 if (($fieldname == "author_signature") AND ($entry != ""))
535 $author_signature = base64_decode($entry);
536 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
537 $parent_author_signature = base64_decode($entry);
538 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
539 if ($signed_data != "") {
541 $signed_data_parent .= ";";
544 $signed_data .= $entry;
546 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
547 ($orig_type == "relayable_retraction"))
548 xml::copy($entry, $fields, $fieldname);
551 // This is something that shouldn't happen at all.
552 if (in_array($type, array("status_message", "reshare", "profile")))
553 if ($msg["author"] != $fields->author) {
554 logger("Message handle is not the same as envelope sender. Quitting this message.");
558 // Only some message types have signatures. So we quit here for the other types.
559 if (!in_array($type, array("comment", "message", "like"))) {
560 return array("fields" => $fields, "relayed" => false);
562 // No author_signature? This is a must, so we quit.
563 if (!isset($author_signature)) {
564 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
568 if (isset($parent_author_signature)) {
571 $key = self::key($msg["author"]);
573 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
574 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);
581 $key = self::key($fields->author);
583 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
584 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
587 return array("fields" => $fields, "relayed" => $relayed);
592 * @brief Fetches the public key for a given handle
594 * @param string $handle The handle
596 * @return string The public key
598 private static function key($handle) {
599 $handle = strval($handle);
601 logger("Fetching diaspora key for: ".$handle);
603 $r = self::person_by_handle($handle);
611 * @brief Fetches data for a given handle
613 * @param string $handle The handle
615 * @return array the queried data
617 private static function person_by_handle($handle) {
619 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
620 dbesc(NETWORK_DIASPORA),
625 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
627 // update record occasionally so it doesn't get stale
628 $d = strtotime($person["updated"]." +00:00");
629 if ($d < strtotime("now - 14 days"))
632 if ($person["guid"] == "")
636 if (!$person OR $update) {
637 logger("create or refresh", LOGGER_DEBUG);
638 $r = probe_url($handle, PROBE_DIASPORA);
640 // Note that Friendica contacts will return a "Diaspora person"
641 // if Diaspora connectivity is enabled on their server
642 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
643 self::add_fcontact($r, $update);
651 * @brief Updates the fcontact table
653 * @param array $arr The fcontact data
654 * @param bool $update Update or insert?
656 * @return string The id of the fcontact entry
658 private static function add_fcontact($arr, $update = false) {
661 $r = q("UPDATE `fcontact` SET
675 WHERE `url` = '%s' AND `network` = '%s'",
677 dbesc($arr["photo"]),
678 dbesc($arr["request"]),
680 dbesc(strtolower($arr["addr"])),
682 dbesc($arr["batch"]),
683 dbesc($arr["notify"]),
685 dbesc($arr["confirm"]),
686 dbesc($arr["alias"]),
687 dbesc($arr["pubkey"]),
688 dbesc(datetime_convert()),
690 dbesc($arr["network"])
693 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
694 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
695 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
698 dbesc($arr["photo"]),
699 dbesc($arr["request"]),
703 dbesc($arr["batch"]),
704 dbesc($arr["notify"]),
706 dbesc($arr["confirm"]),
707 dbesc($arr["network"]),
708 dbesc($arr["alias"]),
709 dbesc($arr["pubkey"]),
710 dbesc(datetime_convert())
718 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
720 * @param int $contact_id The id in the contact table
721 * @param int $gcontact_id The id in the gcontact table
723 * @return string the handle
725 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
728 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
730 if ($gcontact_id != 0) {
731 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
732 intval($gcontact_id));
734 if (dbm::is_result($r)) {
735 return strtolower($r[0]["addr"]);
739 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
740 intval($contact_id));
742 if (dbm::is_result($r)) {
745 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
747 if ($contact['addr'] != "") {
748 $handle = $contact['addr'];
750 $baseurl_start = strpos($contact['url'],'://') + 3;
751 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
752 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
753 $handle = $contact['nick'].'@'.$baseurl;
757 return strtolower($handle);
761 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
764 * @param mixed $fcontact_guid Hexadecimal string guid
766 * @return string the contact url or null
768 public static function url_from_contact_guid($fcontact_guid) {
769 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
771 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
772 dbesc(NETWORK_DIASPORA),
773 dbesc($fcontact_guid)
776 if (dbm::is_result($r)) {
784 * @brief Get a contact id for a given handle
786 * @param int $uid The user id
787 * @param string $handle The handle in the format user@domain.tld
789 * @return The contact id
791 private static function contact_by_handle($uid, $handle) {
793 // First do a direct search on the contact table
794 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
799 if (dbm::is_result($r)) {
802 // We haven't found it?
803 // We use another function for it that will possibly create a contact entry
804 $cid = get_contact($handle, $uid);
807 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
809 if (dbm::is_result($r)) {
815 $handle_parts = explode("@", $handle);
816 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
817 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
822 if (dbm::is_result($r)) {
826 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
831 * @brief Check if posting is allowed for this contact
833 * @param array $importer Array of the importer user
834 * @param array $contact The contact that is checked
835 * @param bool $is_comment Is the check for a comment?
837 * @return bool is the contact allowed to post?
839 private static function post_allow($importer, $contact, $is_comment = false) {
841 // perhaps we were already sharing with this person. Now they're sharing with us.
842 // That makes us friends.
843 // Normally this should have handled by getting a request - but this could get lost
844 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
845 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
846 intval(CONTACT_IS_FRIEND),
847 intval($contact["id"]),
848 intval($importer["uid"])
850 $contact["rel"] = CONTACT_IS_FRIEND;
851 logger("defining user ".$contact["nick"]." as friend");
854 // We don't seem to like that person
855 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
857 // We are following this person? Then it is okay
858 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
860 // Is it a post to a community? That's good
861 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
864 // Messages for the global users and comments are always accepted
865 if (($importer["uid"] == 0) || $is_comment) {
873 * @brief Fetches the contact id for a handle and checks if posting is allowed
875 * @param array $importer Array of the importer user
876 * @param string $handle The checked handle in the format user@domain.tld
877 * @param bool $is_comment Is the check for a comment?
879 * @return array The contact data
881 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
882 $contact = self::contact_by_handle($importer["uid"], $handle);
884 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
885 // If a contact isn't found, we accept it anyway if it is a comment
893 if (!self::post_allow($importer, $contact, $is_comment)) {
894 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
901 * @brief Does the message already exists on the system?
903 * @param int $uid The user id
904 * @param string $guid The guid of the message
906 * @return int|bool message id if the message already was stored into the system - or false.
908 private static function message_exists($uid, $guid) {
909 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
914 if (dbm::is_result($r)) {
915 logger("message ".$guid." already exists for user ".$uid);
923 * @brief Checks for links to posts in a message
925 * @param array $item The item array
927 private static function fetch_guid($item) {
928 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
929 function ($match) use ($item){
930 return(self::fetch_guid_sub($match, $item));
935 * @brief Checks for relative /people/* links in an item body to match local
936 * contacts or prepends the remote host taken from the author link.
938 * @param string $body The item body to replace links from
939 * @param string $author_link The author link for missing local contact fallback
941 * @return the replaced string
943 public function replace_people_guid($body, $author_link) {
944 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
945 function ($match) use ($author_link) {
947 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
948 // 1 => '0123456789abcdef'
950 $handle = self::url_from_contact_guid($match[1]);
953 $return = '@[url='.$handle.']'.$match[2].'[/url]';
955 // No local match, restoring absolute remote URL from author scheme and host
956 $author_url = parse_url($author_link);
957 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
967 * @brief sub function of "fetch_guid" which checks for links in messages
969 * @param array $match array containing a link that has to be checked for a message link
970 * @param array $item The item array
972 private static function fetch_guid_sub($match, $item) {
973 if (!self::store_by_guid($match[1], $item["author-link"]))
974 self::store_by_guid($match[1], $item["owner-link"]);
978 * @brief Fetches an item with a given guid from a given server
980 * @param string $guid the message guid
981 * @param string $server The server address
982 * @param int $uid The user id of the user
984 * @return int the message id of the stored message or false
986 private static function store_by_guid($guid, $server, $uid = 0) {
987 $serverparts = parse_url($server);
988 $server = $serverparts["scheme"]."://".$serverparts["host"];
990 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
992 $msg = self::message($guid, $server);
997 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
999 // Now call the dispatcher
1000 return self::dispatch_public($msg);
1004 * @brief Fetches a message from a server
1006 * @param string $guid message guid
1007 * @param string $server The url of the server
1008 * @param int $level Endless loop prevention
1011 * 'message' => The message XML
1012 * 'author' => The author handle
1013 * 'key' => The public key of the author
1015 private static function message($guid, $server, $level = 0) {
1020 // This will work for new Diaspora servers and Friendica servers from 3.5
1021 $source_url = $server."/fetch/post/".$guid;
1022 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1024 $envelope = fetch_url($source_url);
1026 logger("Envelope was fetched.", LOGGER_DEBUG);
1027 $x = self::verify_magic_envelope($envelope);
1029 logger("Envelope could not be verified.", LOGGER_DEBUG);
1031 logger("Envelope was verified.", LOGGER_DEBUG);
1035 // This will work for older Diaspora and Friendica servers
1037 $source_url = $server."/p/".$guid.".xml";
1038 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1040 $x = fetch_url($source_url);
1045 $source_xml = parse_xml_string($x, false);
1047 if (!is_object($source_xml))
1050 if ($source_xml->post->reshare) {
1051 // Reshare of a reshare - old Diaspora version
1052 logger("Message is a reshare", LOGGER_DEBUG);
1053 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1054 } elseif ($source_xml->getName() == "reshare") {
1055 // Reshare of a reshare - new Diaspora version
1056 logger("Message is a new reshare", LOGGER_DEBUG);
1057 return self::message($source_xml->root_guid, $server, ++$level);
1062 // Fetch the author - for the old and the new Diaspora version
1063 if ($source_xml->post->status_message->diaspora_handle)
1064 $author = (string)$source_xml->post->status_message->diaspora_handle;
1065 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1066 $author = (string)$source_xml->author;
1068 // If this isn't a "status_message" then quit
1070 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1074 $msg = array("message" => $x, "author" => $author);
1076 $msg["key"] = self::key($msg["author"]);
1082 * @brief Fetches the item record of a given guid
1084 * @param int $uid The user id
1085 * @param string $guid message guid
1086 * @param string $author The handle of the item
1087 * @param array $contact The contact of the item owner
1089 * @return array the item record
1091 private static function parent_item($uid, $guid, $author, $contact) {
1092 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1093 `author-name`, `author-link`, `author-avatar`,
1094 `owner-name`, `owner-link`, `owner-avatar`
1095 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1096 intval($uid), dbesc($guid));
1099 $result = self::store_by_guid($guid, $contact["url"], $uid);
1102 $person = self::person_by_handle($author);
1103 $result = self::store_by_guid($guid, $person["url"], $uid);
1107 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1109 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1110 `author-name`, `author-link`, `author-avatar`,
1111 `owner-name`, `owner-link`, `owner-avatar`
1112 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1113 intval($uid), dbesc($guid));
1118 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1121 logger("parent item found: parent: ".$guid." - user: ".$uid);
1127 * @brief returns contact details
1129 * @param array $contact The default contact if the person isn't found
1130 * @param array $person The record of the person
1131 * @param int $uid The user id
1134 * 'cid' => contact id
1135 * 'network' => network type
1137 private static function author_contact_by_url($contact, $person, $uid) {
1139 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1140 dbesc(normalise_link($person["url"])), intval($uid));
1143 $network = $r[0]["network"];
1145 // We are receiving content from a user that possibly is about to be terminated
1146 // This means the user is vital, so we remove a possible termination date.
1147 unmark_for_death($r[0]);
1149 $cid = $contact["id"];
1150 $network = NETWORK_DIASPORA;
1153 return array("cid" => $cid, "network" => $network);
1157 * @brief Is the profile a hubzilla profile?
1159 * @param string $url The profile link
1161 * @return bool is it a hubzilla server?
1163 public static function is_redmatrix($url) {
1164 return(strstr($url, "/channel/"));
1168 * @brief Generate a post link with a given handle and message guid
1170 * @param string $addr The user handle
1171 * @param string $guid message guid
1173 * @return string the post link
1175 private static function plink($addr, $guid) {
1176 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1180 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1182 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1183 // So we try another way as well.
1184 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1186 $r[0]["network"] = $s[0]["network"];
1188 if ($r[0]["network"] == NETWORK_DFRN)
1189 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1191 if (self::is_redmatrix($r[0]["url"]))
1192 return $r[0]["url"]."/?f=&mid=".$guid;
1194 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1198 * @brief Processes an account deletion
1200 * @param array $importer Array of the importer user
1201 * @param object $data The message object
1203 * @return bool Success
1205 private static function receive_account_deletion($importer, $data) {
1207 /// @todo Account deletion should remove the contact from the global contacts as well
1209 $author = notags(unxmlify($data->author));
1211 $contact = self::contact_by_handle($importer["uid"], $author);
1213 logger("cannot find contact for author: ".$author);
1217 // We now remove the contact
1218 contact_remove($contact["id"]);
1223 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1225 * @param string $author Author handle
1226 * @param string $guid Message guid
1227 * @param boolean $onlyfound Only return uri when found in the database
1229 * @return string The constructed uri or the one from our database
1231 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1233 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1234 if (dbm::is_result($r)) {
1235 return $r[0]["uri"];
1236 } elseif (!$onlyfound) {
1237 return $author.":".$guid;
1244 * @brief Fetch the guid from our database with a given uri
1246 * @param string $author Author handle
1247 * @param string $uri Message uri
1249 * @return string The post guid
1251 private static function get_guid_from_uri($uri, $uid) {
1253 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1254 if (dbm::is_result($r)) {
1255 return $r[0]["guid"];
1262 * @brief Find the best importer for a comment, like, ...
1264 * @param string $guid The guid of the item
1266 * @return array|boolean the origin owner of that post - or false
1268 private static function importer_for_guid($guid) {
1269 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1271 if (dbm::is_result($item)) {
1272 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1273 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1274 if (dbm::is_result($contact)) {
1282 * @brief Processes an incoming comment
1284 * @param array $importer Array of the importer user
1285 * @param string $sender The sender of the message
1286 * @param object $data The message object
1287 * @param string $xml The original XML of the message
1289 * @return int The message id of the generated comment or "false" if there was an error
1291 private static function receive_comment($importer, $sender, $data, $xml) {
1292 $guid = notags(unxmlify($data->guid));
1293 $parent_guid = notags(unxmlify($data->parent_guid));
1294 $text = unxmlify($data->text);
1295 $author = notags(unxmlify($data->author));
1297 if (isset($data->created_at)) {
1298 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1300 $created_at = datetime_convert();
1303 if (isset($data->thread_parent_guid)) {
1304 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1305 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1310 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1315 $message_id = self::message_exists($importer["uid"], $guid);
1320 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1321 if (!$parent_item) {
1325 $person = self::person_by_handle($author);
1326 if (!is_array($person)) {
1327 logger("unable to find author details");
1331 // Fetch the contact id - if we know this contact
1332 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1334 $datarray = array();
1336 $datarray["uid"] = $importer["uid"];
1337 $datarray["contact-id"] = $author_contact["cid"];
1338 $datarray["network"] = $author_contact["network"];
1340 $datarray["author-name"] = $person["name"];
1341 $datarray["author-link"] = $person["url"];
1342 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1344 $datarray["owner-name"] = $contact["name"];
1345 $datarray["owner-link"] = $contact["url"];
1346 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1348 $datarray["guid"] = $guid;
1349 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1351 $datarray["type"] = "remote-comment";
1352 $datarray["verb"] = ACTIVITY_POST;
1353 $datarray["gravity"] = GRAVITY_COMMENT;
1355 if ($thr_uri != "") {
1356 $datarray["parent-uri"] = $thr_uri;
1358 $datarray["parent-uri"] = $parent_item["uri"];
1361 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1363 $datarray["protocol"] = PROTOCOL_DIASPORA;
1364 $datarray["source"] = $xml;
1366 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1368 $body = diaspora2bb($text);
1370 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1372 self::fetch_guid($datarray);
1374 $message_id = item_store($datarray);
1377 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1380 // If we are the origin of the parent we store the original data and notify our followers
1381 if ($message_id AND $parent_item["origin"]) {
1383 // Formerly we stored the signed text, the signature and the author in different fields.
1384 // We now store the raw data so that we are more flexible.
1385 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1386 intval($message_id),
1387 dbesc(json_encode($data))
1391 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1398 * @brief processes and stores private messages
1400 * @param array $importer Array of the importer user
1401 * @param array $contact The contact of the message
1402 * @param object $data The message object
1403 * @param array $msg Array of the processed message, author handle and key
1404 * @param object $mesg The private message
1405 * @param array $conversation The conversation record to which this message belongs
1407 * @return bool "true" if it was successful
1409 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1410 $guid = notags(unxmlify($data->guid));
1411 $subject = notags(unxmlify($data->subject));
1412 $author = notags(unxmlify($data->author));
1414 $msg_guid = notags(unxmlify($mesg->guid));
1415 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1416 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1417 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1418 $msg_text = unxmlify($mesg->text);
1419 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1421 // "diaspora_handle" is the element name from the old version
1422 // "author" is the element name from the new version
1423 if ($mesg->author) {
1424 $msg_author = notags(unxmlify($mesg->author));
1425 } elseif ($mesg->diaspora_handle) {
1426 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1431 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1433 if ($msg_conversation_guid != $guid) {
1434 logger("message conversation guid does not belong to the current conversation.");
1438 $body = diaspora2bb($msg_text);
1439 $message_uri = $msg_author.":".$msg_guid;
1441 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1443 $author_signature = base64_decode($msg_author_signature);
1445 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1449 $person = self::person_by_handle($msg_author);
1451 if (is_array($person) && x($person, "pubkey")) {
1452 $key = $person["pubkey"];
1454 logger("unable to find author details");
1459 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1460 logger("verification failed.");
1464 if ($msg_parent_author_signature) {
1465 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1467 $parent_author_signature = base64_decode($msg_parent_author_signature);
1471 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1472 logger("owner verification failed.");
1477 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1480 if (dbm::is_result($r)) {
1481 logger("duplicate message already delivered.", LOGGER_DEBUG);
1485 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1486 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1487 intval($importer["uid"]),
1489 intval($conversation["id"]),
1490 dbesc($person["name"]),
1491 dbesc($person["photo"]),
1492 dbesc($person["url"]),
1493 intval($contact["id"]),
1498 dbesc($message_uri),
1499 dbesc($author.":".$guid),
1500 dbesc($msg_created_at)
1503 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1504 dbesc(datetime_convert()),
1505 intval($conversation["id"])
1509 "type" => NOTIFY_MAIL,
1510 "notify_flags" => $importer["notify-flags"],
1511 "language" => $importer["language"],
1512 "to_name" => $importer["username"],
1513 "to_email" => $importer["email"],
1514 "uid" =>$importer["uid"],
1515 "item" => array("subject" => $subject, "body" => $body),
1516 "source_name" => $person["name"],
1517 "source_link" => $person["url"],
1518 "source_photo" => $person["thumb"],
1519 "verb" => ACTIVITY_POST,
1526 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1528 * @param array $importer Array of the importer user
1529 * @param array $msg Array of the processed message, author handle and key
1530 * @param object $data The message object
1532 * @return bool Success
1534 private static function receive_conversation($importer, $msg, $data) {
1535 $guid = notags(unxmlify($data->guid));
1536 $subject = notags(unxmlify($data->subject));
1537 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1538 $author = notags(unxmlify($data->author));
1539 $participants = notags(unxmlify($data->participants));
1541 $messages = $data->message;
1543 if (!count($messages)) {
1544 logger("empty conversation");
1548 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1552 $conversation = null;
1554 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1555 intval($importer["uid"]),
1559 $conversation = $c[0];
1561 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1562 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1563 intval($importer["uid"]),
1567 dbesc(datetime_convert()),
1569 dbesc($participants)
1572 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1573 intval($importer["uid"]),
1578 $conversation = $c[0];
1580 if (!$conversation) {
1581 logger("unable to create conversation.");
1585 foreach ($messages as $mesg)
1586 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1592 * @brief Creates the body for a "like" message
1594 * @param array $contact The contact that send us the "like"
1595 * @param array $parent_item The item array of the parent item
1596 * @param string $guid message guid
1598 * @return string the body
1600 private static function construct_like_body($contact, $parent_item, $guid) {
1601 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1603 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1604 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1605 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1607 return sprintf($bodyverb, $ulink, $alink, $plink);
1611 * @brief Creates a XML object for a "like"
1613 * @param array $importer Array of the importer user
1614 * @param array $parent_item The item array of the parent item
1616 * @return string The XML
1618 private static function construct_like_object($importer, $parent_item) {
1619 $objtype = ACTIVITY_OBJ_NOTE;
1620 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1621 $parent_body = $parent_item["body"];
1623 $xmldata = array("object" => array("type" => $objtype,
1625 "id" => $parent_item["uri"],
1628 "content" => $parent_body));
1630 return xml::from_array($xmldata, $xml, true);
1634 * @brief Processes "like" messages
1636 * @param array $importer Array of the importer user
1637 * @param string $sender The sender of the message
1638 * @param object $data The message object
1640 * @return int The message id of the generated like or "false" if there was an error
1642 private static function receive_like($importer, $sender, $data) {
1643 $positive = notags(unxmlify($data->positive));
1644 $guid = notags(unxmlify($data->guid));
1645 $parent_type = notags(unxmlify($data->parent_type));
1646 $parent_guid = notags(unxmlify($data->parent_guid));
1647 $author = notags(unxmlify($data->author));
1649 // likes on comments aren't supported by Diaspora - only on posts
1650 // But maybe this will be supported in the future, so we will accept it.
1651 if (!in_array($parent_type, array("Post", "Comment")))
1654 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1658 $message_id = self::message_exists($importer["uid"], $guid);
1662 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1666 $person = self::person_by_handle($author);
1667 if (!is_array($person)) {
1668 logger("unable to find author details");
1672 // Fetch the contact id - if we know this contact
1673 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1675 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1676 // We would accept this anyhow.
1677 if ($positive == "true")
1678 $verb = ACTIVITY_LIKE;
1680 $verb = ACTIVITY_DISLIKE;
1682 $datarray = array();
1684 $datarray["protocol"] = PROTOCOL_DIASPORA;
1686 $datarray["uid"] = $importer["uid"];
1687 $datarray["contact-id"] = $author_contact["cid"];
1688 $datarray["network"] = $author_contact["network"];
1690 $datarray["author-name"] = $person["name"];
1691 $datarray["author-link"] = $person["url"];
1692 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1694 $datarray["owner-name"] = $contact["name"];
1695 $datarray["owner-link"] = $contact["url"];
1696 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1698 $datarray["guid"] = $guid;
1699 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1701 $datarray["type"] = "activity";
1702 $datarray["verb"] = $verb;
1703 $datarray["gravity"] = GRAVITY_LIKE;
1704 $datarray["parent-uri"] = $parent_item["uri"];
1706 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1707 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1709 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1711 $message_id = item_store($datarray);
1714 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1716 // If we are the origin of the parent we store the original data and notify our followers
1717 if ($message_id AND $parent_item["origin"]) {
1719 // Formerly we stored the signed text, the signature and the author in different fields.
1720 // We now store the raw data so that we are more flexible.
1721 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1722 intval($message_id),
1723 dbesc(json_encode($data))
1727 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1734 * @brief Processes private messages
1736 * @param array $importer Array of the importer user
1737 * @param object $data The message object
1739 * @return bool Success?
1741 private static function receive_message($importer, $data) {
1742 $guid = notags(unxmlify($data->guid));
1743 $parent_guid = notags(unxmlify($data->parent_guid));
1744 $text = unxmlify($data->text);
1745 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1746 $author = notags(unxmlify($data->author));
1747 $conversation_guid = notags(unxmlify($data->conversation_guid));
1749 $contact = self::allowed_contact_by_handle($importer, $author, true);
1754 $conversation = null;
1756 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1757 intval($importer["uid"]),
1758 dbesc($conversation_guid)
1761 $conversation = $c[0];
1763 logger("conversation not available.");
1767 $message_uri = $author.":".$guid;
1769 $person = self::person_by_handle($author);
1771 logger("unable to find author details");
1775 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1776 dbesc($message_uri),
1777 intval($importer["uid"])
1779 if (dbm::is_result($r)) {
1780 logger("duplicate message already delivered.", LOGGER_DEBUG);
1784 $body = diaspora2bb($text);
1786 $body = self::replace_people_guid($body, $person["url"]);
1788 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1789 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1790 intval($importer["uid"]),
1792 intval($conversation["id"]),
1793 dbesc($person["name"]),
1794 dbesc($person["photo"]),
1795 dbesc($person["url"]),
1796 intval($contact["id"]),
1797 dbesc($conversation["subject"]),
1801 dbesc($message_uri),
1802 dbesc($author.":".$parent_guid),
1806 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1807 dbesc(datetime_convert()),
1808 intval($conversation["id"])
1815 * @brief Processes participations - unsupported by now
1817 * @param array $importer Array of the importer user
1818 * @param object $data The message object
1820 * @return bool always true
1822 private static function receive_participation($importer, $data) {
1823 // I'm not sure if we can fully support this message type
1828 * @brief Processes photos - unneeded
1830 * @param array $importer Array of the importer user
1831 * @param object $data The message object
1833 * @return bool always true
1835 private static function receive_photo($importer, $data) {
1836 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1841 * @brief Processes poll participations - unssupported
1843 * @param array $importer Array of the importer user
1844 * @param object $data The message object
1846 * @return bool always true
1848 private static function receive_poll_participation($importer, $data) {
1849 // We don't support polls by now
1854 * @brief Processes incoming profile updates
1856 * @param array $importer Array of the importer user
1857 * @param object $data The message object
1859 * @return bool Success
1861 private static function receive_profile($importer, $data) {
1862 $author = strtolower(notags(unxmlify($data->author)));
1864 $contact = self::contact_by_handle($importer["uid"], $author);
1868 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1869 $image_url = unxmlify($data->image_url);
1870 $birthday = unxmlify($data->birthday);
1871 $location = diaspora2bb(unxmlify($data->location));
1872 $about = diaspora2bb(unxmlify($data->bio));
1873 $gender = unxmlify($data->gender);
1874 $searchable = (unxmlify($data->searchable) == "true");
1875 $nsfw = (unxmlify($data->nsfw) == "true");
1876 $tags = unxmlify($data->tag_string);
1878 $tags = explode("#", $tags);
1880 $keywords = array();
1881 foreach ($tags as $tag) {
1882 $tag = trim(strtolower($tag));
1887 $keywords = implode(", ", $keywords);
1889 $handle_parts = explode("@", $author);
1890 $nick = $handle_parts[0];
1893 $name = $handle_parts[0];
1895 if ( preg_match("|^https?://|", $image_url) === 0)
1896 $image_url = "http://".$handle_parts[1].$image_url;
1898 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1900 // Generic birthday. We don't know the timezone. The year is irrelevant.
1902 $birthday = str_replace("1000", "1901", $birthday);
1904 if ($birthday != "")
1905 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1907 // this is to prevent multiple birthday notifications in a single year
1908 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1910 if (substr($birthday,5) === substr($contact["bd"],5))
1911 $birthday = $contact["bd"];
1913 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1914 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1918 dbesc(datetime_convert()),
1924 intval($contact["id"]),
1925 intval($importer["uid"])
1928 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1929 "photo" => $image_url, "name" => $name, "location" => $location,
1930 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1931 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1932 "hide" => !$searchable, "nsfw" => $nsfw);
1934 $gcid = update_gcontact($gcontact);
1936 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1938 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1944 * @brief Processes incoming friend requests
1946 * @param array $importer Array of the importer user
1947 * @param array $contact The contact that send the request
1949 private static function receive_request_make_friend($importer, $contact) {
1953 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1954 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1955 intval(CONTACT_IS_FRIEND),
1956 intval($contact["id"]),
1957 intval($importer["uid"])
1960 // send notification
1962 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1963 intval($importer["uid"])
1966 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1968 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1969 intval($importer["uid"])
1972 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1974 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1977 $arr["protocol"] = PROTOCOL_DIASPORA;
1978 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1979 $arr["uid"] = $importer["uid"];
1980 $arr["contact-id"] = $self[0]["id"];
1982 $arr["type"] = 'wall';
1983 $arr["gravity"] = 0;
1985 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1986 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1987 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1988 $arr["verb"] = ACTIVITY_FRIEND;
1989 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1991 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1992 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1993 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1994 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1996 $arr["object"] = self::construct_new_friend_object($contact);
1998 $arr["last-child"] = 1;
2000 $arr["allow_cid"] = $user[0]["allow_cid"];
2001 $arr["allow_gid"] = $user[0]["allow_gid"];
2002 $arr["deny_cid"] = $user[0]["deny_cid"];
2003 $arr["deny_gid"] = $user[0]["deny_gid"];
2005 $i = item_store($arr);
2007 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
2013 * @brief Creates a XML object for a "new friend" message
2015 * @param array $contact Array of the contact
2017 * @return string The XML
2019 private static function construct_new_friend_object($contact) {
2020 $objtype = ACTIVITY_OBJ_PERSON;
2021 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2022 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2024 $xmldata = array("object" => array("type" => $objtype,
2025 "title" => $contact["name"],
2026 "id" => $contact["url"]."/".$contact["name"],
2029 return xml::from_array($xmldata, $xml, true);
2033 * @brief Processes incoming sharing notification
2035 * @param array $importer Array of the importer user
2036 * @param object $data The message object
2038 * @return bool Success
2040 private static function receive_contact_request($importer, $data) {
2041 $author = unxmlify($data->author);
2042 $recipient = unxmlify($data->recipient);
2044 if (!$author || !$recipient) {
2048 // the current protocol version doesn't know these fields
2049 // That means that we will assume their existance
2050 if (isset($data->following)) {
2051 $following = (unxmlify($data->following) == "true");
2056 if (isset($data->sharing)) {
2057 $sharing = (unxmlify($data->sharing) == "true");
2062 $contact = self::contact_by_handle($importer["uid"],$author);
2064 // perhaps we were already sharing with this person. Now they're sharing with us.
2065 // That makes us friends.
2067 if ($following AND $sharing) {
2068 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
2069 self::receive_request_make_friend($importer, $contact);
2071 // refetch the contact array
2072 $contact = self::contact_by_handle($importer["uid"],$author);
2074 // If we are now friends, we are sending a share message.
2075 // Normally we needn't to do so, but the first message could have been vanished.
2076 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
2077 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2079 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2080 $ret = self::send_share($u[0], $contact);
2084 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2085 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2090 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2091 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2093 } elseif (!$following AND !$sharing) {
2094 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2096 } elseif (!$following AND $sharing) {
2097 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2098 } elseif ($following AND $sharing) {
2099 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2100 } elseif ($following AND !$sharing) {
2101 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2104 $ret = self::person_by_handle($author);
2106 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2107 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2111 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2113 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2114 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2115 intval($importer["uid"]),
2116 dbesc($ret["network"]),
2117 dbesc($ret["addr"]),
2120 dbesc(normalise_link($ret["url"])),
2122 dbesc($ret["name"]),
2123 dbesc($ret["nick"]),
2124 dbesc($ret["photo"]),
2125 dbesc($ret["pubkey"]),
2126 dbesc($ret["notify"]),
2127 dbesc($ret["poll"]),
2132 // find the contact record we just created
2134 $contact_record = self::contact_by_handle($importer["uid"],$author);
2136 if (!$contact_record) {
2137 logger("unable to locate newly created contact record.");
2141 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2143 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2145 if (intval($def_gid))
2146 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2148 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2150 if ($importer["page-flags"] == PAGE_NORMAL) {
2152 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2154 $hash = random_string().(string)time(); // Generate a confirm_key
2156 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2157 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2158 intval($importer["uid"]),
2159 intval($contact_record["id"]),
2162 dbesc(t("Sharing notification from Diaspora network")),
2164 dbesc(datetime_convert())
2168 // automatic friend approval
2170 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2172 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2174 // technically they are sharing with us (CONTACT_IS_SHARING),
2175 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2176 // we are going to change the relationship and make them a follower.
2178 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2179 $new_relation = CONTACT_IS_FRIEND;
2180 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2181 $new_relation = CONTACT_IS_SHARING;
2183 $new_relation = CONTACT_IS_FOLLOWER;
2185 $r = q("UPDATE `contact` SET `rel` = %d,
2193 intval($new_relation),
2194 dbesc(datetime_convert()),
2195 dbesc(datetime_convert()),
2196 intval($contact_record["id"])
2199 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2201 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2202 $ret = self::send_share($u[0], $contact_record);
2204 // Send the profile data, maybe it weren't transmitted before
2205 self::send_profile($importer["uid"], array($contact_record));
2213 * @brief Fetches a message with a given guid
2215 * @param string $guid message guid
2216 * @param string $orig_author handle of the original post
2217 * @param string $author handle of the sharer
2219 * @return array The fetched item
2221 private static function original_item($guid, $orig_author, $author) {
2223 // Do we already have this item?
2224 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2225 `author-name`, `author-link`, `author-avatar`
2226 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2229 if (dbm::is_result($r)) {
2230 logger("reshared message ".$guid." already exists on system.");
2232 // Maybe it is already a reshared item?
2233 // Then refetch the content, if it is a reshare from a reshare.
2234 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2235 if (self::is_reshare($r[0]["body"], true)) {
2237 } elseif (self::is_reshare($r[0]["body"], false)) {
2238 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2240 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2242 // Add OEmbed and other information to the body
2243 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2251 if (!dbm::is_result($r)) {
2252 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2253 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2254 $item_id = self::store_by_guid($guid, $server);
2257 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2258 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2259 $item_id = self::store_by_guid($guid, $server);
2263 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2264 `author-name`, `author-link`, `author-avatar`
2265 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2268 if (dbm::is_result($r)) {
2269 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2270 if (self::is_reshare($r[0]["body"], false)) {
2271 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2272 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2284 * @brief Processes a reshare message
2286 * @param array $importer Array of the importer user
2287 * @param object $data The message object
2288 * @param string $xml The original XML of the message
2290 * @return int the message id
2292 private static function receive_reshare($importer, $data, $xml) {
2293 $root_author = notags(unxmlify($data->root_author));
2294 $root_guid = notags(unxmlify($data->root_guid));
2295 $guid = notags(unxmlify($data->guid));
2296 $author = notags(unxmlify($data->author));
2297 $public = notags(unxmlify($data->public));
2298 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2300 $contact = self::allowed_contact_by_handle($importer, $author, false);
2305 $message_id = self::message_exists($importer["uid"], $guid);
2310 $original_item = self::original_item($root_guid, $root_author, $author);
2311 if (!$original_item) {
2315 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2317 $datarray = array();
2319 $datarray["uid"] = $importer["uid"];
2320 $datarray["contact-id"] = $contact["id"];
2321 $datarray["network"] = NETWORK_DIASPORA;
2323 $datarray["author-name"] = $contact["name"];
2324 $datarray["author-link"] = $contact["url"];
2325 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2327 $datarray["owner-name"] = $datarray["author-name"];
2328 $datarray["owner-link"] = $datarray["author-link"];
2329 $datarray["owner-avatar"] = $datarray["author-avatar"];
2331 $datarray["guid"] = $guid;
2332 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2334 $datarray["verb"] = ACTIVITY_POST;
2335 $datarray["gravity"] = GRAVITY_PARENT;
2337 $datarray["protocol"] = PROTOCOL_DIASPORA;
2338 $datarray["source"] = $xml;
2340 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2341 $original_item["guid"], $original_item["created"], $orig_url);
2342 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2344 $datarray["tag"] = $original_item["tag"];
2345 $datarray["app"] = $original_item["app"];
2347 $datarray["plink"] = self::plink($author, $guid);
2348 $datarray["private"] = (($public == "false") ? 1 : 0);
2349 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2351 $datarray["object-type"] = $original_item["object-type"];
2353 self::fetch_guid($datarray);
2354 $message_id = item_store($datarray);
2357 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2364 * @brief Processes retractions
2366 * @param array $importer Array of the importer user
2367 * @param array $contact The contact of the item owner
2368 * @param object $data The message object
2370 * @return bool success
2372 private static function item_retraction($importer, $contact, $data) {
2373 $target_type = notags(unxmlify($data->target_type));
2374 $target_guid = notags(unxmlify($data->target_guid));
2375 $author = notags(unxmlify($data->author));
2377 $person = self::person_by_handle($author);
2378 if (!is_array($person)) {
2379 logger("unable to find author detail for ".$author);
2383 if (!isset($contact["url"])) {
2384 $contact["url"] = $person["url"];
2387 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2388 dbesc($target_guid),
2389 intval($importer["uid"])
2392 logger("Target guid ".$target_guid." was not found for user ".$importer["uid"]);
2396 // Check if the sender is the thread owner
2397 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2398 intval($r[0]["parent"]));
2400 // Only delete it if the parent author really fits
2401 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2402 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2406 // 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
2407 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2408 dbesc(datetime_convert()),
2409 dbesc(datetime_convert()),
2412 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2414 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2416 // Now check if the retraction needs to be relayed by us
2417 if ($p[0]["origin"]) {
2419 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2426 * @brief Receives retraction messages
2428 * @param array $importer Array of the importer user
2429 * @param string $sender The sender of the message
2430 * @param object $data The message object
2432 * @return bool Success
2434 private static function receive_retraction($importer, $sender, $data) {
2435 $target_type = notags(unxmlify($data->target_type));
2437 $contact = self::contact_by_handle($importer["uid"], $sender);
2438 if (!$contact AND (in_array($target_type, array("Contact", "Person")))) {
2439 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2443 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2445 switch ($target_type) {
2448 case "Post": // "Post" will be supported in a future version
2450 case "StatusMessage":
2451 return self::item_retraction($importer, $contact, $data);
2455 /// @todo What should we do with an "unshare"?
2456 // Removing the contact isn't correct since we still can read the public items
2457 contact_remove($contact["id"]);
2461 logger("Unknown target type ".$target_type);
2468 * @brief Receives status messages
2470 * @param array $importer Array of the importer user
2471 * @param object $data The message object
2472 * @param string $xml The original XML of the message
2474 * @return int The message id of the newly created item
2476 private static function receive_status_message($importer, $data, $xml) {
2477 $raw_message = unxmlify($data->raw_message);
2478 $guid = notags(unxmlify($data->guid));
2479 $author = notags(unxmlify($data->author));
2480 $public = notags(unxmlify($data->public));
2481 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2482 $provider_display_name = notags(unxmlify($data->provider_display_name));
2484 /// @todo enable support for polls
2485 //if ($data->poll) {
2486 // foreach ($data->poll AS $poll)
2490 $contact = self::allowed_contact_by_handle($importer, $author, false);
2495 $message_id = self::message_exists($importer["uid"], $guid);
2501 if ($data->location) {
2502 foreach ($data->location->children() AS $fieldname => $data) {
2503 $address[$fieldname] = notags(unxmlify($data));
2507 $body = diaspora2bb($raw_message);
2509 $datarray = array();
2511 // Attach embedded pictures to the body
2513 foreach ($data->photo AS $photo) {
2514 $body = "[img]".unxmlify($photo->remote_photo_path).
2515 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2518 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2520 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2522 // Add OEmbed and other information to the body
2523 if (!self::is_redmatrix($contact["url"])) {
2524 $body = add_page_info_to_body($body, false, true);
2528 $datarray["uid"] = $importer["uid"];
2529 $datarray["contact-id"] = $contact["id"];
2530 $datarray["network"] = NETWORK_DIASPORA;
2532 $datarray["author-name"] = $contact["name"];
2533 $datarray["author-link"] = $contact["url"];
2534 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2536 $datarray["owner-name"] = $datarray["author-name"];
2537 $datarray["owner-link"] = $datarray["author-link"];
2538 $datarray["owner-avatar"] = $datarray["author-avatar"];
2540 $datarray["guid"] = $guid;
2541 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2543 $datarray["verb"] = ACTIVITY_POST;
2544 $datarray["gravity"] = GRAVITY_PARENT;
2546 $datarray["protocol"] = PROTOCOL_DIASPORA;
2547 $datarray["source"] = $xml;
2549 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2551 if ($provider_display_name != "") {
2552 $datarray["app"] = $provider_display_name;
2555 $datarray["plink"] = self::plink($author, $guid);
2556 $datarray["private"] = (($public == "false") ? 1 : 0);
2557 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2559 if (isset($address["address"])) {
2560 $datarray["location"] = $address["address"];
2563 if (isset($address["lat"]) AND isset($address["lng"])) {
2564 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2567 self::fetch_guid($datarray);
2568 $message_id = item_store($datarray);
2571 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2577 /* ************************************************************************************** *
2578 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2579 * ************************************************************************************** */
2582 * @brief returnes the handle of a contact
2584 * @param array $me contact array
2586 * @return string the handle in the format user@domain.tld
2588 private static function my_handle($contact) {
2589 if ($contact["addr"] != "") {
2590 return $contact["addr"];
2593 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2594 // So - just in case - we build the the address here.
2595 if ($contact["nickname"] != "") {
2596 $nick = $contact["nickname"];
2598 $nick = $contact["nick"];
2601 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2605 * @brief Creates the envelope for the "fetch" endpoint
2607 * @param string $msg The message that is to be transmitted
2608 * @param array $user The record of the sender
2610 * @return string The envelope
2613 public static function build_magic_envelope($msg, $user) {
2615 $b64url_data = base64url_encode($msg);
2616 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2618 $key_id = base64url_encode(self::my_handle($user));
2619 $type = "application/xml";
2620 $encoding = "base64url";
2621 $alg = "RSA-SHA256";
2622 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2623 $signature = rsa_sign($signable_data, $user["prvkey"]);
2624 $sig = base64url_encode($signature);
2626 $xmldata = array("me:env" => array("me:data" => $data,
2627 "@attributes" => array("type" => $type),
2628 "me:encoding" => $encoding,
2631 "@attributes2" => array("key_id" => $key_id)));
2633 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2635 return xml::from_array($xmldata, $xml, false, $namespaces);
2639 * @brief Creates the envelope for a public message
2641 * @param string $msg The message that is to be transmitted
2642 * @param array $user The record of the sender
2643 * @param array $contact Target of the communication
2644 * @param string $prvkey The private key of the sender
2645 * @param string $pubkey The public key of the receiver
2647 * @return string The envelope
2649 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2651 logger("Message: ".$msg, LOGGER_DATA);
2653 $handle = self::my_handle($user);
2655 $b64url_data = base64url_encode($msg);
2657 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2659 $type = "application/xml";
2660 $encoding = "base64url";
2661 $alg = "RSA-SHA256";
2663 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2665 $signature = rsa_sign($signable_data,$prvkey);
2666 $sig = base64url_encode($signature);
2668 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2669 "me:env" => array("me:encoding" => $encoding,
2672 "@attributes" => array("type" => $type),
2673 "me:sig" => $sig)));
2675 $namespaces = array("" => "https://joindiaspora.com/protocol",
2676 "me" => "http://salmon-protocol.org/ns/magic-env");
2678 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2680 logger("magic_env: ".$magic_env, LOGGER_DATA);
2685 * @brief Creates the envelope for a private message
2687 * @param string $msg The message that is to be transmitted
2688 * @param array $user The record of the sender
2689 * @param array $contact Target of the communication
2690 * @param string $prvkey The private key of the sender
2691 * @param string $pubkey The public key of the receiver
2693 * @return string The envelope
2695 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2697 logger("Message: ".$msg, LOGGER_DATA);
2699 // without a public key nothing will work
2702 logger("pubkey missing: contact id: ".$contact["id"]);
2706 $inner_aes_key = openssl_random_pseudo_bytes(32);
2707 $b_inner_aes_key = base64_encode($inner_aes_key);
2708 $inner_iv = openssl_random_pseudo_bytes(16);
2709 $b_inner_iv = base64_encode($inner_iv);
2711 $outer_aes_key = openssl_random_pseudo_bytes(32);
2712 $b_outer_aes_key = base64_encode($outer_aes_key);
2713 $outer_iv = openssl_random_pseudo_bytes(16);
2714 $b_outer_iv = base64_encode($outer_iv);
2716 $handle = self::my_handle($user);
2718 $inner_encrypted = self::aes_encrypt($inner_aes_key, $inner_iv, $msg);
2720 $b64_data = base64_encode($inner_encrypted);
2723 $b64url_data = base64url_encode($b64_data);
2724 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2726 $type = "application/xml";
2727 $encoding = "base64url";
2728 $alg = "RSA-SHA256";
2730 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2732 $signature = rsa_sign($signable_data,$prvkey);
2733 $sig = base64url_encode($signature);
2735 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2736 "aes_key" => $b_inner_aes_key,
2737 "author_id" => $handle));
2739 $decrypted_header = xml::from_array($xmldata, $xml, true);
2741 $ciphertext = self::aes_encrypt($outer_aes_key, $outer_iv, $decrypted_header);
2743 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2745 $encrypted_outer_key_bundle = "";
2746 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2748 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2750 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2752 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2753 "ciphertext" => base64_encode($ciphertext)));
2754 $cipher_json = base64_encode($encrypted_header_json_object);
2756 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2757 "me:env" => array("me:encoding" => $encoding,
2760 "@attributes" => array("type" => $type),
2761 "me:sig" => $sig)));
2763 $namespaces = array("" => "https://joindiaspora.com/protocol",
2764 "me" => "http://salmon-protocol.org/ns/magic-env");
2766 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2768 logger("magic_env: ".$magic_env, LOGGER_DATA);
2773 * @brief Create the envelope for a message
2775 * @param string $msg The message that is to be transmitted
2776 * @param array $user The record of the sender
2777 * @param array $contact Target of the communication
2778 * @param string $prvkey The private key of the sender
2779 * @param string $pubkey The public key of the receiver
2780 * @param bool $public Is the message public?
2782 * @return string The message that will be transmitted to other servers
2784 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2787 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2789 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2791 // The data that will be transmitted is double encoded via "urlencode", strange ...
2792 $slap = "xml=".urlencode(urlencode($magic_env));
2797 * @brief Creates a signature for a message
2799 * @param array $owner the array of the owner of the message
2800 * @param array $message The message that is to be signed
2802 * @return string The signature
2804 private static function signature($owner, $message) {
2806 unset($sigmsg["author_signature"]);
2807 unset($sigmsg["parent_author_signature"]);
2809 $signed_text = implode(";", $sigmsg);
2811 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2815 * @brief Transmit a message to a target server
2817 * @param array $owner the array of the item owner
2818 * @param array $contact Target of the communication
2819 * @param string $slap The message that is to be transmitted
2820 * @param bool $public_batch Is it a public post?
2821 * @param bool $queue_run Is the transmission called from the queue?
2822 * @param string $guid message guid
2824 * @return int Result of the transmission
2826 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2830 $enabled = intval(get_config("system", "diaspora_enabled"));
2834 $logid = random_string(4);
2835 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2837 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2841 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2843 if (!$queue_run && was_recently_delayed($contact["id"])) {
2846 if (!intval(get_config("system", "diaspora_test"))) {
2847 post_url($dest_url."/", $slap);
2848 $return_code = $a->get_curl_code();
2850 logger("test_mode");
2855 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2857 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2858 logger("queue message");
2860 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2861 intval($contact["id"]),
2862 dbesc(NETWORK_DIASPORA),
2864 intval($public_batch)
2867 logger("add_to_queue ignored - identical item already in queue");
2869 // queue message for redelivery
2870 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2872 // The message could not be delivered. We mark the contact as "dead"
2873 mark_for_death($contact);
2875 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2876 // We successfully delivered a message, the contact is alive
2877 unmark_for_death($contact);
2880 return(($return_code) ? $return_code : (-1));
2885 * @brief Build the post xml
2887 * @param string $type The message type
2888 * @param array $message The message data
2890 * @return string The post XML
2892 public static function build_post_xml($type, $message) {
2894 $data = array("XML" => array("post" => array($type => $message)));
2895 return xml::from_array($data, $xml);
2899 * @brief Builds and transmit messages
2901 * @param array $owner the array of the item owner
2902 * @param array $contact Target of the communication
2903 * @param string $type The message type
2904 * @param array $message The message data
2905 * @param bool $public_batch Is it a public post?
2906 * @param string $guid message guid
2907 * @param bool $spool Should the transmission be spooled or transmitted?
2909 * @return int Result of the transmission
2911 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2913 $msg = self::build_post_xml($type, $message);
2915 logger('message: '.$msg, LOGGER_DATA);
2916 logger('send guid '.$guid, LOGGER_DEBUG);
2918 // Fallback if the private key wasn't transmitted in the expected field
2919 if ($owner['uprvkey'] == "")
2920 $owner['uprvkey'] = $owner['prvkey'];
2922 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2925 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2928 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2930 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2932 return $return_code;
2936 * @brief Sends a "share" message
2938 * @param array $owner the array of the item owner
2939 * @param array $contact Target of the communication
2941 * @return int The result of the transmission
2943 public static function send_share($owner,$contact) {
2945 $message = array("sender_handle" => self::my_handle($owner),
2946 "recipient_handle" => $contact["addr"]);
2948 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2950 return self::build_and_transmit($owner, $contact, "request", $message);
2954 * @brief sends an "unshare"
2956 * @param array $owner the array of the item owner
2957 * @param array $contact Target of the communication
2959 * @return int The result of the transmission
2961 public static function send_unshare($owner,$contact) {
2963 $message = array("post_guid" => $owner["guid"],
2964 "diaspora_handle" => self::my_handle($owner),
2965 "type" => "Person");
2967 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2969 return self::build_and_transmit($owner, $contact, "retraction", $message);
2973 * @brief Checks a message body if it is a reshare
2975 * @param string $body The message body that is to be check
2976 * @param bool $complete Should it be a complete check or a simple check?
2978 * @return array|bool Reshare details or "false" if no reshare
2980 public static function is_reshare($body, $complete = true) {
2981 $body = trim($body);
2983 // Skip if it isn't a pure repeated messages
2984 // Does it start with a share?
2985 if ((strpos($body, "[share") > 0) AND $complete)
2988 // Does it end with a share?
2989 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2992 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2993 // Skip if there is no shared message in there
2994 if ($body == $attributes)
2997 // If we don't do the complete check we quit here
3002 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3003 if ($matches[1] != "")
3004 $guid = $matches[1];
3006 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3007 if ($matches[1] != "")
3008 $guid = $matches[1];
3011 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3012 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3015 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3016 $ret["root_guid"] = $guid;
3022 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3023 if ($matches[1] != "")
3024 $profile = $matches[1];
3026 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3027 if ($matches[1] != "")
3028 $profile = $matches[1];
3032 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3033 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
3037 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3038 if ($matches[1] != "")
3039 $link = $matches[1];
3041 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3042 if ($matches[1] != "")
3043 $link = $matches[1];
3045 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3046 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
3053 * @brief Create an event array
3055 * @param integer $event_id The id of the event
3057 * @return array with event data
3059 private static function build_event($event_id) {
3061 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3062 if (!dbm::is_result($r)) {
3068 $eventdata = array();
3070 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3071 if (!dbm::is_result($r)) {
3077 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3078 if (!dbm::is_result($r)) {
3084 $eventdata['author'] = self::my_handle($owner);
3086 if ($event['guid']) {
3087 $eventdata['guid'] = $event['guid'];
3090 $mask = 'Y-m-d\TH:i:s\Z';
3092 /// @todo - establish "all day" events in Friendica
3093 $eventdata["all_day"] = "false";
3095 if (!$event['adjust']) {
3096 $eventdata['timezone'] = $user['timezone'];
3098 if ($eventdata['timezone'] == "") {
3099 $eventdata['timezone'] = 'UTC';
3103 if ($event['start']) {
3104 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3106 if ($event['finish'] AND !$event['nofinish']) {
3107 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3109 if ($event['summary']) {
3110 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3112 if ($event['desc']) {
3113 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3115 if ($event['location']) {
3116 $location = array();
3117 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3118 $location["lat"] = 0;
3119 $location["lng"] = 0;
3120 $eventdata['location'] = $location;
3127 * @brief Create a post (status message or reshare)
3129 * @param array $item The item that will be exported
3130 * @param array $owner the array of the item owner
3133 * 'type' -> Message type ("status_message" or "reshare")
3134 * 'message' -> Array of XML elements of the status
3136 public static function build_status($item, $owner) {
3138 $cachekey = "diaspora:build_status:".$item['guid'];
3140 $result = Cache::get($cachekey);
3141 if (!is_null($result)) {
3145 $myaddr = self::my_handle($owner);
3147 $public = (($item["private"]) ? "false" : "true");
3149 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3151 // Detect a share element and do a reshare
3152 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3153 $message = array("root_diaspora_id" => $ret["root_handle"],
3154 "root_guid" => $ret["root_guid"],
3155 "guid" => $item["guid"],
3156 "diaspora_handle" => $myaddr,
3157 "public" => $public,
3158 "created_at" => $created,
3159 "provider_display_name" => $item["app"]);
3163 $title = $item["title"];
3164 $body = $item["body"];
3166 // convert to markdown
3167 $body = html_entity_decode(bb2diaspora($body));
3171 $body = "## ".html_entity_decode($title)."\n\n".$body;
3173 if ($item["attach"]) {
3174 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3176 $body .= "\n".t("Attachments:")."\n";
3177 foreach ($matches as $mtch)
3178 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3182 $location = array();
3184 if ($item["location"] != "")
3185 $location["address"] = $item["location"];
3187 if ($item["coord"] != "") {
3188 $coord = explode(" ", $item["coord"]);
3189 $location["lat"] = $coord[0];
3190 $location["lng"] = $coord[1];
3193 $message = array("raw_message" => $body,
3194 "location" => $location,
3195 "guid" => $item["guid"],
3196 "diaspora_handle" => $myaddr,
3197 "public" => $public,
3198 "created_at" => $created,
3199 "provider_display_name" => $item["app"]);
3201 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3202 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3203 unset($message["location"]);
3206 if ($item['event-id'] > 0) {
3207 $event = self::build_event($item['event-id']);
3208 if (count($event)) {
3209 $message['event'] = $event;
3211 /// @todo Once Diaspora supports it, we will remove the body
3212 // $message['raw_message'] = '';
3216 $type = "status_message";
3219 $msg = array("type" => $type, "message" => $message);
3221 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3227 * @brief Sends a post
3229 * @param array $item The item that will be exported
3230 * @param array $owner the array of the item owner
3231 * @param array $contact Target of the communication
3232 * @param bool $public_batch Is it a public post?
3234 * @return int The result of the transmission
3236 public static function send_status($item, $owner, $contact, $public_batch = false) {
3238 $status = self::build_status($item, $owner);
3240 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3244 * @brief Creates a "like" object
3246 * @param array $item The item that will be exported
3247 * @param array $owner the array of the item owner
3249 * @return array The data for a "like"
3251 private static function construct_like($item, $owner) {
3253 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3254 dbesc($item["thr-parent"]));
3255 if (!dbm::is_result($p))
3260 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3261 if ($item['verb'] === ACTIVITY_LIKE) {
3263 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3264 $positive = "false";
3267 return(array("positive" => $positive,
3268 "guid" => $item["guid"],
3269 "target_type" => $target_type,
3270 "parent_guid" => $parent["guid"],
3271 "author_signature" => "",
3272 "diaspora_handle" => self::my_handle($owner)));
3276 * @brief Creates an "EventParticipation" object
3278 * @param array $item The item that will be exported
3279 * @param array $owner the array of the item owner
3281 * @return array The data for an "EventParticipation"
3283 private static function construct_attend($item, $owner) {
3285 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3286 dbesc($item["thr-parent"]));
3287 if (!dbm::is_result($p))
3292 switch ($item['verb']) {
3293 case ACTIVITY_ATTEND:
3294 $attend_answer = 'accepted';
3296 case ACTIVITY_ATTENDNO:
3297 $attend_answer = 'declined';
3299 case ACTIVITY_ATTENDMAYBE:
3300 $attend_answer = 'tentative';
3303 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3307 return(array("author" => self::my_handle($owner),
3308 "guid" => $item["guid"],
3309 "parent_guid" => $parent["guid"],
3310 "status" => $attend_answer,
3311 "author_signature" => ""));
3315 * @brief Creates the object for a comment
3317 * @param array $item The item that will be exported
3318 * @param array $owner the array of the item owner
3320 * @return array The data for a comment
3322 private static function construct_comment($item, $owner) {
3324 $cachekey = "diaspora:construct_comment:".$item['guid'];
3326 $result = Cache::get($cachekey);
3327 if (!is_null($result)) {
3331 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3332 intval($item["parent"]),
3333 intval($item["parent"])
3336 if (!dbm::is_result($p))
3341 $text = html_entity_decode(bb2diaspora($item["body"]));
3342 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3344 $comment = array("guid" => $item["guid"],
3345 "parent_guid" => $parent["guid"],
3346 "author_signature" => "",
3348 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3349 "diaspora_handle" => self::my_handle($owner));
3351 // Send the thread parent guid only if it is a threaded comment
3352 if ($item['thr-parent'] != $item['parent-uri']) {
3353 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3356 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3362 * @brief Send a like or a comment
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_followup($item,$owner,$contact,$public_batch = false) {
3373 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3374 $message = self::construct_attend($item, $owner);
3375 $type = "event_participation";
3376 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3377 $message = self::construct_like($item, $owner);
3380 $message = self::construct_comment($item, $owner);
3387 $message["author_signature"] = self::signature($owner, $message);
3389 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3393 * @brief Creates a message from a signature record entry
3395 * @param array $item The item that will be exported
3396 * @param array $signature The entry of the "sign" record
3398 * @return string The message
3400 private static function message_from_signature($item, $signature) {
3402 // Split the signed text
3403 $signed_parts = explode(";", $signature['signed_text']);
3405 if ($item["deleted"])
3406 $message = array("parent_author_signature" => "",
3407 "target_guid" => $signed_parts[0],
3408 "target_type" => $signed_parts[1],
3409 "sender_handle" => $signature['signer'],
3410 "target_author_signature" => $signature['signature']);
3411 elseif ($item['verb'] === ACTIVITY_LIKE)
3412 $message = array("positive" => $signed_parts[0],
3413 "guid" => $signed_parts[1],
3414 "target_type" => $signed_parts[2],
3415 "parent_guid" => $signed_parts[3],
3416 "parent_author_signature" => "",
3417 "author_signature" => $signature['signature'],
3418 "diaspora_handle" => $signed_parts[4]);
3420 // Remove the comment guid
3421 $guid = array_shift($signed_parts);
3423 // Remove the parent guid
3424 $parent_guid = array_shift($signed_parts);
3426 // Remove the handle
3427 $handle = array_pop($signed_parts);
3429 // Glue the parts together
3430 $text = implode(";", $signed_parts);
3432 $message = array("guid" => $guid,
3433 "parent_guid" => $parent_guid,
3434 "parent_author_signature" => "",
3435 "author_signature" => $signature['signature'],
3436 "text" => implode(";", $signed_parts),
3437 "diaspora_handle" => $handle);
3443 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3445 * @param array $item The item that will be exported
3446 * @param array $owner the array of the item owner
3447 * @param array $contact Target of the communication
3448 * @param bool $public_batch Is it a public post?
3450 * @return int The result of the transmission
3452 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3454 if ($item["deleted"])
3455 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3456 elseif ($item['verb'] === ACTIVITY_LIKE)
3461 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3463 // fetch the original signature
3465 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3466 intval($item["id"]));
3469 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3475 // Old way - is used by the internal Friendica functions
3476 /// @todo Change all signatur storing functions to the new format
3477 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3478 $message = self::message_from_signature($item, $signature);
3480 $msg = json_decode($signature['signed_text'], true);
3483 if (is_array($msg)) {
3484 foreach ($msg AS $field => $data) {
3485 if (!$item["deleted"]) {
3486 if ($field == "author")
3487 $field = "diaspora_handle";
3488 if ($field == "parent_type")
3489 $field = "target_type";
3492 $message[$field] = $data;
3495 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3498 $message["parent_author_signature"] = self::signature($owner, $message);
3500 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3502 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3506 * @brief Sends a retraction (deletion) of a message, like or comment
3508 * @param array $item The item that will be exported
3509 * @param array $owner the array of the item owner
3510 * @param array $contact Target of the communication
3511 * @param bool $public_batch Is it a public post?
3512 * @param bool $relay Is the retraction transmitted from a relay?
3514 * @return int The result of the transmission
3516 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3518 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3520 // Check whether the retraction is for a top-level post or whether it's a relayable
3521 if ($item["uri"] !== $item["parent-uri"]) {
3522 $msg_type = "relayable_retraction";
3523 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3525 $msg_type = "signed_retraction";
3526 $target_type = "StatusMessage";
3529 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3530 $signature = "parent_author_signature";
3532 $signature = "target_author_signature";
3534 $signed_text = $item["guid"].";".$target_type;
3536 $message = array("target_guid" => $item['guid'],
3537 "target_type" => $target_type,
3538 "sender_handle" => $itemaddr,
3539 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3541 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3543 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3547 * @brief Sends a mail
3549 * @param array $item The item that will be exported
3550 * @param array $owner The owner
3551 * @param array $contact Target of the communication
3553 * @return int The result of the transmission
3555 public static function send_mail($item, $owner, $contact) {
3557 $myaddr = self::my_handle($owner);
3559 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3560 intval($item["convid"]),
3561 intval($item["uid"])
3564 if (!dbm::is_result($r)) {
3565 logger("conversation not found.");
3571 "guid" => $cnv["guid"],
3572 "subject" => $cnv["subject"],
3573 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3574 "diaspora_handle" => $cnv["creator"],
3575 "participant_handles" => $cnv["recips"]
3578 $body = bb2diaspora($item["body"]);
3579 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3581 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3582 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3585 "guid" => $item["guid"],
3586 "parent_guid" => $cnv["guid"],
3587 "parent_author_signature" => $sig,
3588 "author_signature" => $sig,
3590 "created_at" => $created,
3591 "diaspora_handle" => $myaddr,
3592 "conversation_guid" => $cnv["guid"]
3595 if ($item["reply"]) {
3599 $message = array("guid" => $cnv["guid"],
3600 "subject" => $cnv["subject"],
3601 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3603 "diaspora_handle" => $cnv["creator"],
3604 "participant_handles" => $cnv["recips"]);
3606 $type = "conversation";
3609 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3613 * @brief Sends profile data
3615 * @param int $uid The user id
3617 public static function send_profile($uid, $recips = false) {
3623 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3624 AND `uid` = %d AND `rel` != %d",
3625 dbesc(NETWORK_DIASPORA),
3627 intval(CONTACT_IS_SHARING)
3632 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3634 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3635 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3636 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3645 $handle = $profile["addr"];
3646 $first = ((strpos($profile['name'],' ')
3647 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3648 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3649 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3650 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3651 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3652 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3654 if ($searchable === 'true') {
3655 $dob = '1000-00-00';
3657 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3658 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3660 $about = $profile['about'];
3661 $about = strip_tags(bbcode($about));
3663 $location = formatted_location($profile);
3665 if ($profile['pub_keywords']) {
3666 $kw = str_replace(',',' ',$profile['pub_keywords']);
3667 $kw = str_replace(' ',' ',$kw);
3668 $arr = explode(' ',$profile['pub_keywords']);
3670 for ($x = 0; $x < 5; $x ++) {
3672 $tags .= '#'. trim($arr[$x]) .' ';
3676 $tags = trim($tags);
3679 $message = array("diaspora_handle" => $handle,
3680 "first_name" => $first,
3681 "last_name" => $last,
3682 "image_url" => $large,
3683 "image_url_medium" => $medium,
3684 "image_url_small" => $small,
3686 "gender" => $profile['gender'],
3688 "location" => $location,
3689 "searchable" => $searchable,
3690 "tag_string" => $tags);
3692 foreach ($recips as $recip) {
3693 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3694 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3699 * @brief Stores the signature for likes that are created on our system
3701 * @param array $contact The contact array of the "like"
3702 * @param int $post_id The post id of the "like"
3704 * @return bool Success
3706 public static function store_like_signature($contact, $post_id) {
3708 // Is the contact the owner? Then fetch the private key
3709 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3710 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3714 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3715 if (!dbm::is_result($r)) {
3719 $contact["uprvkey"] = $r[0]['prvkey'];
3721 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3722 if (!dbm::is_result($r)) {
3726 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3730 $message = self::construct_like($r[0], $contact);
3731 $message["author_signature"] = self::signature($contact, $message);
3733 // We now store the signature more flexible to dynamically support new fields.
3734 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3735 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3736 intval($message_id),
3737 dbesc(json_encode($message))
3740 logger('Stored diaspora like signature');
3745 * @brief Stores the signature for comments that are created on our system
3747 * @param array $item The item array of the comment
3748 * @param array $contact The contact array of the item owner
3749 * @param string $uprvkey The private key of the sender
3750 * @param int $message_id The message id of the comment
3752 * @return bool Success
3754 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3756 if ($uprvkey == "") {
3757 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3761 $contact["uprvkey"] = $uprvkey;
3763 $message = self::construct_comment($item, $contact);
3764 $message["author_signature"] = self::signature($contact, $message);
3766 // We now store the signature more flexible to dynamically support new fields.
3767 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3768 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3769 intval($message_id),
3770 dbesc(json_encode($message))
3773 logger('Stored diaspora comment signature');