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 in the new format
192 * @param array $importer Array of the importer user
193 * @param string $raw raw post message
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_raw($importer, $raw) {
201 $data = json_decode($raw);
203 // Is it a private post? Then decrypt the outer Salmon
204 if (is_object($data)) {
205 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
206 $ciphertext = base64_decode($data->encrypted_magic_envelope);
208 $outer_key_bundle = '';
209 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
210 $j_outer_key_bundle = json_decode($outer_key_bundle);
212 if (!is_object($j_outer_key_bundle)) {
213 logger('Outer Salmon did not verify. Discarding.');
214 http_status_exit(400);
217 $outer_iv = base64_decode($j_outer_key_bundle->iv);
218 $outer_key = base64_decode($j_outer_key_bundle->key);
220 $xml = diaspora::aes_decrypt($outer_key, $outer_iv, $ciphertext);
225 $basedom = parse_xml_string($xml);
227 if (!is_object($basedom)) {
228 logger('Received data does not seem to be an XML. Discarding.');
229 http_status_exit(400);
232 $base = $basedom->children(NAMESPACE_SALMON_ME);
234 // Not sure if this cleaning is needed
235 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
237 // Build the signed data
238 $type = $base->data[0]->attributes()->type[0];
239 $encoding = $base->encoding;
241 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
243 // This is the signature
244 $signature = base64url_decode($base->sig);
246 // Get the senders' public key
247 $key_id = $base->sig[0]->attributes()->key_id[0];
248 $author_addr = base64_decode($key_id);
249 $key = diaspora::key($author_addr);
251 $verify = rsa_verify($signed_data, $signature, $key);
253 logger('Message did not verify. Discarding.');
254 http_status_exit(400);
257 return array('message' => (string)base64url_decode($base->data),
258 'author' => unxmlify($author_addr),
259 'key' => (string)$key);
263 * @brief: Decodes incoming Diaspora message in the deprecated format
265 * @param array $importer Array of the importer user
266 * @param string $xml urldecoded Diaspora salmon
269 * 'message' -> decoded Diaspora XML message
270 * 'author' -> author diaspora handle
271 * 'key' -> author public key (converted to pkcs#8)
273 public static function decode($importer, $xml) {
276 $basedom = parse_xml_string($xml);
278 if (!is_object($basedom)) {
279 logger("XML is not parseable.");
282 $children = $basedom->children('https://joindiaspora.com/protocol');
284 if ($children->header) {
286 $author_link = str_replace('acct:','',$children->header->author_id);
289 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
291 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
292 $ciphertext = base64_decode($encrypted_header->ciphertext);
294 $outer_key_bundle = '';
295 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
297 $j_outer_key_bundle = json_decode($outer_key_bundle);
299 $outer_iv = base64_decode($j_outer_key_bundle->iv);
300 $outer_key = base64_decode($j_outer_key_bundle->key);
302 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
304 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
305 $idom = parse_xml_string($decrypted,false);
307 $inner_iv = base64_decode($idom->iv);
308 $inner_aes_key = base64_decode($idom->aes_key);
310 $author_link = str_replace('acct:','',$idom->author_id);
313 $dom = $basedom->children(NAMESPACE_SALMON_ME);
315 // figure out where in the DOM tree our data is hiding
317 if ($dom->provenance->data)
318 $base = $dom->provenance;
319 elseif ($dom->env->data)
325 logger('unable to locate salmon data in xml');
326 http_status_exit(400);
330 // Stash the signature away for now. We have to find their key or it won't be good for anything.
331 $signature = base64url_decode($base->sig);
335 // strip whitespace so our data element will return to one big base64 blob
336 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
339 // stash away some other stuff for later
341 $type = $base->data[0]->attributes()->type[0];
342 $keyhash = $base->sig[0]->attributes()->keyhash[0];
343 $encoding = $base->encoding;
347 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
351 $data = base64url_decode($data);
355 $inner_decrypted = $data;
358 // Decode the encrypted blob
360 $inner_encrypted = base64_decode($data);
361 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
365 logger('Could not retrieve author URI.');
366 http_status_exit(400);
368 // Once we have the author URI, go to the web and try to find their public key
369 // (first this will look it up locally if it is in the fcontact cache)
370 // This will also convert diaspora public key from pkcs#1 to pkcs#8
372 logger('Fetching key for '.$author_link);
373 $key = self::key($author_link);
376 logger('Could not retrieve author key.');
377 http_status_exit(400);
380 $verify = rsa_verify($signed_data,$signature,$key);
383 logger('Message did not verify. Discarding.');
384 http_status_exit(400);
387 logger('Message verified.');
389 return array('message' => (string)$inner_decrypted,
390 'author' => unxmlify($author_link),
391 'key' => (string)$key);
396 * @brief Dispatches public messages and find the fitting receivers
398 * @param array $msg The post that will be dispatched
400 * @return int The message id of the generated message, "true" or "false" if there was an error
402 public static function dispatch_public($msg) {
404 $enabled = intval(get_config("system", "diaspora_enabled"));
406 logger("diaspora is disabled");
410 if (!($postdata = self::valid_posting($msg))) {
411 logger("Invalid posting");
415 $fields = $postdata['fields'];
417 // Is it a an action (comment, like, ...) for our own post?
418 if (isset($fields->parent_guid) AND !$postdata["relayed"]) {
419 $guid = notags(unxmlify($fields->parent_guid));
420 $importer = self::importer_for_guid($guid);
421 if (is_array($importer)) {
422 logger("delivering to origin: ".$importer["name"]);
423 $message_id = self::dispatch($importer, $msg, $fields);
428 // Now distribute it to the followers
429 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
430 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
431 AND NOT `account_expired` AND NOT `account_removed`",
432 dbesc(NETWORK_DIASPORA),
433 dbesc($msg["author"])
436 if (dbm::is_result($r)) {
437 foreach ($r as $rr) {
438 logger("delivering to: ".$rr["username"]);
439 self::dispatch($rr, $msg, $fields);
441 } elseif (!Config::get('system', 'relay_subscribe', false)) {
442 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
444 // Use a dummy importer to import the data for the public copy
445 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
446 $message_id = self::dispatch($importer, $msg, $fields);
453 * @brief Dispatches the different message types to the different functions
455 * @param array $importer Array of the importer user
456 * @param array $msg The post that will be dispatched
457 * @param object $fields SimpleXML object that contains the message
459 * @return int The message id of the generated message, "true" or "false" if there was an error
461 public static function dispatch($importer, $msg, $fields = null) {
463 // The sender is the handle of the contact that sent the message.
464 // This will often be different with relayed messages (for example "like" and "comment")
465 $sender = $msg["author"];
467 // This is only needed for private postings since this is already done for public ones before
468 if (is_null($fields)) {
469 if (!($postdata = self::valid_posting($msg))) {
470 logger("Invalid posting");
473 $fields = $postdata['fields'];
476 $type = $fields->getName();
478 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
481 case "account_deletion":
482 return self::receive_account_deletion($importer, $fields);
485 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
488 return self::receive_contact_request($importer, $fields);
491 return self::receive_conversation($importer, $msg, $fields);
494 return self::receive_like($importer, $sender, $fields);
497 return self::receive_message($importer, $fields);
499 case "participation": // Not implemented
500 return self::receive_participation($importer, $fields);
502 case "photo": // Not implemented
503 return self::receive_photo($importer, $fields);
505 case "poll_participation": // Not implemented
506 return self::receive_poll_participation($importer, $fields);
509 return self::receive_profile($importer, $fields);
512 return self::receive_reshare($importer, $fields, $msg["message"]);
515 return self::receive_retraction($importer, $sender, $fields);
517 case "status_message":
518 return self::receive_status_message($importer, $fields, $msg["message"]);
521 logger("Unknown message type ".$type);
529 * @brief Checks if a posting is valid and fetches the data fields.
531 * This function does not only check the signature.
532 * It also does the conversion between the old and the new diaspora format.
534 * @param array $msg Array with the XML, the sender handle and the sender signature
536 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
538 private static function valid_posting($msg) {
540 $data = parse_xml_string($msg["message"], false);
542 if (!is_object($data)) {
543 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
547 $first_child = $data->getName();
549 // Is this the new or the old version?
550 if ($data->getName() == "XML") {
552 foreach ($data->post->children() as $child)
559 $type = $element->getName();
562 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
564 // All retractions are handled identically from now on.
565 // In the new version there will only be "retraction".
566 if (in_array($type, array("signed_retraction", "relayable_retraction")))
567 $type = "retraction";
569 if ($type == "request")
572 $fields = new SimpleXMLElement("<".$type."/>");
576 foreach ($element->children() AS $fieldname => $entry) {
578 // Translation for the old XML structure
579 if ($fieldname == "diaspora_handle") {
580 $fieldname = "author";
582 if ($fieldname == "participant_handles") {
583 $fieldname = "participants";
585 if (in_array($type, array("like", "participation"))) {
586 if ($fieldname == "target_type") {
587 $fieldname = "parent_type";
590 if ($fieldname == "sender_handle") {
591 $fieldname = "author";
593 if ($fieldname == "recipient_handle") {
594 $fieldname = "recipient";
596 if ($fieldname == "root_diaspora_id") {
597 $fieldname = "root_author";
599 if ($type == "status_message") {
600 if ($fieldname == "raw_message") {
604 if ($type == "retraction") {
605 if ($fieldname == "post_guid") {
606 $fieldname = "target_guid";
608 if ($fieldname == "type") {
609 $fieldname = "target_type";
614 if (($fieldname == "author_signature") AND ($entry != ""))
615 $author_signature = base64_decode($entry);
616 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
617 $parent_author_signature = base64_decode($entry);
618 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
619 if ($signed_data != "") {
621 $signed_data_parent .= ";";
624 $signed_data .= $entry;
626 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
627 ($orig_type == "relayable_retraction"))
628 xml::copy($entry, $fields, $fieldname);
631 // This is something that shouldn't happen at all.
632 if (in_array($type, array("status_message", "reshare", "profile")))
633 if ($msg["author"] != $fields->author) {
634 logger("Message handle is not the same as envelope sender. Quitting this message.");
638 // Only some message types have signatures. So we quit here for the other types.
639 if (!in_array($type, array("comment", "like"))) {
640 return array("fields" => $fields, "relayed" => false);
642 // No author_signature? This is a must, so we quit.
643 if (!isset($author_signature)) {
644 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
648 if (isset($parent_author_signature)) {
651 $key = self::key($msg["author"]);
653 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
654 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);
661 $key = self::key($fields->author);
663 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
664 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
667 return array("fields" => $fields, "relayed" => $relayed);
672 * @brief Fetches the public key for a given handle
674 * @param string $handle The handle
676 * @return string The public key
678 private static function key($handle) {
679 $handle = strval($handle);
681 logger("Fetching diaspora key for: ".$handle);
683 $r = self::person_by_handle($handle);
691 * @brief Fetches data for a given handle
693 * @param string $handle The handle
695 * @return array the queried data
697 public static function person_by_handle($handle) {
699 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
700 dbesc(NETWORK_DIASPORA),
705 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
707 // update record occasionally so it doesn't get stale
708 $d = strtotime($person["updated"]." +00:00");
709 if ($d < strtotime("now - 14 days"))
712 if ($person["guid"] == "")
716 if (!$person OR $update) {
717 logger("create or refresh", LOGGER_DEBUG);
718 $r = probe_url($handle, PROBE_DIASPORA);
720 // Note that Friendica contacts will return a "Diaspora person"
721 // if Diaspora connectivity is enabled on their server
722 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
723 self::add_fcontact($r, $update);
731 * @brief Updates the fcontact table
733 * @param array $arr The fcontact data
734 * @param bool $update Update or insert?
736 * @return string The id of the fcontact entry
738 private static function add_fcontact($arr, $update = false) {
741 $r = q("UPDATE `fcontact` SET
755 WHERE `url` = '%s' AND `network` = '%s'",
757 dbesc($arr["photo"]),
758 dbesc($arr["request"]),
760 dbesc(strtolower($arr["addr"])),
762 dbesc($arr["batch"]),
763 dbesc($arr["notify"]),
765 dbesc($arr["confirm"]),
766 dbesc($arr["alias"]),
767 dbesc($arr["pubkey"]),
768 dbesc(datetime_convert()),
770 dbesc($arr["network"])
773 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
774 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
775 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
778 dbesc($arr["photo"]),
779 dbesc($arr["request"]),
783 dbesc($arr["batch"]),
784 dbesc($arr["notify"]),
786 dbesc($arr["confirm"]),
787 dbesc($arr["network"]),
788 dbesc($arr["alias"]),
789 dbesc($arr["pubkey"]),
790 dbesc(datetime_convert())
798 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
800 * @param int $contact_id The id in the contact table
801 * @param int $gcontact_id The id in the gcontact table
803 * @return string the handle
805 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
808 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
810 if ($gcontact_id != 0) {
811 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
812 intval($gcontact_id));
814 if (dbm::is_result($r)) {
815 return strtolower($r[0]["addr"]);
819 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
820 intval($contact_id));
822 if (dbm::is_result($r)) {
825 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
827 if ($contact['addr'] != "") {
828 $handle = $contact['addr'];
830 $baseurl_start = strpos($contact['url'],'://') + 3;
831 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
832 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
833 $handle = $contact['nick'].'@'.$baseurl;
837 return strtolower($handle);
841 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
844 * @param mixed $fcontact_guid Hexadecimal string guid
846 * @return string the contact url or null
848 public static function url_from_contact_guid($fcontact_guid) {
849 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
851 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
852 dbesc(NETWORK_DIASPORA),
853 dbesc($fcontact_guid)
856 if (dbm::is_result($r)) {
864 * @brief Get a contact id for a given handle
866 * @param int $uid The user id
867 * @param string $handle The handle in the format user@domain.tld
869 * @return The contact id
871 private static function contact_by_handle($uid, $handle) {
873 // First do a direct search on the contact table
874 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
879 if (dbm::is_result($r)) {
882 // We haven't found it?
883 // We use another function for it that will possibly create a contact entry
884 $cid = get_contact($handle, $uid);
887 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
889 if (dbm::is_result($r)) {
895 $handle_parts = explode("@", $handle);
896 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
897 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
902 if (dbm::is_result($r)) {
906 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
911 * @brief Check if posting is allowed for this contact
913 * @param array $importer Array of the importer user
914 * @param array $contact The contact that is checked
915 * @param bool $is_comment Is the check for a comment?
917 * @return bool is the contact allowed to post?
919 private static function post_allow($importer, $contact, $is_comment = false) {
921 // perhaps we were already sharing with this person. Now they're sharing with us.
922 // That makes us friends.
923 // Normally this should have handled by getting a request - but this could get lost
924 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
925 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
926 intval(CONTACT_IS_FRIEND),
927 intval($contact["id"]),
928 intval($importer["uid"])
930 $contact["rel"] = CONTACT_IS_FRIEND;
931 logger("defining user ".$contact["nick"]." as friend");
934 // We don't seem to like that person
935 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
937 // We are following this person? Then it is okay
938 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
940 // Is it a post to a community? That's good
941 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
944 // Messages for the global users and comments are always accepted
945 if (($importer["uid"] == 0) || $is_comment) {
953 * @brief Fetches the contact id for a handle and checks if posting is allowed
955 * @param array $importer Array of the importer user
956 * @param string $handle The checked handle in the format user@domain.tld
957 * @param bool $is_comment Is the check for a comment?
959 * @return array The contact data
961 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
962 $contact = self::contact_by_handle($importer["uid"], $handle);
964 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
965 // If a contact isn't found, we accept it anyway if it is a comment
973 if (!self::post_allow($importer, $contact, $is_comment)) {
974 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
981 * @brief Does the message already exists on the system?
983 * @param int $uid The user id
984 * @param string $guid The guid of the message
986 * @return int|bool message id if the message already was stored into the system - or false.
988 private static function message_exists($uid, $guid) {
989 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
994 if (dbm::is_result($r)) {
995 logger("message ".$guid." already exists for user ".$uid);
1003 * @brief Checks for links to posts in a message
1005 * @param array $item The item array
1007 private static function fetch_guid($item) {
1008 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1009 function ($match) use ($item){
1010 return(self::fetch_guid_sub($match, $item));
1015 * @brief Checks for relative /people/* links in an item body to match local
1016 * contacts or prepends the remote host taken from the author link.
1018 * @param string $body The item body to replace links from
1019 * @param string $author_link The author link for missing local contact fallback
1021 * @return the replaced string
1023 public function replace_people_guid($body, $author_link) {
1024 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1025 function ($match) use ($author_link) {
1027 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1028 // 1 => '0123456789abcdef'
1030 $handle = self::url_from_contact_guid($match[1]);
1033 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1035 // No local match, restoring absolute remote URL from author scheme and host
1036 $author_url = parse_url($author_link);
1037 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1047 * @brief sub function of "fetch_guid" which checks for links in messages
1049 * @param array $match array containing a link that has to be checked for a message link
1050 * @param array $item The item array
1052 private static function fetch_guid_sub($match, $item) {
1053 if (!self::store_by_guid($match[1], $item["author-link"]))
1054 self::store_by_guid($match[1], $item["owner-link"]);
1058 * @brief Fetches an item with a given guid from a given server
1060 * @param string $guid the message guid
1061 * @param string $server The server address
1062 * @param int $uid The user id of the user
1064 * @return int the message id of the stored message or false
1066 private static function store_by_guid($guid, $server, $uid = 0) {
1067 $serverparts = parse_url($server);
1068 $server = $serverparts["scheme"]."://".$serverparts["host"];
1070 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1072 $msg = self::message($guid, $server);
1077 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1079 // Now call the dispatcher
1080 return self::dispatch_public($msg);
1084 * @brief Fetches a message from a server
1086 * @param string $guid message guid
1087 * @param string $server The url of the server
1088 * @param int $level Endless loop prevention
1091 * 'message' => The message XML
1092 * 'author' => The author handle
1093 * 'key' => The public key of the author
1095 private static function message($guid, $server, $level = 0) {
1100 // This will work for new Diaspora servers and Friendica servers from 3.5
1101 $source_url = $server."/fetch/post/".$guid;
1102 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1104 $envelope = fetch_url($source_url);
1106 logger("Envelope was fetched.", LOGGER_DEBUG);
1107 $x = self::verify_magic_envelope($envelope);
1109 logger("Envelope could not be verified.", LOGGER_DEBUG);
1111 logger("Envelope was verified.", LOGGER_DEBUG);
1115 // This will work for older Diaspora and Friendica servers
1117 $source_url = $server."/p/".$guid.".xml";
1118 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1120 $x = fetch_url($source_url);
1125 $source_xml = parse_xml_string($x, false);
1127 if (!is_object($source_xml))
1130 if ($source_xml->post->reshare) {
1131 // Reshare of a reshare - old Diaspora version
1132 logger("Message is a reshare", LOGGER_DEBUG);
1133 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1134 } elseif ($source_xml->getName() == "reshare") {
1135 // Reshare of a reshare - new Diaspora version
1136 logger("Message is a new reshare", LOGGER_DEBUG);
1137 return self::message($source_xml->root_guid, $server, ++$level);
1142 // Fetch the author - for the old and the new Diaspora version
1143 if ($source_xml->post->status_message->diaspora_handle)
1144 $author = (string)$source_xml->post->status_message->diaspora_handle;
1145 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1146 $author = (string)$source_xml->author;
1148 // If this isn't a "status_message" then quit
1150 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1154 $msg = array("message" => $x, "author" => $author);
1156 $msg["key"] = self::key($msg["author"]);
1162 * @brief Fetches the item record of a given guid
1164 * @param int $uid The user id
1165 * @param string $guid message guid
1166 * @param string $author The handle of the item
1167 * @param array $contact The contact of the item owner
1169 * @return array the item record
1171 private static function parent_item($uid, $guid, $author, $contact) {
1172 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1173 `author-name`, `author-link`, `author-avatar`,
1174 `owner-name`, `owner-link`, `owner-avatar`
1175 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1176 intval($uid), dbesc($guid));
1179 $result = self::store_by_guid($guid, $contact["url"], $uid);
1182 $person = self::person_by_handle($author);
1183 $result = self::store_by_guid($guid, $person["url"], $uid);
1187 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1189 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1190 `author-name`, `author-link`, `author-avatar`,
1191 `owner-name`, `owner-link`, `owner-avatar`
1192 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1193 intval($uid), dbesc($guid));
1198 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1201 logger("parent item found: parent: ".$guid." - user: ".$uid);
1207 * @brief returns contact details
1209 * @param array $contact The default contact if the person isn't found
1210 * @param array $person The record of the person
1211 * @param int $uid The user id
1214 * 'cid' => contact id
1215 * 'network' => network type
1217 private static function author_contact_by_url($contact, $person, $uid) {
1219 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1220 dbesc(normalise_link($person["url"])), intval($uid));
1223 $network = $r[0]["network"];
1225 // We are receiving content from a user that possibly is about to be terminated
1226 // This means the user is vital, so we remove a possible termination date.
1227 unmark_for_death($r[0]);
1229 $cid = $contact["id"];
1230 $network = NETWORK_DIASPORA;
1233 return array("cid" => $cid, "network" => $network);
1237 * @brief Is the profile a hubzilla profile?
1239 * @param string $url The profile link
1241 * @return bool is it a hubzilla server?
1243 public static function is_redmatrix($url) {
1244 return(strstr($url, "/channel/"));
1248 * @brief Generate a post link with a given handle and message guid
1250 * @param string $addr The user handle
1251 * @param string $guid message guid
1253 * @return string the post link
1255 private static function plink($addr, $guid) {
1256 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1260 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1262 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1263 // So we try another way as well.
1264 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1266 $r[0]["network"] = $s[0]["network"];
1268 if ($r[0]["network"] == NETWORK_DFRN)
1269 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1271 if (self::is_redmatrix($r[0]["url"]))
1272 return $r[0]["url"]."/?f=&mid=".$guid;
1274 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1278 * @brief Processes an account deletion
1280 * @param array $importer Array of the importer user
1281 * @param object $data The message object
1283 * @return bool Success
1285 private static function receive_account_deletion($importer, $data) {
1287 /// @todo Account deletion should remove the contact from the global contacts as well
1289 $author = notags(unxmlify($data->author));
1291 $contact = self::contact_by_handle($importer["uid"], $author);
1293 logger("cannot find contact for author: ".$author);
1297 // We now remove the contact
1298 contact_remove($contact["id"]);
1303 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1305 * @param string $author Author handle
1306 * @param string $guid Message guid
1307 * @param boolean $onlyfound Only return uri when found in the database
1309 * @return string The constructed uri or the one from our database
1311 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1313 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1314 if (dbm::is_result($r)) {
1315 return $r[0]["uri"];
1316 } elseif (!$onlyfound) {
1317 return $author.":".$guid;
1324 * @brief Fetch the guid from our database with a given uri
1326 * @param string $author Author handle
1327 * @param string $uri Message uri
1329 * @return string The post guid
1331 private static function get_guid_from_uri($uri, $uid) {
1333 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1334 if (dbm::is_result($r)) {
1335 return $r[0]["guid"];
1342 * @brief Find the best importer for a comment, like, ...
1344 * @param string $guid The guid of the item
1346 * @return array|boolean the origin owner of that post - or false
1348 private static function importer_for_guid($guid) {
1349 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1351 if (dbm::is_result($item)) {
1352 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1353 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1354 if (dbm::is_result($contact)) {
1362 * @brief Processes an incoming comment
1364 * @param array $importer Array of the importer user
1365 * @param string $sender The sender of the message
1366 * @param object $data The message object
1367 * @param string $xml The original XML of the message
1369 * @return int The message id of the generated comment or "false" if there was an error
1371 private static function receive_comment($importer, $sender, $data, $xml) {
1372 $author = notags(unxmlify($data->author));
1373 $guid = notags(unxmlify($data->guid));
1374 $parent_guid = notags(unxmlify($data->parent_guid));
1375 $text = unxmlify($data->text);
1377 if (isset($data->created_at)) {
1378 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1380 $created_at = datetime_convert();
1383 if (isset($data->thread_parent_guid)) {
1384 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1385 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1390 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1395 $message_id = self::message_exists($importer["uid"], $guid);
1400 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1401 if (!$parent_item) {
1405 $person = self::person_by_handle($author);
1406 if (!is_array($person)) {
1407 logger("unable to find author details");
1411 // Fetch the contact id - if we know this contact
1412 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1414 $datarray = array();
1416 $datarray["uid"] = $importer["uid"];
1417 $datarray["contact-id"] = $author_contact["cid"];
1418 $datarray["network"] = $author_contact["network"];
1420 $datarray["author-name"] = $person["name"];
1421 $datarray["author-link"] = $person["url"];
1422 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1424 $datarray["owner-name"] = $contact["name"];
1425 $datarray["owner-link"] = $contact["url"];
1426 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1428 $datarray["guid"] = $guid;
1429 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1431 $datarray["type"] = "remote-comment";
1432 $datarray["verb"] = ACTIVITY_POST;
1433 $datarray["gravity"] = GRAVITY_COMMENT;
1435 if ($thr_uri != "") {
1436 $datarray["parent-uri"] = $thr_uri;
1438 $datarray["parent-uri"] = $parent_item["uri"];
1441 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1443 $datarray["protocol"] = PROTOCOL_DIASPORA;
1444 $datarray["source"] = $xml;
1446 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1448 $body = diaspora2bb($text);
1450 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1452 self::fetch_guid($datarray);
1454 $message_id = item_store($datarray);
1457 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1460 // If we are the origin of the parent we store the original data and notify our followers
1461 if ($message_id AND $parent_item["origin"]) {
1463 // Formerly we stored the signed text, the signature and the author in different fields.
1464 // We now store the raw data so that we are more flexible.
1465 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1466 intval($message_id),
1467 dbesc(json_encode($data))
1471 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1478 * @brief processes and stores private messages
1480 * @param array $importer Array of the importer user
1481 * @param array $contact The contact of the message
1482 * @param object $data The message object
1483 * @param array $msg Array of the processed message, author handle and key
1484 * @param object $mesg The private message
1485 * @param array $conversation The conversation record to which this message belongs
1487 * @return bool "true" if it was successful
1489 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1490 $author = notags(unxmlify($data->author));
1491 $guid = notags(unxmlify($data->guid));
1492 $subject = notags(unxmlify($data->subject));
1494 // "diaspora_handle" is the element name from the old version
1495 // "author" is the element name from the new version
1496 if ($mesg->author) {
1497 $msg_author = notags(unxmlify($mesg->author));
1498 } elseif ($mesg->diaspora_handle) {
1499 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1504 $msg_guid = notags(unxmlify($mesg->guid));
1505 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1506 $msg_text = unxmlify($mesg->text);
1507 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1509 if ($msg_conversation_guid != $guid) {
1510 logger("message conversation guid does not belong to the current conversation.");
1514 $body = diaspora2bb($msg_text);
1515 $message_uri = $msg_author.":".$msg_guid;
1517 $person = self::person_by_handle($msg_author);
1519 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1522 if (dbm::is_result($r)) {
1523 logger("duplicate message already delivered.", LOGGER_DEBUG);
1527 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1528 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1529 intval($importer["uid"]),
1531 intval($conversation["id"]),
1532 dbesc($person["name"]),
1533 dbesc($person["photo"]),
1534 dbesc($person["url"]),
1535 intval($contact["id"]),
1540 dbesc($message_uri),
1541 dbesc($author.":".$guid),
1542 dbesc($msg_created_at)
1545 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1546 dbesc(datetime_convert()),
1547 intval($conversation["id"])
1551 "type" => NOTIFY_MAIL,
1552 "notify_flags" => $importer["notify-flags"],
1553 "language" => $importer["language"],
1554 "to_name" => $importer["username"],
1555 "to_email" => $importer["email"],
1556 "uid" =>$importer["uid"],
1557 "item" => array("subject" => $subject, "body" => $body),
1558 "source_name" => $person["name"],
1559 "source_link" => $person["url"],
1560 "source_photo" => $person["thumb"],
1561 "verb" => ACTIVITY_POST,
1568 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1570 * @param array $importer Array of the importer user
1571 * @param array $msg Array of the processed message, author handle and key
1572 * @param object $data The message object
1574 * @return bool Success
1576 private static function receive_conversation($importer, $msg, $data) {
1577 $author = notags(unxmlify($data->author));
1578 $guid = notags(unxmlify($data->guid));
1579 $subject = notags(unxmlify($data->subject));
1580 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1581 $participants = notags(unxmlify($data->participants));
1583 $messages = $data->message;
1585 if (!count($messages)) {
1586 logger("empty conversation");
1590 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1594 $conversation = null;
1596 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1597 intval($importer["uid"]),
1601 $conversation = $c[0];
1603 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1604 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1605 intval($importer["uid"]),
1609 dbesc(datetime_convert()),
1611 dbesc($participants)
1614 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1615 intval($importer["uid"]),
1620 $conversation = $c[0];
1622 if (!$conversation) {
1623 logger("unable to create conversation.");
1627 foreach ($messages as $mesg)
1628 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1634 * @brief Creates the body for a "like" message
1636 * @param array $contact The contact that send us the "like"
1637 * @param array $parent_item The item array of the parent item
1638 * @param string $guid message guid
1640 * @return string the body
1642 private static function construct_like_body($contact, $parent_item, $guid) {
1643 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1645 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1646 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1647 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1649 return sprintf($bodyverb, $ulink, $alink, $plink);
1653 * @brief Creates a XML object for a "like"
1655 * @param array $importer Array of the importer user
1656 * @param array $parent_item The item array of the parent item
1658 * @return string The XML
1660 private static function construct_like_object($importer, $parent_item) {
1661 $objtype = ACTIVITY_OBJ_NOTE;
1662 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1663 $parent_body = $parent_item["body"];
1665 $xmldata = array("object" => array("type" => $objtype,
1667 "id" => $parent_item["uri"],
1670 "content" => $parent_body));
1672 return xml::from_array($xmldata, $xml, true);
1676 * @brief Processes "like" messages
1678 * @param array $importer Array of the importer user
1679 * @param string $sender The sender of the message
1680 * @param object $data The message object
1682 * @return int The message id of the generated like or "false" if there was an error
1684 private static function receive_like($importer, $sender, $data) {
1685 $author = notags(unxmlify($data->author));
1686 $guid = notags(unxmlify($data->guid));
1687 $parent_guid = notags(unxmlify($data->parent_guid));
1688 $parent_type = notags(unxmlify($data->parent_type));
1689 $positive = notags(unxmlify($data->positive));
1691 // likes on comments aren't supported by Diaspora - only on posts
1692 // But maybe this will be supported in the future, so we will accept it.
1693 if (!in_array($parent_type, array("Post", "Comment")))
1696 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1700 $message_id = self::message_exists($importer["uid"], $guid);
1704 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1708 $person = self::person_by_handle($author);
1709 if (!is_array($person)) {
1710 logger("unable to find author details");
1714 // Fetch the contact id - if we know this contact
1715 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1717 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1718 // We would accept this anyhow.
1719 if ($positive == "true")
1720 $verb = ACTIVITY_LIKE;
1722 $verb = ACTIVITY_DISLIKE;
1724 $datarray = array();
1726 $datarray["protocol"] = PROTOCOL_DIASPORA;
1728 $datarray["uid"] = $importer["uid"];
1729 $datarray["contact-id"] = $author_contact["cid"];
1730 $datarray["network"] = $author_contact["network"];
1732 $datarray["author-name"] = $person["name"];
1733 $datarray["author-link"] = $person["url"];
1734 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1736 $datarray["owner-name"] = $contact["name"];
1737 $datarray["owner-link"] = $contact["url"];
1738 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1740 $datarray["guid"] = $guid;
1741 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1743 $datarray["type"] = "activity";
1744 $datarray["verb"] = $verb;
1745 $datarray["gravity"] = GRAVITY_LIKE;
1746 $datarray["parent-uri"] = $parent_item["uri"];
1748 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1749 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1751 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1753 $message_id = item_store($datarray);
1756 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1758 // If we are the origin of the parent we store the original data and notify our followers
1759 if ($message_id AND $parent_item["origin"]) {
1761 // Formerly we stored the signed text, the signature and the author in different fields.
1762 // We now store the raw data so that we are more flexible.
1763 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1764 intval($message_id),
1765 dbesc(json_encode($data))
1769 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1776 * @brief Processes private messages
1778 * @param array $importer Array of the importer user
1779 * @param object $data The message object
1781 * @return bool Success?
1783 private static function receive_message($importer, $data) {
1784 $author = notags(unxmlify($data->author));
1785 $guid = notags(unxmlify($data->guid));
1786 $conversation_guid = notags(unxmlify($data->conversation_guid));
1787 $text = unxmlify($data->text);
1788 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1790 $contact = self::allowed_contact_by_handle($importer, $author, true);
1795 $conversation = null;
1797 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1798 intval($importer["uid"]),
1799 dbesc($conversation_guid)
1802 $conversation = $c[0];
1804 logger("conversation not available.");
1808 $message_uri = $author.":".$guid;
1810 $person = self::person_by_handle($author);
1812 logger("unable to find author details");
1816 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1817 dbesc($message_uri),
1818 intval($importer["uid"])
1820 if (dbm::is_result($r)) {
1821 logger("duplicate message already delivered.", LOGGER_DEBUG);
1825 $body = diaspora2bb($text);
1827 $body = self::replace_people_guid($body, $person["url"]);
1829 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1830 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1831 intval($importer["uid"]),
1833 intval($conversation["id"]),
1834 dbesc($person["name"]),
1835 dbesc($person["photo"]),
1836 dbesc($person["url"]),
1837 intval($contact["id"]),
1838 dbesc($conversation["subject"]),
1842 dbesc($message_uri),
1843 dbesc($author.":".$conversation["guid"]),
1847 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1848 dbesc(datetime_convert()),
1849 intval($conversation["id"])
1856 * @brief Processes participations - unsupported by now
1858 * @param array $importer Array of the importer user
1859 * @param object $data The message object
1861 * @return bool always true
1863 private static function receive_participation($importer, $data) {
1864 // I'm not sure if we can fully support this message type
1869 * @brief Processes photos - unneeded
1871 * @param array $importer Array of the importer user
1872 * @param object $data The message object
1874 * @return bool always true
1876 private static function receive_photo($importer, $data) {
1877 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1882 * @brief Processes poll participations - unssupported
1884 * @param array $importer Array of the importer user
1885 * @param object $data The message object
1887 * @return bool always true
1889 private static function receive_poll_participation($importer, $data) {
1890 // We don't support polls by now
1895 * @brief Processes incoming profile updates
1897 * @param array $importer Array of the importer user
1898 * @param object $data The message object
1900 * @return bool Success
1902 private static function receive_profile($importer, $data) {
1903 $author = strtolower(notags(unxmlify($data->author)));
1905 $contact = self::contact_by_handle($importer["uid"], $author);
1909 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1910 $image_url = unxmlify($data->image_url);
1911 $birthday = unxmlify($data->birthday);
1912 $gender = unxmlify($data->gender);
1913 $about = diaspora2bb(unxmlify($data->bio));
1914 $location = diaspora2bb(unxmlify($data->location));
1915 $searchable = (unxmlify($data->searchable) == "true");
1916 $nsfw = (unxmlify($data->nsfw) == "true");
1917 $tags = unxmlify($data->tag_string);
1919 $tags = explode("#", $tags);
1921 $keywords = array();
1922 foreach ($tags as $tag) {
1923 $tag = trim(strtolower($tag));
1928 $keywords = implode(", ", $keywords);
1930 $handle_parts = explode("@", $author);
1931 $nick = $handle_parts[0];
1934 $name = $handle_parts[0];
1936 if ( preg_match("|^https?://|", $image_url) === 0)
1937 $image_url = "http://".$handle_parts[1].$image_url;
1939 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1941 // Generic birthday. We don't know the timezone. The year is irrelevant.
1943 $birthday = str_replace("1000", "1901", $birthday);
1945 if ($birthday != "")
1946 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1948 // this is to prevent multiple birthday notifications in a single year
1949 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1951 if (substr($birthday,5) === substr($contact["bd"],5))
1952 $birthday = $contact["bd"];
1954 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1955 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1959 dbesc(datetime_convert()),
1965 intval($contact["id"]),
1966 intval($importer["uid"])
1969 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1970 "photo" => $image_url, "name" => $name, "location" => $location,
1971 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1972 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1973 "hide" => !$searchable, "nsfw" => $nsfw);
1975 $gcid = update_gcontact($gcontact);
1977 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1979 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1985 * @brief Processes incoming friend requests
1987 * @param array $importer Array of the importer user
1988 * @param array $contact The contact that send the request
1990 private static function receive_request_make_friend($importer, $contact) {
1994 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1995 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1996 intval(CONTACT_IS_FRIEND),
1997 intval($contact["id"]),
1998 intval($importer["uid"])
2001 // send notification
2003 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2004 intval($importer["uid"])
2007 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
2009 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2010 intval($importer["uid"])
2013 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2015 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2018 $arr["protocol"] = PROTOCOL_DIASPORA;
2019 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2020 $arr["uid"] = $importer["uid"];
2021 $arr["contact-id"] = $self[0]["id"];
2023 $arr["type"] = 'wall';
2024 $arr["gravity"] = 0;
2026 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2027 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2028 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2029 $arr["verb"] = ACTIVITY_FRIEND;
2030 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2032 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2033 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2034 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2035 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2037 $arr["object"] = self::construct_new_friend_object($contact);
2039 $arr["last-child"] = 1;
2041 $arr["allow_cid"] = $user[0]["allow_cid"];
2042 $arr["allow_gid"] = $user[0]["allow_gid"];
2043 $arr["deny_cid"] = $user[0]["deny_cid"];
2044 $arr["deny_gid"] = $user[0]["deny_gid"];
2046 $i = item_store($arr);
2048 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
2054 * @brief Creates a XML object for a "new friend" message
2056 * @param array $contact Array of the contact
2058 * @return string The XML
2060 private static function construct_new_friend_object($contact) {
2061 $objtype = ACTIVITY_OBJ_PERSON;
2062 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2063 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2065 $xmldata = array("object" => array("type" => $objtype,
2066 "title" => $contact["name"],
2067 "id" => $contact["url"]."/".$contact["name"],
2070 return xml::from_array($xmldata, $xml, true);
2074 * @brief Processes incoming sharing notification
2076 * @param array $importer Array of the importer user
2077 * @param object $data The message object
2079 * @return bool Success
2081 private static function receive_contact_request($importer, $data) {
2082 $author = unxmlify($data->author);
2083 $recipient = unxmlify($data->recipient);
2085 if (!$author || !$recipient) {
2089 // the current protocol version doesn't know these fields
2090 // That means that we will assume their existance
2091 if (isset($data->following)) {
2092 $following = (unxmlify($data->following) == "true");
2097 if (isset($data->sharing)) {
2098 $sharing = (unxmlify($data->sharing) == "true");
2103 $contact = self::contact_by_handle($importer["uid"],$author);
2105 // perhaps we were already sharing with this person. Now they're sharing with us.
2106 // That makes us friends.
2108 if ($following AND $sharing) {
2109 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
2110 self::receive_request_make_friend($importer, $contact);
2112 // refetch the contact array
2113 $contact = self::contact_by_handle($importer["uid"],$author);
2115 // If we are now friends, we are sending a share message.
2116 // Normally we needn't to do so, but the first message could have been vanished.
2117 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
2118 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2120 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2121 $ret = self::send_share($u[0], $contact);
2125 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2126 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2131 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2132 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2134 } elseif (!$following AND !$sharing) {
2135 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2137 } elseif (!$following AND $sharing) {
2138 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2139 } elseif ($following AND $sharing) {
2140 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2141 } elseif ($following AND !$sharing) {
2142 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2145 $ret = self::person_by_handle($author);
2147 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2148 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2152 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2154 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2155 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2156 intval($importer["uid"]),
2157 dbesc($ret["network"]),
2158 dbesc($ret["addr"]),
2161 dbesc(normalise_link($ret["url"])),
2163 dbesc($ret["name"]),
2164 dbesc($ret["nick"]),
2165 dbesc($ret["photo"]),
2166 dbesc($ret["pubkey"]),
2167 dbesc($ret["notify"]),
2168 dbesc($ret["poll"]),
2173 // find the contact record we just created
2175 $contact_record = self::contact_by_handle($importer["uid"],$author);
2177 if (!$contact_record) {
2178 logger("unable to locate newly created contact record.");
2182 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2184 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2186 if (intval($def_gid))
2187 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2189 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2191 if ($importer["page-flags"] == PAGE_NORMAL) {
2193 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2195 $hash = random_string().(string)time(); // Generate a confirm_key
2197 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2198 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2199 intval($importer["uid"]),
2200 intval($contact_record["id"]),
2203 dbesc(t("Sharing notification from Diaspora network")),
2205 dbesc(datetime_convert())
2209 // automatic friend approval
2211 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2213 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2215 // technically they are sharing with us (CONTACT_IS_SHARING),
2216 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2217 // we are going to change the relationship and make them a follower.
2219 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2220 $new_relation = CONTACT_IS_FRIEND;
2221 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2222 $new_relation = CONTACT_IS_SHARING;
2224 $new_relation = CONTACT_IS_FOLLOWER;
2226 $r = q("UPDATE `contact` SET `rel` = %d,
2234 intval($new_relation),
2235 dbesc(datetime_convert()),
2236 dbesc(datetime_convert()),
2237 intval($contact_record["id"])
2240 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2242 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2243 $ret = self::send_share($u[0], $contact_record);
2245 // Send the profile data, maybe it weren't transmitted before
2246 self::send_profile($importer["uid"], array($contact_record));
2254 * @brief Fetches a message with a given guid
2256 * @param string $guid message guid
2257 * @param string $orig_author handle of the original post
2258 * @param string $author handle of the sharer
2260 * @return array The fetched item
2262 private static function original_item($guid, $orig_author, $author) {
2264 // Do we already have this item?
2265 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2266 `author-name`, `author-link`, `author-avatar`
2267 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2270 if (dbm::is_result($r)) {
2271 logger("reshared message ".$guid." already exists on system.");
2273 // Maybe it is already a reshared item?
2274 // Then refetch the content, if it is a reshare from a reshare.
2275 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2276 if (self::is_reshare($r[0]["body"], true)) {
2278 } elseif (self::is_reshare($r[0]["body"], false)) {
2279 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2281 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2283 // Add OEmbed and other information to the body
2284 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2292 if (!dbm::is_result($r)) {
2293 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2294 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2295 $item_id = self::store_by_guid($guid, $server);
2298 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2299 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2300 $item_id = self::store_by_guid($guid, $server);
2304 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2305 `author-name`, `author-link`, `author-avatar`
2306 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2309 if (dbm::is_result($r)) {
2310 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2311 if (self::is_reshare($r[0]["body"], false)) {
2312 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2313 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2325 * @brief Processes a reshare message
2327 * @param array $importer Array of the importer user
2328 * @param object $data The message object
2329 * @param string $xml The original XML of the message
2331 * @return int the message id
2333 private static function receive_reshare($importer, $data, $xml) {
2334 $author = notags(unxmlify($data->author));
2335 $guid = notags(unxmlify($data->guid));
2336 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2337 $root_author = notags(unxmlify($data->root_author));
2338 $root_guid = notags(unxmlify($data->root_guid));
2339 /// @todo handle unprocessed property "provider_display_name"
2340 $public = notags(unxmlify($data->public));
2342 $contact = self::allowed_contact_by_handle($importer, $author, false);
2347 $message_id = self::message_exists($importer["uid"], $guid);
2352 $original_item = self::original_item($root_guid, $root_author, $author);
2353 if (!$original_item) {
2357 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2359 $datarray = array();
2361 $datarray["uid"] = $importer["uid"];
2362 $datarray["contact-id"] = $contact["id"];
2363 $datarray["network"] = NETWORK_DIASPORA;
2365 $datarray["author-name"] = $contact["name"];
2366 $datarray["author-link"] = $contact["url"];
2367 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2369 $datarray["owner-name"] = $datarray["author-name"];
2370 $datarray["owner-link"] = $datarray["author-link"];
2371 $datarray["owner-avatar"] = $datarray["author-avatar"];
2373 $datarray["guid"] = $guid;
2374 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2376 $datarray["verb"] = ACTIVITY_POST;
2377 $datarray["gravity"] = GRAVITY_PARENT;
2379 $datarray["protocol"] = PROTOCOL_DIASPORA;
2380 $datarray["source"] = $xml;
2382 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2383 $original_item["guid"], $original_item["created"], $orig_url);
2384 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2386 $datarray["tag"] = $original_item["tag"];
2387 $datarray["app"] = $original_item["app"];
2389 $datarray["plink"] = self::plink($author, $guid);
2390 $datarray["private"] = (($public == "false") ? 1 : 0);
2391 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2393 $datarray["object-type"] = $original_item["object-type"];
2395 self::fetch_guid($datarray);
2396 $message_id = item_store($datarray);
2399 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2406 * @brief Processes retractions
2408 * @param array $importer Array of the importer user
2409 * @param array $contact The contact of the item owner
2410 * @param object $data The message object
2412 * @return bool success
2414 private static function item_retraction($importer, $contact, $data) {
2415 $author = notags(unxmlify($data->author));
2416 $target_guid = notags(unxmlify($data->target_guid));
2417 $target_type = notags(unxmlify($data->target_type));
2419 $person = self::person_by_handle($author);
2420 if (!is_array($person)) {
2421 logger("unable to find author detail for ".$author);
2425 if (!isset($contact["url"])) {
2426 $contact["url"] = $person["url"];
2429 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2430 dbesc($target_guid),
2431 intval($importer["uid"])
2434 logger("Target guid ".$target_guid." was not found for user ".$importer["uid"]);
2438 // Check if the sender is the thread owner
2439 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2440 intval($r[0]["parent"]));
2442 // Only delete it if the parent author really fits
2443 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2444 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2448 // 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
2449 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2450 dbesc(datetime_convert()),
2451 dbesc(datetime_convert()),
2454 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2456 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2458 // Now check if the retraction needs to be relayed by us
2459 if ($p[0]["origin"]) {
2461 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2468 * @brief Receives retraction messages
2470 * @param array $importer Array of the importer user
2471 * @param string $sender The sender of the message
2472 * @param object $data The message object
2474 * @return bool Success
2476 private static function receive_retraction($importer, $sender, $data) {
2477 $target_type = notags(unxmlify($data->target_type));
2479 $contact = self::contact_by_handle($importer["uid"], $sender);
2480 if (!$contact AND (in_array($target_type, array("Contact", "Person")))) {
2481 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2485 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2487 switch ($target_type) {
2490 case "Post": // "Post" will be supported in a future version
2492 case "StatusMessage":
2493 return self::item_retraction($importer, $contact, $data);
2497 /// @todo What should we do with an "unshare"?
2498 // Removing the contact isn't correct since we still can read the public items
2499 contact_remove($contact["id"]);
2503 logger("Unknown target type ".$target_type);
2510 * @brief Receives status messages
2512 * @param array $importer Array of the importer user
2513 * @param object $data The message object
2514 * @param string $xml The original XML of the message
2516 * @return int The message id of the newly created item
2518 private static function receive_status_message($importer, $data, $xml) {
2519 $author = notags(unxmlify($data->author));
2520 $guid = notags(unxmlify($data->guid));
2521 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2522 $public = notags(unxmlify($data->public));
2523 $text = unxmlify($data->text);
2524 $provider_display_name = notags(unxmlify($data->provider_display_name));
2526 $contact = self::allowed_contact_by_handle($importer, $author, false);
2531 $message_id = self::message_exists($importer["uid"], $guid);
2537 if ($data->location) {
2538 foreach ($data->location->children() AS $fieldname => $data) {
2539 $address[$fieldname] = notags(unxmlify($data));
2543 $body = diaspora2bb($text);
2545 $datarray = array();
2547 // Attach embedded pictures to the body
2549 foreach ($data->photo AS $photo) {
2550 $body = "[img]".unxmlify($photo->remote_photo_path).
2551 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2554 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2556 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2558 // Add OEmbed and other information to the body
2559 if (!self::is_redmatrix($contact["url"])) {
2560 $body = add_page_info_to_body($body, false, true);
2564 /// @todo enable support for polls
2565 //if ($data->poll) {
2566 // foreach ($data->poll AS $poll)
2571 /// @todo enable support for events
2573 $datarray["uid"] = $importer["uid"];
2574 $datarray["contact-id"] = $contact["id"];
2575 $datarray["network"] = NETWORK_DIASPORA;
2577 $datarray["author-name"] = $contact["name"];
2578 $datarray["author-link"] = $contact["url"];
2579 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2581 $datarray["owner-name"] = $datarray["author-name"];
2582 $datarray["owner-link"] = $datarray["author-link"];
2583 $datarray["owner-avatar"] = $datarray["author-avatar"];
2585 $datarray["guid"] = $guid;
2586 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2588 $datarray["verb"] = ACTIVITY_POST;
2589 $datarray["gravity"] = GRAVITY_PARENT;
2591 $datarray["protocol"] = PROTOCOL_DIASPORA;
2592 $datarray["source"] = $xml;
2594 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2596 if ($provider_display_name != "") {
2597 $datarray["app"] = $provider_display_name;
2600 $datarray["plink"] = self::plink($author, $guid);
2601 $datarray["private"] = (($public == "false") ? 1 : 0);
2602 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2604 if (isset($address["address"])) {
2605 $datarray["location"] = $address["address"];
2608 if (isset($address["lat"]) AND isset($address["lng"])) {
2609 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2612 self::fetch_guid($datarray);
2613 $message_id = item_store($datarray);
2616 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2622 /* ************************************************************************************** *
2623 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2624 * ************************************************************************************** */
2627 * @brief returnes the handle of a contact
2629 * @param array $me contact array
2631 * @return string the handle in the format user@domain.tld
2633 private static function my_handle($contact) {
2634 if ($contact["addr"] != "") {
2635 return $contact["addr"];
2638 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2639 // So - just in case - we build the the address here.
2640 if ($contact["nickname"] != "") {
2641 $nick = $contact["nickname"];
2643 $nick = $contact["nick"];
2646 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2650 * @brief Creates the envelope for the "fetch" endpoint
2652 * @param string $msg The message that is to be transmitted
2653 * @param array $user The record of the sender
2655 * @return string The envelope
2658 public static function build_magic_envelope($msg, $user) {
2660 $b64url_data = base64url_encode($msg);
2661 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2663 $key_id = base64url_encode(self::my_handle($user));
2664 $type = "application/xml";
2665 $encoding = "base64url";
2666 $alg = "RSA-SHA256";
2667 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2668 $signature = rsa_sign($signable_data, $user["prvkey"]);
2669 $sig = base64url_encode($signature);
2671 $xmldata = array("me:env" => array("me:data" => $data,
2672 "@attributes" => array("type" => $type),
2673 "me:encoding" => $encoding,
2676 "@attributes2" => array("key_id" => $key_id)));
2678 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2680 return xml::from_array($xmldata, $xml, false, $namespaces);
2684 * @brief Creates the envelope for a public message
2686 * @param string $msg The message that is to be transmitted
2687 * @param array $user The record of the sender
2688 * @param array $contact Target of the communication
2689 * @param string $prvkey The private key of the sender
2690 * @param string $pubkey The public key of the receiver
2692 * @return string The envelope
2694 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2696 logger("Message: ".$msg, LOGGER_DATA);
2698 $handle = self::my_handle($user);
2700 $b64url_data = base64url_encode($msg);
2702 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2704 $type = "application/xml";
2705 $encoding = "base64url";
2706 $alg = "RSA-SHA256";
2708 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2710 $signature = rsa_sign($signable_data,$prvkey);
2711 $sig = base64url_encode($signature);
2713 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2714 "me:env" => array("me:encoding" => $encoding,
2717 "@attributes" => array("type" => $type),
2718 "me:sig" => $sig)));
2720 $namespaces = array("" => "https://joindiaspora.com/protocol",
2721 "me" => "http://salmon-protocol.org/ns/magic-env");
2723 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2725 logger("magic_env: ".$magic_env, LOGGER_DATA);
2730 * @brief Creates the envelope for a private message
2732 * @param string $msg The message that is to be transmitted
2733 * @param array $user The record of the sender
2734 * @param array $contact Target of the communication
2735 * @param string $prvkey The private key of the sender
2736 * @param string $pubkey The public key of the receiver
2738 * @return string The envelope
2740 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2742 logger("Message: ".$msg, LOGGER_DATA);
2744 // without a public key nothing will work
2747 logger("pubkey missing: contact id: ".$contact["id"]);
2751 $inner_aes_key = openssl_random_pseudo_bytes(32);
2752 $b_inner_aes_key = base64_encode($inner_aes_key);
2753 $inner_iv = openssl_random_pseudo_bytes(16);
2754 $b_inner_iv = base64_encode($inner_iv);
2756 $outer_aes_key = openssl_random_pseudo_bytes(32);
2757 $b_outer_aes_key = base64_encode($outer_aes_key);
2758 $outer_iv = openssl_random_pseudo_bytes(16);
2759 $b_outer_iv = base64_encode($outer_iv);
2761 $handle = self::my_handle($user);
2763 $inner_encrypted = self::aes_encrypt($inner_aes_key, $inner_iv, $msg);
2765 $b64_data = base64_encode($inner_encrypted);
2768 $b64url_data = base64url_encode($b64_data);
2769 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2771 $type = "application/xml";
2772 $encoding = "base64url";
2773 $alg = "RSA-SHA256";
2775 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2777 $signature = rsa_sign($signable_data,$prvkey);
2778 $sig = base64url_encode($signature);
2780 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2781 "aes_key" => $b_inner_aes_key,
2782 "author_id" => $handle));
2784 $decrypted_header = xml::from_array($xmldata, $xml, true);
2786 $ciphertext = self::aes_encrypt($outer_aes_key, $outer_iv, $decrypted_header);
2788 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2790 $encrypted_outer_key_bundle = "";
2791 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2793 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2795 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2797 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2798 "ciphertext" => base64_encode($ciphertext)));
2799 $cipher_json = base64_encode($encrypted_header_json_object);
2801 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2802 "me:env" => array("me:encoding" => $encoding,
2805 "@attributes" => array("type" => $type),
2806 "me:sig" => $sig)));
2808 $namespaces = array("" => "https://joindiaspora.com/protocol",
2809 "me" => "http://salmon-protocol.org/ns/magic-env");
2811 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2813 logger("magic_env: ".$magic_env, LOGGER_DATA);
2818 * @brief Create the envelope for a message
2820 * @param string $msg The message that is to be transmitted
2821 * @param array $user The record of the sender
2822 * @param array $contact Target of the communication
2823 * @param string $prvkey The private key of the sender
2824 * @param string $pubkey The public key of the receiver
2825 * @param bool $public Is the message public?
2827 * @return string The message that will be transmitted to other servers
2829 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2832 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2834 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2836 // The data that will be transmitted is double encoded via "urlencode", strange ...
2837 $slap = "xml=".urlencode(urlencode($magic_env));
2842 * @brief Creates a signature for a message
2844 * @param array $owner the array of the owner of the message
2845 * @param array $message The message that is to be signed
2847 * @return string The signature
2849 private static function signature($owner, $message) {
2851 unset($sigmsg["author_signature"]);
2852 unset($sigmsg["parent_author_signature"]);
2854 $signed_text = implode(";", $sigmsg);
2856 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2860 * @brief Transmit a message to a target server
2862 * @param array $owner the array of the item owner
2863 * @param array $contact Target of the communication
2864 * @param string $slap The message that is to be transmitted
2865 * @param bool $public_batch Is it a public post?
2866 * @param bool $queue_run Is the transmission called from the queue?
2867 * @param string $guid message guid
2869 * @return int Result of the transmission
2871 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2875 $enabled = intval(get_config("system", "diaspora_enabled"));
2879 $logid = random_string(4);
2880 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2882 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2886 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2888 if (!$queue_run && was_recently_delayed($contact["id"])) {
2891 if (!intval(get_config("system", "diaspora_test"))) {
2892 post_url($dest_url."/", $slap);
2893 $return_code = $a->get_curl_code();
2895 logger("test_mode");
2900 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2902 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2903 logger("queue message");
2905 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2906 intval($contact["id"]),
2907 dbesc(NETWORK_DIASPORA),
2909 intval($public_batch)
2912 logger("add_to_queue ignored - identical item already in queue");
2914 // queue message for redelivery
2915 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2917 // The message could not be delivered. We mark the contact as "dead"
2918 mark_for_death($contact);
2920 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2921 // We successfully delivered a message, the contact is alive
2922 unmark_for_death($contact);
2925 return(($return_code) ? $return_code : (-1));
2930 * @brief Build the post xml
2932 * @param string $type The message type
2933 * @param array $message The message data
2935 * @return string The post XML
2937 public static function build_post_xml($type, $message) {
2939 $data = array("XML" => array("post" => array($type => $message)));
2940 return xml::from_array($data, $xml);
2944 * @brief Builds and transmit messages
2946 * @param array $owner the array of the item owner
2947 * @param array $contact Target of the communication
2948 * @param string $type The message type
2949 * @param array $message The message data
2950 * @param bool $public_batch Is it a public post?
2951 * @param string $guid message guid
2952 * @param bool $spool Should the transmission be spooled or transmitted?
2954 * @return int Result of the transmission
2956 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2958 $msg = self::build_post_xml($type, $message);
2960 logger('message: '.$msg, LOGGER_DATA);
2961 logger('send guid '.$guid, LOGGER_DEBUG);
2963 // Fallback if the private key wasn't transmitted in the expected field
2964 if ($owner['uprvkey'] == "")
2965 $owner['uprvkey'] = $owner['prvkey'];
2967 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2970 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2973 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2975 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2977 return $return_code;
2981 * @brief Sends a "share" message
2983 * @param array $owner the array of the item owner
2984 * @param array $contact Target of the communication
2986 * @return int The result of the transmission
2988 public static function send_share($owner,$contact) {
2990 $message = array("sender_handle" => self::my_handle($owner),
2991 "recipient_handle" => $contact["addr"]);
2993 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2995 return self::build_and_transmit($owner, $contact, "request", $message);
2999 * @brief sends an "unshare"
3001 * @param array $owner the array of the item owner
3002 * @param array $contact Target of the communication
3004 * @return int The result of the transmission
3006 public static function send_unshare($owner,$contact) {
3008 $message = array("post_guid" => $owner["guid"],
3009 "diaspora_handle" => self::my_handle($owner),
3010 "type" => "Person");
3012 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3014 return self::build_and_transmit($owner, $contact, "retraction", $message);
3018 * @brief Checks a message body if it is a reshare
3020 * @param string $body The message body that is to be check
3021 * @param bool $complete Should it be a complete check or a simple check?
3023 * @return array|bool Reshare details or "false" if no reshare
3025 public static function is_reshare($body, $complete = true) {
3026 $body = trim($body);
3028 // Skip if it isn't a pure repeated messages
3029 // Does it start with a share?
3030 if ((strpos($body, "[share") > 0) AND $complete)
3033 // Does it end with a share?
3034 if (strlen($body) > (strrpos($body, "[/share]") + 8))
3037 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3038 // Skip if there is no shared message in there
3039 if ($body == $attributes)
3042 // If we don't do the complete check we quit here
3047 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3048 if ($matches[1] != "")
3049 $guid = $matches[1];
3051 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3052 if ($matches[1] != "")
3053 $guid = $matches[1];
3056 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3057 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3060 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3061 $ret["root_guid"] = $guid;
3067 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3068 if ($matches[1] != "")
3069 $profile = $matches[1];
3071 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3072 if ($matches[1] != "")
3073 $profile = $matches[1];
3077 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3078 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
3082 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3083 if ($matches[1] != "")
3084 $link = $matches[1];
3086 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3087 if ($matches[1] != "")
3088 $link = $matches[1];
3090 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3091 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
3098 * @brief Create an event array
3100 * @param integer $event_id The id of the event
3102 * @return array with event data
3104 private static function build_event($event_id) {
3106 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3107 if (!dbm::is_result($r)) {
3113 $eventdata = array();
3115 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3116 if (!dbm::is_result($r)) {
3122 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3123 if (!dbm::is_result($r)) {
3129 $eventdata['author'] = self::my_handle($owner);
3131 if ($event['guid']) {
3132 $eventdata['guid'] = $event['guid'];
3135 $mask = 'Y-m-d\TH:i:s\Z';
3137 /// @todo - establish "all day" events in Friendica
3138 $eventdata["all_day"] = "false";
3140 if (!$event['adjust']) {
3141 $eventdata['timezone'] = $user['timezone'];
3143 if ($eventdata['timezone'] == "") {
3144 $eventdata['timezone'] = 'UTC';
3148 if ($event['start']) {
3149 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3151 if ($event['finish'] AND !$event['nofinish']) {
3152 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3154 if ($event['summary']) {
3155 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3157 if ($event['desc']) {
3158 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3160 if ($event['location']) {
3161 $location = array();
3162 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3163 $location["lat"] = 0;
3164 $location["lng"] = 0;
3165 $eventdata['location'] = $location;
3172 * @brief Create a post (status message or reshare)
3174 * @param array $item The item that will be exported
3175 * @param array $owner the array of the item owner
3178 * 'type' -> Message type ("status_message" or "reshare")
3179 * 'message' -> Array of XML elements of the status
3181 public static function build_status($item, $owner) {
3183 $cachekey = "diaspora:build_status:".$item['guid'];
3185 $result = Cache::get($cachekey);
3186 if (!is_null($result)) {
3190 $myaddr = self::my_handle($owner);
3192 $public = (($item["private"]) ? "false" : "true");
3194 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3196 // Detect a share element and do a reshare
3197 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3198 $message = array("root_diaspora_id" => $ret["root_handle"],
3199 "root_guid" => $ret["root_guid"],
3200 "guid" => $item["guid"],
3201 "diaspora_handle" => $myaddr,
3202 "public" => $public,
3203 "created_at" => $created,
3204 "provider_display_name" => $item["app"]);
3208 $title = $item["title"];
3209 $body = $item["body"];
3211 // convert to markdown
3212 $body = html_entity_decode(bb2diaspora($body));
3216 $body = "## ".html_entity_decode($title)."\n\n".$body;
3218 if ($item["attach"]) {
3219 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3221 $body .= "\n".t("Attachments:")."\n";
3222 foreach ($matches as $mtch)
3223 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3227 $location = array();
3229 if ($item["location"] != "")
3230 $location["address"] = $item["location"];
3232 if ($item["coord"] != "") {
3233 $coord = explode(" ", $item["coord"]);
3234 $location["lat"] = $coord[0];
3235 $location["lng"] = $coord[1];
3238 $message = array("raw_message" => $body,
3239 "location" => $location,
3240 "guid" => $item["guid"],
3241 "diaspora_handle" => $myaddr,
3242 "public" => $public,
3243 "created_at" => $created,
3244 "provider_display_name" => $item["app"]);
3246 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3247 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3248 unset($message["location"]);
3251 if ($item['event-id'] > 0) {
3252 $event = self::build_event($item['event-id']);
3253 if (count($event)) {
3254 $message['event'] = $event;
3256 /// @todo Once Diaspora supports it, we will remove the body
3257 // $message['raw_message'] = '';
3261 $type = "status_message";
3264 $msg = array("type" => $type, "message" => $message);
3266 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3272 * @brief Sends a post
3274 * @param array $item The item that will be exported
3275 * @param array $owner the array of the item owner
3276 * @param array $contact Target of the communication
3277 * @param bool $public_batch Is it a public post?
3279 * @return int The result of the transmission
3281 public static function send_status($item, $owner, $contact, $public_batch = false) {
3283 $status = self::build_status($item, $owner);
3285 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3289 * @brief Creates a "like" object
3291 * @param array $item The item that will be exported
3292 * @param array $owner the array of the item owner
3294 * @return array The data for a "like"
3296 private static function construct_like($item, $owner) {
3298 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3299 dbesc($item["thr-parent"]));
3300 if (!dbm::is_result($p))
3305 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3306 if ($item['verb'] === ACTIVITY_LIKE) {
3308 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3309 $positive = "false";
3312 return(array("positive" => $positive,
3313 "guid" => $item["guid"],
3314 "target_type" => $target_type,
3315 "parent_guid" => $parent["guid"],
3316 "author_signature" => "",
3317 "diaspora_handle" => self::my_handle($owner)));
3321 * @brief Creates an "EventParticipation" object
3323 * @param array $item The item that will be exported
3324 * @param array $owner the array of the item owner
3326 * @return array The data for an "EventParticipation"
3328 private static function construct_attend($item, $owner) {
3330 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3331 dbesc($item["thr-parent"]));
3332 if (!dbm::is_result($p))
3337 switch ($item['verb']) {
3338 case ACTIVITY_ATTEND:
3339 $attend_answer = 'accepted';
3341 case ACTIVITY_ATTENDNO:
3342 $attend_answer = 'declined';
3344 case ACTIVITY_ATTENDMAYBE:
3345 $attend_answer = 'tentative';
3348 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3352 return(array("author" => self::my_handle($owner),
3353 "guid" => $item["guid"],
3354 "parent_guid" => $parent["guid"],
3355 "status" => $attend_answer,
3356 "author_signature" => ""));
3360 * @brief Creates the object for a comment
3362 * @param array $item The item that will be exported
3363 * @param array $owner the array of the item owner
3365 * @return array The data for a comment
3367 private static function construct_comment($item, $owner) {
3369 $cachekey = "diaspora:construct_comment:".$item['guid'];
3371 $result = Cache::get($cachekey);
3372 if (!is_null($result)) {
3376 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3377 intval($item["parent"]),
3378 intval($item["parent"])
3381 if (!dbm::is_result($p))
3386 $text = html_entity_decode(bb2diaspora($item["body"]));
3387 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3389 $comment = array("guid" => $item["guid"],
3390 "parent_guid" => $parent["guid"],
3391 "author_signature" => "",
3393 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3394 "diaspora_handle" => self::my_handle($owner));
3396 // Send the thread parent guid only if it is a threaded comment
3397 if ($item['thr-parent'] != $item['parent-uri']) {
3398 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3401 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3407 * @brief Send a like or a comment
3409 * @param array $item The item that will be exported
3410 * @param array $owner the array of the item owner
3411 * @param array $contact Target of the communication
3412 * @param bool $public_batch Is it a public post?
3414 * @return int The result of the transmission
3416 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3418 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3419 $message = self::construct_attend($item, $owner);
3420 $type = "event_participation";
3421 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3422 $message = self::construct_like($item, $owner);
3425 $message = self::construct_comment($item, $owner);
3432 $message["author_signature"] = self::signature($owner, $message);
3434 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3438 * @brief Creates a message from a signature record entry
3440 * @param array $item The item that will be exported
3441 * @param array $signature The entry of the "sign" record
3443 * @return string The message
3445 private static function message_from_signature($item, $signature) {
3447 // Split the signed text
3448 $signed_parts = explode(";", $signature['signed_text']);
3450 if ($item["deleted"])
3451 $message = array("parent_author_signature" => "",
3452 "target_guid" => $signed_parts[0],
3453 "target_type" => $signed_parts[1],
3454 "sender_handle" => $signature['signer'],
3455 "target_author_signature" => $signature['signature']);
3456 elseif ($item['verb'] === ACTIVITY_LIKE)
3457 $message = array("positive" => $signed_parts[0],
3458 "guid" => $signed_parts[1],
3459 "target_type" => $signed_parts[2],
3460 "parent_guid" => $signed_parts[3],
3461 "parent_author_signature" => "",
3462 "author_signature" => $signature['signature'],
3463 "diaspora_handle" => $signed_parts[4]);
3465 // Remove the comment guid
3466 $guid = array_shift($signed_parts);
3468 // Remove the parent guid
3469 $parent_guid = array_shift($signed_parts);
3471 // Remove the handle
3472 $handle = array_pop($signed_parts);
3474 // Glue the parts together
3475 $text = implode(";", $signed_parts);
3477 $message = array("guid" => $guid,
3478 "parent_guid" => $parent_guid,
3479 "parent_author_signature" => "",
3480 "author_signature" => $signature['signature'],
3481 "text" => implode(";", $signed_parts),
3482 "diaspora_handle" => $handle);
3488 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3490 * @param array $item The item that will be exported
3491 * @param array $owner the array of the item owner
3492 * @param array $contact Target of the communication
3493 * @param bool $public_batch Is it a public post?
3495 * @return int The result of the transmission
3497 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3499 if ($item["deleted"])
3500 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3501 elseif ($item['verb'] === ACTIVITY_LIKE)
3506 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3508 // fetch the original signature
3510 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3511 intval($item["id"]));
3514 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3520 // Old way - is used by the internal Friendica functions
3521 /// @todo Change all signatur storing functions to the new format
3522 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3523 $message = self::message_from_signature($item, $signature);
3525 $msg = json_decode($signature['signed_text'], true);
3528 if (is_array($msg)) {
3529 foreach ($msg AS $field => $data) {
3530 if (!$item["deleted"]) {
3531 if ($field == "author")
3532 $field = "diaspora_handle";
3533 if ($field == "parent_type")
3534 $field = "target_type";
3537 $message[$field] = $data;
3540 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3543 $message["parent_author_signature"] = self::signature($owner, $message);
3545 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3547 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3551 * @brief Sends a retraction (deletion) of a message, like or comment
3553 * @param array $item The item that will be exported
3554 * @param array $owner the array of the item owner
3555 * @param array $contact Target of the communication
3556 * @param bool $public_batch Is it a public post?
3557 * @param bool $relay Is the retraction transmitted from a relay?
3559 * @return int The result of the transmission
3561 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3563 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3565 // Check whether the retraction is for a top-level post or whether it's a relayable
3566 if ($item["uri"] !== $item["parent-uri"]) {
3567 $msg_type = "relayable_retraction";
3568 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3570 $msg_type = "signed_retraction";
3571 $target_type = "StatusMessage";
3574 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3575 $signature = "parent_author_signature";
3577 $signature = "target_author_signature";
3579 $signed_text = $item["guid"].";".$target_type;
3581 $message = array("target_guid" => $item['guid'],
3582 "target_type" => $target_type,
3583 "sender_handle" => $itemaddr,
3584 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3586 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3588 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3592 * @brief Sends a mail
3594 * @param array $item The item that will be exported
3595 * @param array $owner The owner
3596 * @param array $contact Target of the communication
3598 * @return int The result of the transmission
3600 public static function send_mail($item, $owner, $contact) {
3602 $myaddr = self::my_handle($owner);
3604 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3605 intval($item["convid"]),
3606 intval($item["uid"])
3609 if (!dbm::is_result($r)) {
3610 logger("conversation not found.");
3616 "guid" => $cnv["guid"],
3617 "subject" => $cnv["subject"],
3618 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3619 "diaspora_handle" => $cnv["creator"],
3620 "participant_handles" => $cnv["recips"]
3623 $body = bb2diaspora($item["body"]);
3624 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3626 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3627 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3630 "guid" => $item["guid"],
3631 "parent_guid" => $cnv["guid"],
3632 "parent_author_signature" => $sig,
3633 "author_signature" => $sig,
3635 "created_at" => $created,
3636 "diaspora_handle" => $myaddr,
3637 "conversation_guid" => $cnv["guid"]
3640 if ($item["reply"]) {
3644 $message = array("guid" => $cnv["guid"],
3645 "subject" => $cnv["subject"],
3646 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3648 "diaspora_handle" => $cnv["creator"],
3649 "participant_handles" => $cnv["recips"]);
3651 $type = "conversation";
3654 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3658 * @brief Sends profile data
3660 * @param int $uid The user id
3662 public static function send_profile($uid, $recips = false) {
3668 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3669 AND `uid` = %d AND `rel` != %d",
3670 dbesc(NETWORK_DIASPORA),
3672 intval(CONTACT_IS_SHARING)
3677 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3679 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3680 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3681 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3690 $handle = $profile["addr"];
3691 $first = ((strpos($profile['name'],' ')
3692 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3693 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3694 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3695 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3696 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3697 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3699 if ($searchable === 'true') {
3700 $dob = '1000-00-00';
3702 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3703 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3705 $about = $profile['about'];
3706 $about = strip_tags(bbcode($about));
3708 $location = formatted_location($profile);
3710 if ($profile['pub_keywords']) {
3711 $kw = str_replace(',',' ',$profile['pub_keywords']);
3712 $kw = str_replace(' ',' ',$kw);
3713 $arr = explode(' ',$profile['pub_keywords']);
3715 for ($x = 0; $x < 5; $x ++) {
3717 $tags .= '#'. trim($arr[$x]) .' ';
3721 $tags = trim($tags);
3724 $message = array("diaspora_handle" => $handle,
3725 "first_name" => $first,
3726 "last_name" => $last,
3727 "image_url" => $large,
3728 "image_url_medium" => $medium,
3729 "image_url_small" => $small,
3731 "gender" => $profile['gender'],
3733 "location" => $location,
3734 "searchable" => $searchable,
3735 "tag_string" => $tags);
3737 foreach ($recips as $recip) {
3738 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3739 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3744 * @brief Stores the signature for likes that are created on our system
3746 * @param array $contact The contact array of the "like"
3747 * @param int $post_id The post id of the "like"
3749 * @return bool Success
3751 public static function store_like_signature($contact, $post_id) {
3753 // Is the contact the owner? Then fetch the private key
3754 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3755 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3759 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3760 if (!dbm::is_result($r)) {
3764 $contact["uprvkey"] = $r[0]['prvkey'];
3766 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3767 if (!dbm::is_result($r)) {
3771 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3775 $message = self::construct_like($r[0], $contact);
3776 $message["author_signature"] = self::signature($contact, $message);
3778 // We now store the signature more flexible to dynamically support new fields.
3779 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3780 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3781 intval($message_id),
3782 dbesc(json_encode($message))
3785 logger('Stored diaspora like signature');
3790 * @brief Stores the signature for comments that are created on our system
3792 * @param array $item The item array of the comment
3793 * @param array $contact The contact array of the item owner
3794 * @param string $uprvkey The private key of the sender
3795 * @param int $message_id The message id of the comment
3797 * @return bool Success
3799 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3801 if ($uprvkey == "") {
3802 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3806 $contact["uprvkey"] = $uprvkey;
3808 $message = self::construct_comment($item, $contact);
3809 $message["author_signature"] = self::signature($contact, $message);
3811 // We now store the signature more flexible to dynamically support new fields.
3812 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3813 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3814 intval($message_id),
3815 dbesc(json_encode($message))
3818 logger('Stored diaspora comment signature');