3 * @file src/Protocol/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 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "validPosting" and interpret only the new protocol.
10 namespace Friendica\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBM;
19 use Friendica\Model\Contact;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Profile;
23 use Friendica\Model\User;
24 use Friendica\Network\Probe;
25 use Friendica\Util\XML;
30 require_once 'include/dba.php';
31 require_once 'include/items.php';
32 require_once 'include/bb2diaspora.php';
33 require_once 'include/datetime.php';
34 require_once 'include/queue_fn.php';
37 * @brief This class contain functions to create and send Diaspora XML files
43 * @brief Return a list of relay servers
45 * This is an experimental Diaspora feature.
47 * @return array of relay servers
49 public static function relayList()
51 $serverdata = Config::get("system", "relay_server");
52 if ($serverdata == "") {
58 $servers = explode(",", $serverdata);
60 foreach ($servers as $server) {
61 $server = trim($server);
62 $addr = "relay@".str_replace("http://", "", normalise_link($server));
63 $batch = $server."/receive/public";
66 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
69 dbesc(normalise_link($server))
74 "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
75 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
80 dbesc(normalise_link($server)),
82 dbesc(NETWORK_DIASPORA),
83 intval(CONTACT_IS_FOLLOWER),
84 dbesc(datetime_convert()),
85 dbesc(datetime_convert()),
86 dbesc(datetime_convert())
89 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
91 $relay[] = $relais[0];
94 $relay[] = $relais[0];
102 * @brief repairs a signature that was double encoded
104 * The function is unused at the moment. It was copied from the old implementation.
106 * @param string $signature The signature
107 * @param string $handle The handle of the signature owner
108 * @param integer $level This value is only set inside this function to avoid endless loops
110 * @return string the repaired signature
112 private static function repairSignature($signature, $handle = "", $level = 1)
114 if ($signature == "") {
118 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
119 $signature = base64_decode($signature);
120 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
122 // Do a recursive call to be able to fix even multiple levels
124 $signature = self::repairSignature($signature, $handle, ++$level);
132 * @brief verify the envelope and return the verified data
134 * @param string $envelope The magic envelope
136 * @return string verified data
138 private static function verifyMagicEnvelope($envelope)
140 $basedom = parse_xml_string($envelope);
142 if (!is_object($basedom)) {
143 logger("Envelope is no XML file");
147 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
149 if (sizeof($children) == 0) {
150 logger("XML has no children");
156 $data = base64url_decode($children->data);
157 $type = $children->data->attributes()->type[0];
159 $encoding = $children->encoding;
161 $alg = $children->alg;
163 $sig = base64url_decode($children->sig);
164 $key_id = $children->sig->attributes()->key_id[0];
166 $handle = base64url_decode($key_id);
169 $b64url_data = base64url_encode($data);
170 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
172 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
174 $key = self::key($handle);
176 $verify = rsa_verify($signable_data, $sig, $key);
178 logger('Message did not verify. Discarding.');
186 * @brief encrypts data via AES
188 * @param string $key The AES key
189 * @param string $iv The IV (is used for CBC encoding)
190 * @param string $data The data that is to be encrypted
192 * @return string encrypted data
194 private static function aesEncrypt($key, $iv, $data)
196 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
200 * @brief decrypts data via AES
202 * @param string $key The AES key
203 * @param string $iv The IV (is used for CBC encoding)
204 * @param string $encrypted The encrypted data
206 * @return string decrypted data
208 private static function aesDecrypt($key, $iv, $encrypted)
210 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
214 * @brief: Decodes incoming Diaspora message in the new format
216 * @param array $importer Array of the importer user
217 * @param string $raw raw post message
220 * 'message' -> decoded Diaspora XML message
221 * 'author' -> author diaspora handle
222 * 'key' -> author public key (converted to pkcs#8)
224 public static function decodeRaw($importer, $raw)
226 $data = json_decode($raw);
228 // Is it a private post? Then decrypt the outer Salmon
229 if (is_object($data)) {
230 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
231 $ciphertext = base64_decode($data->encrypted_magic_envelope);
233 $outer_key_bundle = '';
234 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
235 $j_outer_key_bundle = json_decode($outer_key_bundle);
237 if (!is_object($j_outer_key_bundle)) {
238 logger('Outer Salmon did not verify. Discarding.');
239 http_status_exit(400);
242 $outer_iv = base64_decode($j_outer_key_bundle->iv);
243 $outer_key = base64_decode($j_outer_key_bundle->key);
245 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
250 $basedom = parse_xml_string($xml);
252 if (!is_object($basedom)) {
253 logger('Received data does not seem to be an XML. Discarding. '.$xml);
254 http_status_exit(400);
257 $base = $basedom->children(NAMESPACE_SALMON_ME);
259 // Not sure if this cleaning is needed
260 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
262 // Build the signed data
263 $type = $base->data[0]->attributes()->type[0];
264 $encoding = $base->encoding;
266 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
268 // This is the signature
269 $signature = base64url_decode($base->sig);
271 // Get the senders' public key
272 $key_id = $base->sig[0]->attributes()->key_id[0];
273 $author_addr = base64_decode($key_id);
274 $key = self::key($author_addr);
276 $verify = rsa_verify($signed_data, $signature, $key);
278 logger('Message did not verify. Discarding.');
279 http_status_exit(400);
282 return array('message' => (string)base64url_decode($base->data),
283 'author' => unxmlify($author_addr),
284 'key' => (string)$key);
288 * @brief: Decodes incoming Diaspora message in the deprecated format
290 * @param array $importer Array of the importer user
291 * @param string $xml urldecoded Diaspora salmon
294 * 'message' -> decoded Diaspora XML message
295 * 'author' -> author diaspora handle
296 * 'key' -> author public key (converted to pkcs#8)
298 public static function decode($importer, $xml)
301 $basedom = parse_xml_string($xml);
303 if (!is_object($basedom)) {
304 logger("XML is not parseable.");
307 $children = $basedom->children('https://joindiaspora.com/protocol');
309 if ($children->header) {
311 $author_link = str_replace('acct:', '', $children->header->author_id);
313 // This happens with posts from a relais
315 logger("This is no private post in the old format", LOGGER_DEBUG);
319 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
321 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
322 $ciphertext = base64_decode($encrypted_header->ciphertext);
324 $outer_key_bundle = '';
325 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
327 $j_outer_key_bundle = json_decode($outer_key_bundle);
329 $outer_iv = base64_decode($j_outer_key_bundle->iv);
330 $outer_key = base64_decode($j_outer_key_bundle->key);
332 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
334 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
335 $idom = parse_xml_string($decrypted);
337 $inner_iv = base64_decode($idom->iv);
338 $inner_aes_key = base64_decode($idom->aes_key);
340 $author_link = str_replace('acct:', '', $idom->author_id);
343 $dom = $basedom->children(NAMESPACE_SALMON_ME);
345 // figure out where in the DOM tree our data is hiding
347 if ($dom->provenance->data) {
348 $base = $dom->provenance;
349 } elseif ($dom->env->data) {
351 } elseif ($dom->data) {
356 logger('unable to locate salmon data in xml');
357 http_status_exit(400);
361 // Stash the signature away for now. We have to find their key or it won't be good for anything.
362 $signature = base64url_decode($base->sig);
366 // strip whitespace so our data element will return to one big base64 blob
367 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
370 // stash away some other stuff for later
372 $type = $base->data[0]->attributes()->type[0];
373 $keyhash = $base->sig[0]->attributes()->keyhash[0];
374 $encoding = $base->encoding;
378 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
382 $data = base64url_decode($data);
386 $inner_decrypted = $data;
388 // Decode the encrypted blob
389 $inner_encrypted = base64_decode($data);
390 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
394 logger('Could not retrieve author URI.');
395 http_status_exit(400);
397 // Once we have the author URI, go to the web and try to find their public key
398 // (first this will look it up locally if it is in the fcontact cache)
399 // This will also convert diaspora public key from pkcs#1 to pkcs#8
401 logger('Fetching key for '.$author_link);
402 $key = self::key($author_link);
405 logger('Could not retrieve author key.');
406 http_status_exit(400);
409 $verify = rsa_verify($signed_data, $signature, $key);
412 logger('Message did not verify. Discarding.');
413 http_status_exit(400);
416 logger('Message verified.');
418 return array('message' => (string)$inner_decrypted,
419 'author' => unxmlify($author_link),
420 'key' => (string)$key);
425 * @brief Dispatches public messages and find the fitting receivers
427 * @param array $msg The post that will be dispatched
429 * @return int The message id of the generated message, "true" or "false" if there was an error
431 public static function dispatchPublic($msg)
433 $enabled = intval(Config::get("system", "diaspora_enabled"));
435 logger("diaspora is disabled");
439 if (!($postdata = self::validPosting($msg))) {
440 logger("Invalid posting");
444 $fields = $postdata['fields'];
446 // Is it a an action (comment, like, ...) for our own post?
447 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
448 $guid = notags(unxmlify($fields->parent_guid));
449 $importer = self::importerForGuid($guid);
450 if (is_array($importer)) {
451 logger("delivering to origin: ".$importer["name"]);
452 $message_id = self::dispatch($importer, $msg, $fields);
457 // Process item retractions. This has to be done separated from the other stuff,
458 // since retractions for comments could come even from non followers.
459 if (!empty($fields) && in_array($fields->getName(), array('retraction'))) {
460 $target = notags(unxmlify($fields->target_type));
461 if (in_array($target, array("Comment", "Like", "Post", "Reshare", "StatusMessage"))) {
462 logger('processing retraction for '.$target, LOGGER_DEBUG);
463 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
464 $message_id = self::dispatch($importer, $msg, $fields);
469 // Now distribute it to the followers
471 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
472 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
473 AND NOT `account_expired` AND NOT `account_removed`",
474 dbesc(NETWORK_DIASPORA),
475 dbesc($msg["author"])
478 if (DBM::is_result($r)) {
479 foreach ($r as $rr) {
480 logger("delivering to: ".$rr["username"]);
481 self::dispatch($rr, $msg, $fields);
483 } elseif (!Config::get('system', 'relay_subscribe', false)) {
484 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
486 // Use a dummy importer to import the data for the public copy
487 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
488 $message_id = self::dispatch($importer, $msg, $fields);
495 * @brief Dispatches the different message types to the different functions
497 * @param array $importer Array of the importer user
498 * @param array $msg The post that will be dispatched
499 * @param object $fields SimpleXML object that contains the message
501 * @return int The message id of the generated message, "true" or "false" if there was an error
503 public static function dispatch($importer, $msg, $fields = null)
505 // The sender is the handle of the contact that sent the message.
506 // This will often be different with relayed messages (for example "like" and "comment")
507 $sender = $msg["author"];
509 // This is only needed for private postings since this is already done for public ones before
510 if (is_null($fields)) {
511 if (!($postdata = self::validPosting($msg))) {
512 logger("Invalid posting");
515 $fields = $postdata['fields'];
518 $type = $fields->getName();
520 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
523 case "account_migration":
524 return self::receiveAccountMigration($importer, $fields);
526 case "account_deletion":
527 return self::receiveAccountDeletion($importer, $fields);
530 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
533 return self::receiveContactRequest($importer, $fields);
536 return self::receiveConversation($importer, $msg, $fields);
539 return self::receiveLike($importer, $sender, $fields);
542 return self::receiveMessage($importer, $fields);
544 case "participation": // Not implemented
545 return self::receiveParticipation($importer, $fields);
547 case "photo": // Not implemented
548 return self::receivePhoto($importer, $fields);
550 case "poll_participation": // Not implemented
551 return self::receivePollParticipation($importer, $fields);
554 return self::receiveProfile($importer, $fields);
557 return self::receiveReshare($importer, $fields, $msg["message"]);
560 return self::receiveRetraction($importer, $sender, $fields);
562 case "status_message":
563 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
566 logger("Unknown message type ".$type);
574 * @brief Checks if a posting is valid and fetches the data fields.
576 * This function does not only check the signature.
577 * It also does the conversion between the old and the new diaspora format.
579 * @param array $msg Array with the XML, the sender handle and the sender signature
581 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
583 private static function validPosting($msg)
585 $data = parse_xml_string($msg["message"]);
587 if (!is_object($data)) {
588 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
592 $first_child = $data->getName();
594 // Is this the new or the old version?
595 if ($data->getName() == "XML") {
597 foreach ($data->post->children() as $child) {
605 $type = $element->getName();
608 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
610 // All retractions are handled identically from now on.
611 // In the new version there will only be "retraction".
612 if (in_array($type, array("signed_retraction", "relayable_retraction")))
613 $type = "retraction";
615 if ($type == "request") {
619 $fields = new SimpleXMLElement("<".$type."/>");
623 foreach ($element->children() as $fieldname => $entry) {
625 // Translation for the old XML structure
626 if ($fieldname == "diaspora_handle") {
627 $fieldname = "author";
629 if ($fieldname == "participant_handles") {
630 $fieldname = "participants";
632 if (in_array($type, array("like", "participation"))) {
633 if ($fieldname == "target_type") {
634 $fieldname = "parent_type";
637 if ($fieldname == "sender_handle") {
638 $fieldname = "author";
640 if ($fieldname == "recipient_handle") {
641 $fieldname = "recipient";
643 if ($fieldname == "root_diaspora_id") {
644 $fieldname = "root_author";
646 if ($type == "status_message") {
647 if ($fieldname == "raw_message") {
651 if ($type == "retraction") {
652 if ($fieldname == "post_guid") {
653 $fieldname = "target_guid";
655 if ($fieldname == "type") {
656 $fieldname = "target_type";
661 if (($fieldname == "author_signature") && ($entry != "")) {
662 $author_signature = base64_decode($entry);
663 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
664 $parent_author_signature = base64_decode($entry);
665 } elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
666 if ($signed_data != "") {
668 $signed_data_parent .= ";";
671 $signed_data .= $entry;
673 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature"))
674 || ($orig_type == "relayable_retraction")
676 XML::copy($entry, $fields, $fieldname);
680 // This is something that shouldn't happen at all.
681 if (in_array($type, array("status_message", "reshare", "profile"))) {
682 if ($msg["author"] != $fields->author) {
683 logger("Message handle is not the same as envelope sender. Quitting this message.");
688 // Only some message types have signatures. So we quit here for the other types.
689 if (!in_array($type, array("comment", "like"))) {
690 return array("fields" => $fields, "relayed" => false);
692 // No author_signature? This is a must, so we quit.
693 if (!isset($author_signature)) {
694 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
698 if (isset($parent_author_signature)) {
701 $key = self::key($msg["author"]);
703 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
704 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);
711 $key = self::key($fields->author);
713 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
714 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
717 return array("fields" => $fields, "relayed" => $relayed);
722 * @brief Fetches the public key for a given handle
724 * @param string $handle The handle
726 * @return string The public key
728 private static function key($handle)
730 $handle = strval($handle);
732 logger("Fetching diaspora key for: ".$handle);
734 $r = self::personByHandle($handle);
743 * @brief Fetches data for a given handle
745 * @param string $handle The handle
747 * @return array the queried data
749 public static function personByHandle($handle)
752 "SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
753 dbesc(NETWORK_DIASPORA),
758 logger("In cache " . print_r($r, true), LOGGER_DEBUG);
760 // update record occasionally so it doesn't get stale
761 $d = strtotime($person["updated"]." +00:00");
762 if ($d < strtotime("now - 14 days")) {
766 if ($person["guid"] == "") {
771 if (!$person || $update) {
772 logger("create or refresh", LOGGER_DEBUG);
773 $r = Probe::uri($handle, NETWORK_DIASPORA);
775 // Note that Friendica contacts will return a "Diaspora person"
776 // if Diaspora connectivity is enabled on their server
777 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
778 self::addFContact($r, $update);
786 * @brief Updates the fcontact table
788 * @param array $arr The fcontact data
789 * @param bool $update Update or insert?
791 * @return string The id of the fcontact entry
793 private static function addFContact($arr, $update = false)
797 "UPDATE `fcontact` SET
811 WHERE `url` = '%s' AND `network` = '%s'",
813 dbesc($arr["photo"]),
814 dbesc($arr["request"]),
816 dbesc(strtolower($arr["addr"])),
818 dbesc($arr["batch"]),
819 dbesc($arr["notify"]),
821 dbesc($arr["confirm"]),
822 dbesc($arr["alias"]),
823 dbesc($arr["pubkey"]),
824 dbesc(datetime_convert()),
826 dbesc($arr["network"])
830 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
831 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
832 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
835 dbesc($arr["photo"]),
836 dbesc($arr["request"]),
840 dbesc($arr["batch"]),
841 dbesc($arr["notify"]),
843 dbesc($arr["confirm"]),
844 dbesc($arr["network"]),
845 dbesc($arr["alias"]),
846 dbesc($arr["pubkey"]),
847 dbesc(datetime_convert())
855 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
857 * @param int $contact_id The id in the contact table
858 * @param int $gcontact_id The id in the gcontact table
860 * @return string the handle
862 public static function handleFromContact($contact_id, $gcontact_id = 0)
866 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
868 if ($gcontact_id != 0) {
870 "SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
874 if (DBM::is_result($r)) {
875 return strtolower($r[0]["addr"]);
880 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
884 if (DBM::is_result($r)) {
887 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
889 if ($contact['addr'] != "") {
890 $handle = $contact['addr'];
892 $baseurl_start = strpos($contact['url'], '://') + 3;
893 // allows installations in a subdirectory--not sure how Diaspora will handle
894 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
895 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
896 $handle = $contact['nick'].'@'.$baseurl;
900 return strtolower($handle);
904 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
907 * @param mixed $fcontact_guid Hexadecimal string guid
909 * @return string the contact url or null
911 public static function urlFromContactGuid($fcontact_guid)
913 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
916 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
917 dbesc(NETWORK_DIASPORA),
918 dbesc($fcontact_guid)
921 if (DBM::is_result($r)) {
929 * @brief Get a contact id for a given handle
931 * @todo Move to Friendica\Model\Contact
933 * @param int $uid The user id
934 * @param string $handle The handle in the format user@domain.tld
936 * @return int Contact id
938 private static function contactByHandle($uid, $handle)
940 // First do a direct search on the contact table
942 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
947 if (DBM::is_result($r)) {
951 * We haven't found it?
952 * We use another function for it that will possibly create a contact entry.
954 $cid = Contact::getIdForURL($handle, $uid);
957 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
958 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
960 if (DBM::is_result($r)) {
966 $handle_parts = explode("@", $handle);
967 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
969 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
974 if (DBM::is_result($r)) {
978 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
983 * @brief Check if posting is allowed for this contact
985 * @param array $importer Array of the importer user
986 * @param array $contact The contact that is checked
987 * @param bool $is_comment Is the check for a comment?
989 * @return bool is the contact allowed to post?
991 private static function postAllow($importer, $contact, $is_comment = false)
994 * Perhaps we were already sharing with this person. Now they're sharing with us.
995 * That makes us friends.
996 * Normally this should have handled by getting a request - but this could get lost
998 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
999 // It is not removed by now. Possibly the code is needed?
1000 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1003 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1004 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1007 // $contact["rel"] = CONTACT_IS_FRIEND;
1008 // logger("defining user ".$contact["nick"]." as friend");
1011 // We don't seem to like that person
1012 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
1013 // Maybe blocked, don't accept.
1015 // We are following this person?
1016 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1017 // Yes, then it is fine.
1019 // Is it a post to a community?
1020 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1023 // Is the message a global user or a comment?
1024 } elseif (($importer["uid"] == 0) || $is_comment) {
1025 // Messages for the global users and comments are always accepted
1033 * @brief Fetches the contact id for a handle and checks if posting is allowed
1035 * @param array $importer Array of the importer user
1036 * @param string $handle The checked handle in the format user@domain.tld
1037 * @param bool $is_comment Is the check for a comment?
1039 * @return array The contact data
1041 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1043 $contact = self::contactByHandle($importer["uid"], $handle);
1045 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1046 // If a contact isn't found, we accept it anyway if it is a comment
1054 if (!self::postAllow($importer, $contact, $is_comment)) {
1055 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1062 * @brief Does the message already exists on the system?
1064 * @param int $uid The user id
1065 * @param string $guid The guid of the message
1067 * @return int|bool message id if the message already was stored into the system - or false.
1069 private static function messageExists($uid, $guid)
1072 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1077 if (DBM::is_result($r)) {
1078 logger("message ".$guid." already exists for user ".$uid);
1086 * @brief Checks for links to posts in a message
1088 * @param array $item The item array
1091 private static function fetchGuid($item)
1093 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1094 preg_replace_callback(
1096 function ($match) use ($item) {
1097 self::fetchGuidSub($match, $item);
1102 preg_replace_callback(
1103 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1104 function ($match) use ($item) {
1105 self::fetchGuidSub($match, $item);
1112 * @brief Checks for relative /people/* links in an item body to match local
1113 * contacts or prepends the remote host taken from the author link.
1115 * @param string $body The item body to replace links from
1116 * @param string $author_link The author link for missing local contact fallback
1118 * @return string the replaced string
1120 public static function replacePeopleGuid($body, $author_link)
1122 $return = preg_replace_callback(
1123 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1124 function ($match) use ($author_link) {
1126 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1127 // 1 => '0123456789abcdef'
1129 $handle = self::urlFromContactGuid($match[1]);
1132 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1134 // No local match, restoring absolute remote URL from author scheme and host
1135 $author_url = parse_url($author_link);
1136 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1148 * @brief sub function of "fetchGuid" which checks for links in messages
1150 * @param array $match array containing a link that has to be checked for a message link
1151 * @param array $item The item array
1154 private static function fetchGuidSub($match, $item)
1156 if (!self::storeByGuid($match[1], $item["author-link"])) {
1157 self::storeByGuid($match[1], $item["owner-link"]);
1162 * @brief Fetches an item with a given guid from a given server
1164 * @param string $guid the message guid
1165 * @param string $server The server address
1166 * @param int $uid The user id of the user
1168 * @return int the message id of the stored message or false
1170 private static function storeByGuid($guid, $server, $uid = 0)
1172 $serverparts = parse_url($server);
1173 $server = $serverparts["scheme"]."://".$serverparts["host"];
1175 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1177 $msg = self::message($guid, $server);
1183 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1185 // Now call the dispatcher
1186 return self::dispatchPublic($msg);
1190 * @brief Fetches a message from a server
1192 * @param string $guid message guid
1193 * @param string $server The url of the server
1194 * @param int $level Endless loop prevention
1197 * 'message' => The message XML
1198 * 'author' => The author handle
1199 * 'key' => The public key of the author
1201 private static function message($guid, $server, $level = 0)
1207 // This will work for new Diaspora servers and Friendica servers from 3.5
1208 $source_url = $server."/fetch/post/".urlencode($guid);
1210 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1212 $envelope = fetch_url($source_url);
1214 logger("Envelope was fetched.", LOGGER_DEBUG);
1215 $x = self::verifyMagicEnvelope($envelope);
1217 logger("Envelope could not be verified.", LOGGER_DEBUG);
1219 logger("Envelope was verified.", LOGGER_DEBUG);
1225 // This will work for older Diaspora and Friendica servers
1227 $source_url = $server."/p/".urlencode($guid).".xml";
1228 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1230 $x = fetch_url($source_url);
1236 $source_xml = parse_xml_string($x);
1238 if (!is_object($source_xml)) {
1242 if ($source_xml->post->reshare) {
1243 // Reshare of a reshare - old Diaspora version
1244 logger("Message is a reshare", LOGGER_DEBUG);
1245 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1246 } elseif ($source_xml->getName() == "reshare") {
1247 // Reshare of a reshare - new Diaspora version
1248 logger("Message is a new reshare", LOGGER_DEBUG);
1249 return self::message($source_xml->root_guid, $server, ++$level);
1254 // Fetch the author - for the old and the new Diaspora version
1255 if ($source_xml->post->status_message->diaspora_handle) {
1256 $author = (string)$source_xml->post->status_message->diaspora_handle;
1257 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1258 $author = (string)$source_xml->author;
1261 // If this isn't a "status_message" then quit
1263 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1267 $msg = array("message" => $x, "author" => $author);
1269 $msg["key"] = self::key($msg["author"]);
1275 * @brief Fetches the item record of a given guid
1277 * @param int $uid The user id
1278 * @param string $guid message guid
1279 * @param string $author The handle of the item
1280 * @param array $contact The contact of the item owner
1282 * @return array the item record
1284 private static function parentItem($uid, $guid, $author, $contact)
1287 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1288 `author-name`, `author-link`, `author-avatar`,
1289 `owner-name`, `owner-link`, `owner-avatar`
1290 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1296 $result = self::storeByGuid($guid, $contact["url"], $uid);
1299 $person = self::personByHandle($author);
1300 $result = self::storeByGuid($guid, $person["url"], $uid);
1304 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1307 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1308 `author-name`, `author-link`, `author-avatar`,
1309 `owner-name`, `owner-link`, `owner-avatar`
1310 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1318 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1321 logger("parent item found: parent: ".$guid." - user: ".$uid);
1327 * @brief returns contact details
1329 * @param array $contact The default contact if the person isn't found
1330 * @param array $person The record of the person
1331 * @param int $uid The user id
1334 * 'cid' => contact id
1335 * 'network' => network type
1337 private static function authorContactByUrl($contact, $person, $uid)
1340 "SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1341 dbesc(normalise_link($person["url"])),
1346 $network = $r[0]["network"];
1348 $cid = $contact["id"];
1349 $network = NETWORK_DIASPORA;
1352 return array("cid" => $cid, "network" => $network);
1356 * @brief Is the profile a hubzilla profile?
1358 * @param string $url The profile link
1360 * @return bool is it a hubzilla server?
1362 public static function isRedmatrix($url)
1364 return(strstr($url, "/channel/"));
1368 * @brief Generate a post link with a given handle and message guid
1370 * @param string $addr The user handle
1371 * @param string $guid message guid
1372 * @param string $parent_guid optional parent guid
1374 * @return string the post link
1376 private static function plink($addr, $guid, $parent_guid = '')
1378 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1381 if (!DBM::is_result($r)) {
1382 if ($parent_guid != '') {
1383 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1385 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1389 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1390 // So we try another way as well.
1391 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1392 if (DBM::is_result($s)) {
1393 $r[0]["network"] = $s[0]["network"];
1396 if ($r[0]["network"] == NETWORK_DFRN) {
1397 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1400 if (self::isRedmatrix($r[0]["url"])) {
1401 return $r[0]["url"]."/?f=&mid=".$guid;
1404 if ($parent_guid != '') {
1405 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1407 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1412 * @brief Receives account migration
1414 * @param array $importer Array of the importer user
1415 * @param object $data The message object
1417 * @return bool Success
1419 private static function receiveAccountMigration($importer, $data)
1421 $old_handle = notags(unxmlify($data->author));
1422 $new_handle = notags(unxmlify($data->profile->author));
1423 $signature = notags(unxmlify($data->signature));
1425 $contact = self::contactByHandle($importer["uid"], $old_handle);
1427 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1431 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1434 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1435 $key = self::key($old_handle);
1436 if (!rsa_verify($signed_text, $signature, $key, "sha256")) {
1437 logger('No valid signature for migration.');
1441 // Update the profile
1442 self::receiveProfile($importer, $data->profile);
1444 // change the technical stuff in contact and gcontact
1445 $data = Probe::uri($new_handle);
1446 if ($data['network'] == NETWORK_PHANTOM) {
1447 logger('Account for '.$new_handle." couldn't be probed.");
1451 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1452 'name' => $data['name'], 'nick' => $data['nick'],
1453 'addr' => $data['addr'], 'batch' => $data['batch'],
1454 'notify' => $data['notify'], 'poll' => $data['poll'],
1455 'network' => $data['network']);
1457 dba::update('contact', $fields, array('addr' => $old_handle));
1459 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1460 'name' => $data['name'], 'nick' => $data['nick'],
1461 'addr' => $data['addr'], 'connect' => $data['addr'],
1462 'notify' => $data['notify'], 'photo' => $data['photo'],
1463 'server_url' => $data['baseurl'], 'network' => $data['network']);
1465 dba::update('gcontact', $fields, array('addr' => $old_handle));
1467 logger('Contacts are updated.');
1470 /// @todo This is an extreme performance killer
1472 'owner-link' => array($contact["url"], $data["url"]),
1473 'author-link' => array($contact["url"], $data["url"]),
1475 foreach ($fields as $n => $f) {
1477 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1480 intval($importer["uid"])
1483 if (DBM::is_result($r)) {
1485 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1490 intval($importer["uid"])
1499 logger('Items are updated.');
1505 * @brief Processes an account deletion
1507 * @param array $importer Array of the importer user
1508 * @param object $data The message object
1510 * @return bool Success
1512 private static function receiveAccountDeletion($importer, $data)
1514 /// @todo Account deletion should remove the contact from the global contacts as well
1516 $author = notags(unxmlify($data->author));
1518 $contact = self::contactByHandle($importer["uid"], $author);
1520 logger("cannot find contact for author: ".$author);
1524 // We now remove the contact
1525 Contact::remove($contact["id"]);
1530 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1532 * @param string $author Author handle
1533 * @param string $guid Message guid
1534 * @param boolean $onlyfound Only return uri when found in the database
1536 * @return string The constructed uri or the one from our database
1538 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1540 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1541 if (DBM::is_result($r)) {
1542 return $r[0]["uri"];
1543 } elseif (!$onlyfound) {
1544 return $author.":".$guid;
1551 * @brief Fetch the guid from our database with a given uri
1553 * @param string $uri Message uri
1554 * @param string $uid Author handle
1556 * @return string The post guid
1558 private static function getGuidFromUri($uri, $uid)
1560 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1561 if (DBM::is_result($r)) {
1562 return $r[0]["guid"];
1569 * @brief Find the best importer for a comment, like, ...
1571 * @param string $guid The guid of the item
1573 * @return array|boolean the origin owner of that post - or false
1575 private static function importerForGuid($guid)
1577 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1579 if (DBM::is_result($item)) {
1580 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1581 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1582 if (DBM::is_result($contact)) {
1590 * @brief Processes an incoming comment
1592 * @param array $importer Array of the importer user
1593 * @param string $sender The sender of the message
1594 * @param object $data The message object
1595 * @param string $xml The original XML of the message
1597 * @return int The message id of the generated comment or "false" if there was an error
1599 private static function receiveComment($importer, $sender, $data, $xml)
1601 $author = notags(unxmlify($data->author));
1602 $guid = notags(unxmlify($data->guid));
1603 $parent_guid = notags(unxmlify($data->parent_guid));
1604 $text = unxmlify($data->text);
1606 if (isset($data->created_at)) {
1607 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1609 $created_at = datetime_convert();
1612 if (isset($data->thread_parent_guid)) {
1613 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1614 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1619 $contact = self::allowedContactByHandle($importer, $sender, true);
1624 $message_id = self::messageExists($importer["uid"], $guid);
1629 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1630 if (!$parent_item) {
1634 $person = self::personByHandle($author);
1635 if (!is_array($person)) {
1636 logger("unable to find author details");
1640 // Fetch the contact id - if we know this contact
1641 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1643 $datarray = array();
1645 $datarray["uid"] = $importer["uid"];
1646 $datarray["contact-id"] = $author_contact["cid"];
1647 $datarray["network"] = $author_contact["network"];
1649 $datarray["author-name"] = $person["name"];
1650 $datarray["author-link"] = $person["url"];
1651 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1653 $datarray["owner-name"] = $contact["name"];
1654 $datarray["owner-link"] = $contact["url"];
1655 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1657 $datarray["guid"] = $guid;
1658 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1660 $datarray["type"] = "remote-comment";
1661 $datarray["verb"] = ACTIVITY_POST;
1662 $datarray["gravity"] = GRAVITY_COMMENT;
1664 if ($thr_uri != "") {
1665 $datarray["parent-uri"] = $thr_uri;
1667 $datarray["parent-uri"] = $parent_item["uri"];
1670 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1672 $datarray["protocol"] = PROTOCOL_DIASPORA;
1673 $datarray["source"] = $xml;
1675 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1677 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1679 $body = diaspora2bb($text);
1681 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1683 self::fetchGuid($datarray);
1685 $message_id = item_store($datarray);
1687 if ($message_id <= 0) {
1692 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1695 // If we are the origin of the parent we store the original data and notify our followers
1696 if ($message_id && $parent_item["origin"]) {
1697 // Formerly we stored the signed text, the signature and the author in different fields.
1698 // We now store the raw data so that we are more flexible.
1699 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1702 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1709 * @brief processes and stores private messages
1711 * @param array $importer Array of the importer user
1712 * @param array $contact The contact of the message
1713 * @param object $data The message object
1714 * @param array $msg Array of the processed message, author handle and key
1715 * @param object $mesg The private message
1716 * @param array $conversation The conversation record to which this message belongs
1718 * @return bool "true" if it was successful
1720 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1722 $author = notags(unxmlify($data->author));
1723 $guid = notags(unxmlify($data->guid));
1724 $subject = notags(unxmlify($data->subject));
1726 // "diaspora_handle" is the element name from the old version
1727 // "author" is the element name from the new version
1728 if ($mesg->author) {
1729 $msg_author = notags(unxmlify($mesg->author));
1730 } elseif ($mesg->diaspora_handle) {
1731 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1736 $msg_guid = notags(unxmlify($mesg->guid));
1737 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1738 $msg_text = unxmlify($mesg->text);
1739 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1741 if ($msg_conversation_guid != $guid) {
1742 logger("message conversation guid does not belong to the current conversation.");
1746 $body = diaspora2bb($msg_text);
1747 $message_uri = $msg_author.":".$msg_guid;
1749 $person = self::personByHandle($msg_author);
1754 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1756 intval($importer["uid"])
1758 if (DBM::is_result($r)) {
1759 logger("duplicate message already delivered.", LOGGER_DEBUG);
1764 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1765 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1766 intval($importer["uid"]),
1768 intval($conversation["id"]),
1769 dbesc($person["name"]),
1770 dbesc($person["photo"]),
1771 dbesc($person["url"]),
1772 intval($contact["id"]),
1777 dbesc($message_uri),
1778 dbesc($author.":".$guid),
1779 dbesc($msg_created_at)
1784 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1788 "type" => NOTIFY_MAIL,
1789 "notify_flags" => $importer["notify-flags"],
1790 "language" => $importer["language"],
1791 "to_name" => $importer["username"],
1792 "to_email" => $importer["email"],
1793 "uid" =>$importer["uid"],
1794 "item" => array("subject" => $subject, "body" => $body),
1795 "source_name" => $person["name"],
1796 "source_link" => $person["url"],
1797 "source_photo" => $person["thumb"],
1798 "verb" => ACTIVITY_POST,
1805 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1807 * @param array $importer Array of the importer user
1808 * @param array $msg Array of the processed message, author handle and key
1809 * @param object $data The message object
1811 * @return bool Success
1813 private static function receiveConversation($importer, $msg, $data)
1815 $author = notags(unxmlify($data->author));
1816 $guid = notags(unxmlify($data->guid));
1817 $subject = notags(unxmlify($data->subject));
1818 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1819 $participants = notags(unxmlify($data->participants));
1821 $messages = $data->message;
1823 if (!count($messages)) {
1824 logger("empty conversation");
1828 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1833 $conversation = null;
1836 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1837 intval($importer["uid"]),
1841 $conversation = $c[0];
1844 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1845 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1846 intval($importer["uid"]),
1850 dbesc(datetime_convert()),
1852 dbesc($participants)
1856 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1857 intval($importer["uid"]),
1863 $conversation = $c[0];
1866 if (!$conversation) {
1867 logger("unable to create conversation.");
1871 foreach ($messages as $mesg) {
1872 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1879 * @brief Creates the body for a "like" message
1881 * @param array $contact The contact that send us the "like"
1882 * @param array $parent_item The item array of the parent item
1883 * @param string $guid message guid
1885 * @return string the body
1887 private static function constructLikeBody($contact, $parent_item, $guid)
1889 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1891 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1892 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1893 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1895 return sprintf($bodyverb, $ulink, $alink, $plink);
1899 * @brief Creates a XML object for a "like"
1901 * @param array $importer Array of the importer user
1902 * @param array $parent_item The item array of the parent item
1904 * @return string The XML
1906 private static function constructLikeObject($importer, $parent_item)
1908 $objtype = ACTIVITY_OBJ_NOTE;
1909 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1910 $parent_body = $parent_item["body"];
1912 $xmldata = array("object" => array("type" => $objtype,
1914 "id" => $parent_item["uri"],
1917 "content" => $parent_body));
1919 return XML::fromArray($xmldata, $xml, true);
1923 * @brief Processes "like" messages
1925 * @param array $importer Array of the importer user
1926 * @param string $sender The sender of the message
1927 * @param object $data The message object
1929 * @return int The message id of the generated like or "false" if there was an error
1931 private static function receiveLike($importer, $sender, $data)
1933 $author = notags(unxmlify($data->author));
1934 $guid = notags(unxmlify($data->guid));
1935 $parent_guid = notags(unxmlify($data->parent_guid));
1936 $parent_type = notags(unxmlify($data->parent_type));
1937 $positive = notags(unxmlify($data->positive));
1939 // likes on comments aren't supported by Diaspora - only on posts
1940 // But maybe this will be supported in the future, so we will accept it.
1941 if (!in_array($parent_type, array("Post", "Comment"))) {
1945 $contact = self::allowedContactByHandle($importer, $sender, true);
1950 $message_id = self::messageExists($importer["uid"], $guid);
1955 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1956 if (!$parent_item) {
1960 $person = self::personByHandle($author);
1961 if (!is_array($person)) {
1962 logger("unable to find author details");
1966 // Fetch the contact id - if we know this contact
1967 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1969 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1970 // We would accept this anyhow.
1971 if ($positive == "true") {
1972 $verb = ACTIVITY_LIKE;
1974 $verb = ACTIVITY_DISLIKE;
1977 $datarray = array();
1979 $datarray["protocol"] = PROTOCOL_DIASPORA;
1981 $datarray["uid"] = $importer["uid"];
1982 $datarray["contact-id"] = $author_contact["cid"];
1983 $datarray["network"] = $author_contact["network"];
1985 $datarray["author-name"] = $person["name"];
1986 $datarray["author-link"] = $person["url"];
1987 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1989 $datarray["owner-name"] = $contact["name"];
1990 $datarray["owner-link"] = $contact["url"];
1991 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1993 $datarray["guid"] = $guid;
1994 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1996 $datarray["type"] = "activity";
1997 $datarray["verb"] = $verb;
1998 $datarray["gravity"] = GRAVITY_LIKE;
1999 $datarray["parent-uri"] = $parent_item["uri"];
2001 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2002 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2004 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2006 $message_id = item_store($datarray);
2008 if ($message_id <= 0) {
2013 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2016 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2017 if ($parent_item["id"] != $parent_item["parent"]) {
2018 $toplevel = dba::select('item', array('origin'), array('id' => $parent_item["parent"]), array('limit' => 1));
2019 $origin = $toplevel["origin"];
2021 $origin = $parent_item["origin"];
2024 // If we are the origin of the parent we store the original data and notify our followers
2025 if ($message_id && $origin) {
2026 // Formerly we stored the signed text, the signature and the author in different fields.
2027 // We now store the raw data so that we are more flexible.
2028 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
2031 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2038 * @brief Processes private messages
2040 * @param array $importer Array of the importer user
2041 * @param object $data The message object
2043 * @return bool Success?
2045 private static function receiveMessage($importer, $data)
2047 $author = notags(unxmlify($data->author));
2048 $guid = notags(unxmlify($data->guid));
2049 $conversation_guid = notags(unxmlify($data->conversation_guid));
2050 $text = unxmlify($data->text);
2051 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2053 $contact = self::allowedContactByHandle($importer, $author, true);
2058 $conversation = null;
2061 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2062 intval($importer["uid"]),
2063 dbesc($conversation_guid)
2066 $conversation = $c[0];
2068 logger("conversation not available.");
2072 $message_uri = $author.":".$guid;
2074 $person = self::personByHandle($author);
2076 logger("unable to find author details");
2080 $body = diaspora2bb($text);
2082 $body = self::replacePeopleGuid($body, $person["url"]);
2087 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2089 intval($importer["uid"])
2091 if (DBM::is_result($r)) {
2092 logger("duplicate message already delivered.", LOGGER_DEBUG);
2097 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2098 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2099 intval($importer["uid"]),
2101 intval($conversation["id"]),
2102 dbesc($person["name"]),
2103 dbesc($person["photo"]),
2104 dbesc($person["url"]),
2105 intval($contact["id"]),
2106 dbesc($conversation["subject"]),
2110 dbesc($message_uri),
2111 dbesc($author.":".$conversation["guid"]),
2117 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
2122 * @brief Processes participations - unsupported by now
2124 * @param array $importer Array of the importer user
2125 * @param object $data The message object
2127 * @return bool always true
2129 private static function receiveParticipation($importer, $data)
2131 // I'm not sure if we can fully support this message type
2136 * @brief Processes photos - unneeded
2138 * @param array $importer Array of the importer user
2139 * @param object $data The message object
2141 * @return bool always true
2143 private static function receivePhoto($importer, $data)
2145 // There doesn't seem to be a reason for this function,
2146 // since the photo data is transmitted in the status message as well
2151 * @brief Processes poll participations - unssupported
2153 * @param array $importer Array of the importer user
2154 * @param object $data The message object
2156 * @return bool always true
2158 private static function receivePollParticipation($importer, $data)
2160 // We don't support polls by now
2165 * @brief Processes incoming profile updates
2167 * @param array $importer Array of the importer user
2168 * @param object $data The message object
2170 * @return bool Success
2172 private static function receiveProfile($importer, $data)
2174 $author = strtolower(notags(unxmlify($data->author)));
2176 $contact = self::contactByHandle($importer["uid"], $author);
2181 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2182 $image_url = unxmlify($data->image_url);
2183 $birthday = unxmlify($data->birthday);
2184 $gender = unxmlify($data->gender);
2185 $about = diaspora2bb(unxmlify($data->bio));
2186 $location = diaspora2bb(unxmlify($data->location));
2187 $searchable = (unxmlify($data->searchable) == "true");
2188 $nsfw = (unxmlify($data->nsfw) == "true");
2189 $tags = unxmlify($data->tag_string);
2191 $tags = explode("#", $tags);
2193 $keywords = array();
2194 foreach ($tags as $tag) {
2195 $tag = trim(strtolower($tag));
2201 $keywords = implode(", ", $keywords);
2203 $handle_parts = explode("@", $author);
2204 $nick = $handle_parts[0];
2207 $name = $handle_parts[0];
2210 if (preg_match("|^https?://|", $image_url) === 0) {
2211 $image_url = "http://".$handle_parts[1].$image_url;
2214 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2216 // Generic birthday. We don't know the timezone. The year is irrelevant.
2218 $birthday = str_replace("1000", "1901", $birthday);
2220 if ($birthday != "") {
2221 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
2224 // this is to prevent multiple birthday notifications in a single year
2225 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2227 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2228 $birthday = $contact["bd"];
2232 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2233 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2237 dbesc(datetime_convert()),
2243 intval($contact["id"]),
2244 intval($importer["uid"])
2247 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2248 "photo" => $image_url, "name" => $name, "location" => $location,
2249 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2250 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2251 "hide" => !$searchable, "nsfw" => $nsfw);
2253 $gcid = GContact::update($gcontact);
2255 GContact::link($gcid, $importer["uid"], $contact["id"]);
2257 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2263 * @brief Processes incoming friend requests
2265 * @param array $importer Array of the importer user
2266 * @param array $contact The contact that send the request
2269 private static function receiveRequestMakeFriend($importer, $contact)
2273 if ($contact["rel"] == CONTACT_IS_SHARING) {
2276 array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
2277 array('id' => $contact["id"], 'uid' => $importer["uid"])
2280 // send notification
2283 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2284 intval($importer["uid"])
2287 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2289 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2290 intval($importer["uid"])
2293 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2295 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2297 $arr["protocol"] = PROTOCOL_DIASPORA;
2298 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2299 $arr["uid"] = $importer["uid"];
2300 $arr["contact-id"] = $self[0]["id"];
2302 $arr["type"] = 'wall';
2303 $arr["gravity"] = 0;
2305 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2306 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2307 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2308 $arr["verb"] = ACTIVITY_FRIEND;
2309 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2311 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2312 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2313 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2314 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2316 $arr["object"] = self::constructNewFriendObject($contact);
2318 $arr["last-child"] = 1;
2320 $arr["allow_cid"] = $user[0]["allow_cid"];
2321 $arr["allow_gid"] = $user[0]["allow_gid"];
2322 $arr["deny_cid"] = $user[0]["deny_cid"];
2323 $arr["deny_gid"] = $user[0]["deny_gid"];
2325 $i = item_store($arr);
2327 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2334 * @brief Creates a XML object for a "new friend" message
2336 * @param array $contact Array of the contact
2338 * @return string The XML
2340 private static function constructNewFriendObject($contact)
2342 $objtype = ACTIVITY_OBJ_PERSON;
2343 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2344 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2346 $xmldata = array("object" => array("type" => $objtype,
2347 "title" => $contact["name"],
2348 "id" => $contact["url"]."/".$contact["name"],
2351 return XML::fromArray($xmldata, $xml, true);
2355 * @brief Processes incoming sharing notification
2357 * @param array $importer Array of the importer user
2358 * @param object $data The message object
2360 * @return bool Success
2362 private static function receiveContactRequest($importer, $data)
2364 $author = unxmlify($data->author);
2365 $recipient = unxmlify($data->recipient);
2367 if (!$author || !$recipient) {
2371 // the current protocol version doesn't know these fields
2372 // That means that we will assume their existance
2373 if (isset($data->following)) {
2374 $following = (unxmlify($data->following) == "true");
2379 if (isset($data->sharing)) {
2380 $sharing = (unxmlify($data->sharing) == "true");
2385 $contact = self::contactByHandle($importer["uid"], $author);
2387 // perhaps we were already sharing with this person. Now they're sharing with us.
2388 // That makes us friends.
2391 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2392 self::receiveRequestMakeFriend($importer, $contact);
2394 // refetch the contact array
2395 $contact = self::contactByHandle($importer["uid"], $author);
2397 // If we are now friends, we are sending a share message.
2398 // Normally we needn't to do so, but the first message could have been vanished.
2399 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND))) {
2400 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2402 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2403 $ret = self::sendShare($u[0], $contact);
2408 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2409 lose_follower($importer, $contact);
2414 if (!$following && $sharing && in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2415 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2417 } elseif (!$following && !$sharing) {
2418 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2420 } elseif (!$following && $sharing) {
2421 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2422 } elseif ($following && $sharing) {
2423 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2424 } elseif ($following && !$sharing) {
2425 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2428 $ret = self::personByHandle($author);
2430 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2431 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2435 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2438 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2439 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2440 intval($importer["uid"]),
2441 dbesc($ret["network"]),
2442 dbesc($ret["addr"]),
2445 dbesc(normalise_link($ret["url"])),
2447 dbesc($ret["name"]),
2448 dbesc($ret["nick"]),
2449 dbesc($ret["photo"]),
2450 dbesc($ret["pubkey"]),
2451 dbesc($ret["notify"]),
2452 dbesc($ret["poll"]),
2457 // find the contact record we just created
2459 $contact_record = self::contactByHandle($importer["uid"], $author);
2461 if (!$contact_record) {
2462 logger("unable to locate newly created contact record.");
2466 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2468 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2470 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2472 if ($importer["page-flags"] == PAGE_NORMAL) {
2473 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2475 $hash = random_string().(string)time(); // Generate a confirm_key
2478 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2479 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2480 intval($importer["uid"]),
2481 intval($contact_record["id"]),
2484 dbesc(t("Sharing notification from Diaspora network")),
2486 dbesc(datetime_convert())
2489 // automatic friend approval
2491 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2493 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2495 // technically they are sharing with us (CONTACT_IS_SHARING),
2496 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2497 // we are going to change the relationship and make them a follower.
2499 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2500 $new_relation = CONTACT_IS_FRIEND;
2501 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2502 $new_relation = CONTACT_IS_SHARING;
2504 $new_relation = CONTACT_IS_FOLLOWER;
2508 "UPDATE `contact` SET `rel` = %d,
2516 intval($new_relation),
2517 dbesc(datetime_convert()),
2518 dbesc(datetime_convert()),
2519 intval($contact_record["id"])
2522 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2524 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2525 $ret = self::sendShare($u[0], $contact_record);
2527 // Send the profile data, maybe it weren't transmitted before
2528 self::sendProfile($importer["uid"], array($contact_record));
2536 * @brief Fetches a message with a given guid
2538 * @param string $guid message guid
2539 * @param string $orig_author handle of the original post
2540 * @param string $author handle of the sharer
2542 * @return array The fetched item
2544 private static function originalItem($guid, $orig_author, $author)
2546 // Do we already have this item?
2548 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2549 `author-name`, `author-link`, `author-avatar`
2550 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2554 if (DBM::is_result($r)) {
2555 logger("reshared message ".$guid." already exists on system.");
2557 // Maybe it is already a reshared item?
2558 // Then refetch the content, if it is a reshare from a reshare.
2559 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2560 if (self::isReshare($r[0]["body"], true)) {
2562 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2563 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2565 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2567 // Add OEmbed and other information to the body
2568 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2576 if (!DBM::is_result($r)) {
2577 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2578 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2579 $item_id = self::storeByGuid($guid, $server);
2582 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2583 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2584 $item_id = self::storeByGuid($guid, $server);
2589 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2590 `author-name`, `author-link`, `author-avatar`
2591 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2595 if (DBM::is_result($r)) {
2596 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2597 if (self::isReshare($r[0]["body"], false)) {
2598 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2599 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2610 * @brief Processes a reshare message
2612 * @param array $importer Array of the importer user
2613 * @param object $data The message object
2614 * @param string $xml The original XML of the message
2616 * @return int the message id
2618 private static function receiveReshare($importer, $data, $xml)
2620 $author = notags(unxmlify($data->author));
2621 $guid = notags(unxmlify($data->guid));
2622 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2623 $root_author = notags(unxmlify($data->root_author));
2624 $root_guid = notags(unxmlify($data->root_guid));
2625 /// @todo handle unprocessed property "provider_display_name"
2626 $public = notags(unxmlify($data->public));
2628 $contact = self::allowedContactByHandle($importer, $author, false);
2633 $message_id = self::messageExists($importer["uid"], $guid);
2638 $original_item = self::originalItem($root_guid, $root_author, $author);
2639 if (!$original_item) {
2643 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2645 $datarray = array();
2647 $datarray["uid"] = $importer["uid"];
2648 $datarray["contact-id"] = $contact["id"];
2649 $datarray["network"] = NETWORK_DIASPORA;
2651 $datarray["author-name"] = $contact["name"];
2652 $datarray["author-link"] = $contact["url"];
2653 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2655 $datarray["owner-name"] = $datarray["author-name"];
2656 $datarray["owner-link"] = $datarray["author-link"];
2657 $datarray["owner-avatar"] = $datarray["author-avatar"];
2659 $datarray["guid"] = $guid;
2660 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2662 $datarray["verb"] = ACTIVITY_POST;
2663 $datarray["gravity"] = GRAVITY_PARENT;
2665 $datarray["protocol"] = PROTOCOL_DIASPORA;
2666 $datarray["source"] = $xml;
2668 $prefix = share_header(
2669 $original_item["author-name"],
2670 $original_item["author-link"],
2671 $original_item["author-avatar"],
2672 $original_item["guid"],
2673 $original_item["created"],
2676 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2678 $datarray["tag"] = $original_item["tag"];
2679 $datarray["app"] = $original_item["app"];
2681 $datarray["plink"] = self::plink($author, $guid);
2682 $datarray["private"] = (($public == "false") ? 1 : 0);
2683 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2685 $datarray["object-type"] = $original_item["object-type"];
2687 self::fetchGuid($datarray);
2688 $message_id = item_store($datarray);
2691 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2699 * @brief Processes retractions
2701 * @param array $importer Array of the importer user
2702 * @param array $contact The contact of the item owner
2703 * @param object $data The message object
2705 * @return bool success
2707 private static function itemRetraction($importer, $contact, $data)
2709 $author = notags(unxmlify($data->author));
2710 $target_guid = notags(unxmlify($data->target_guid));
2711 $target_type = notags(unxmlify($data->target_type));
2713 $person = self::personByHandle($author);
2714 if (!is_array($person)) {
2715 logger("unable to find author detail for ".$author);
2719 if (empty($contact["url"])) {
2720 $contact["url"] = $person["url"];
2723 // Fetch items that are about to be deleted
2724 $fields = array('uid', 'id', 'parent', 'parent-uri', 'author-link');
2726 // When we receive a public retraction, we delete every item that we find.
2727 if ($importer['uid'] == 0) {
2728 $condition = array("`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid);
2730 $condition = array("`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']);
2732 $r = dba::select('item', $fields, $condition);
2733 if (!DBM::is_result($r)) {
2734 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2738 while ($item = dba::fetch($r)) {
2739 // Fetch the parent item
2740 $parent = dba::select('item', array('author-link', 'origin'), array('id' => $item["parent"]), array('limit' => 1));
2742 // Only delete it if the parent author really fits
2743 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2744 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2748 // Currently we don't have a central deletion function that we could use in this case.
2749 // The function "item_drop" doesn't work for that case
2756 'edited' => datetime_convert(),
2757 'changed' => datetime_convert()),
2758 array('id' => $item["id"])
2761 // Delete the thread - if it is a starting post and not a comment
2762 if ($target_type != 'Comment') {
2763 delete_thread($item["id"], $item["parent-uri"]);
2766 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2768 // Now check if the retraction needs to be relayed by us
2769 if ($parent["origin"]) {
2771 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2779 * @brief Receives retraction messages
2781 * @param array $importer Array of the importer user
2782 * @param string $sender The sender of the message
2783 * @param object $data The message object
2785 * @return bool Success
2787 private static function receiveRetraction($importer, $sender, $data)
2789 $target_type = notags(unxmlify($data->target_type));
2791 $contact = self::contactByHandle($importer["uid"], $sender);
2792 if (!$contact && (in_array($target_type, array("Contact", "Person")))) {
2793 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2797 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2799 switch ($target_type) {
2804 case "StatusMessage":
2805 return self::itemRetraction($importer, $contact, $data);
2809 /// @todo What should we do with an "unshare"?
2810 // Removing the contact isn't correct since we still can read the public items
2811 Contact::remove($contact["id"]);
2815 logger("Unknown target type ".$target_type);
2822 * @brief Receives status messages
2824 * @param array $importer Array of the importer user
2825 * @param object $data The message object
2826 * @param string $xml The original XML of the message
2828 * @return int The message id of the newly created item
2830 private static function receiveStatusMessage($importer, $data, $xml)
2832 $author = notags(unxmlify($data->author));
2833 $guid = notags(unxmlify($data->guid));
2834 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2835 $public = notags(unxmlify($data->public));
2836 $text = unxmlify($data->text);
2837 $provider_display_name = notags(unxmlify($data->provider_display_name));
2839 $contact = self::allowedContactByHandle($importer, $author, false);
2844 $message_id = self::messageExists($importer["uid"], $guid);
2850 if ($data->location) {
2851 foreach ($data->location->children() as $fieldname => $data) {
2852 $address[$fieldname] = notags(unxmlify($data));
2856 $body = diaspora2bb($text);
2858 $datarray = array();
2860 // Attach embedded pictures to the body
2862 foreach ($data->photo as $photo) {
2863 $body = "[img]".unxmlify($photo->remote_photo_path).
2864 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2867 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2869 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2871 // Add OEmbed and other information to the body
2872 if (!self::isRedmatrix($contact["url"])) {
2873 $body = add_page_info_to_body($body, false, true);
2877 /// @todo enable support for polls
2878 //if ($data->poll) {
2879 // foreach ($data->poll AS $poll)
2884 /// @todo enable support for events
2886 $datarray["uid"] = $importer["uid"];
2887 $datarray["contact-id"] = $contact["id"];
2888 $datarray["network"] = NETWORK_DIASPORA;
2890 $datarray["author-name"] = $contact["name"];
2891 $datarray["author-link"] = $contact["url"];
2892 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2894 $datarray["owner-name"] = $datarray["author-name"];
2895 $datarray["owner-link"] = $datarray["author-link"];
2896 $datarray["owner-avatar"] = $datarray["author-avatar"];
2898 $datarray["guid"] = $guid;
2899 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2901 $datarray["verb"] = ACTIVITY_POST;
2902 $datarray["gravity"] = GRAVITY_PARENT;
2904 $datarray["protocol"] = PROTOCOL_DIASPORA;
2905 $datarray["source"] = $xml;
2907 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2909 if ($provider_display_name != "") {
2910 $datarray["app"] = $provider_display_name;
2913 $datarray["plink"] = self::plink($author, $guid);
2914 $datarray["private"] = (($public == "false") ? 1 : 0);
2915 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2917 if (isset($address["address"])) {
2918 $datarray["location"] = $address["address"];
2921 if (isset($address["lat"]) && isset($address["lng"])) {
2922 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2925 self::fetchGuid($datarray);
2926 $message_id = item_store($datarray);
2929 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2936 /* ************************************************************************************** *
2937 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2938 * ************************************************************************************** */
2941 * @brief returnes the handle of a contact
2943 * @param array $contact contact array
2945 * @return string the handle in the format user@domain.tld
2947 private static function myHandle($contact)
2949 if ($contact["addr"] != "") {
2950 return $contact["addr"];
2953 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2954 // So - just in case - we build the the address here.
2955 if ($contact["nickname"] != "") {
2956 $nick = $contact["nickname"];
2958 $nick = $contact["nick"];
2961 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2966 * @brief Creates the data for a private message in the new format
2968 * @param string $msg The message that is to be transmitted
2969 * @param array $user The record of the sender
2970 * @param array $contact Target of the communication
2971 * @param string $prvkey The private key of the sender
2972 * @param string $pubkey The public key of the receiver
2974 * @return string The encrypted data
2976 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
2978 logger("Message: ".$msg, LOGGER_DATA);
2980 // without a public key nothing will work
2982 logger("pubkey missing: contact id: ".$contact["id"]);
2986 $aes_key = openssl_random_pseudo_bytes(32);
2987 $b_aes_key = base64_encode($aes_key);
2988 $iv = openssl_random_pseudo_bytes(16);
2989 $b_iv = base64_encode($iv);
2991 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2993 $json = json_encode(array("iv" => $b_iv, "key" => $b_aes_key));
2995 $encrypted_key_bundle = "";
2996 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2998 $json_object = json_encode(
2999 array("aes_key" => base64_encode($encrypted_key_bundle),
3000 "encrypted_magic_envelope" => base64_encode($ciphertext))
3003 return $json_object;
3007 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3009 * @param string $msg The message that is to be transmitted
3010 * @param array $user The record of the sender
3012 * @return string The envelope
3014 public static function buildMagicEnvelope($msg, $user)
3016 $b64url_data = base64url_encode($msg);
3017 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
3019 $key_id = base64url_encode(self::myHandle($user));
3020 $type = "application/xml";
3021 $encoding = "base64url";
3022 $alg = "RSA-SHA256";
3023 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3025 // Fallback if the private key wasn't transmitted in the expected field
3026 if ($user['uprvkey'] == "") {
3027 $user['uprvkey'] = $user['prvkey'];
3030 $signature = rsa_sign($signable_data, $user["uprvkey"]);
3031 $sig = base64url_encode($signature);
3033 $xmldata = array("me:env" => array("me:data" => $data,
3034 "@attributes" => array("type" => $type),
3035 "me:encoding" => $encoding,
3038 "@attributes2" => array("key_id" => $key_id)));
3040 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
3042 return XML::fromArray($xmldata, $xml, false, $namespaces);
3046 * @brief Create the envelope for a message
3048 * @param string $msg The message that is to be transmitted
3049 * @param array $user The record of the sender
3050 * @param array $contact Target of the communication
3051 * @param string $prvkey The private key of the sender
3052 * @param string $pubkey The public key of the receiver
3053 * @param bool $public Is the message public?
3055 * @return string The message that will be transmitted to other servers
3057 private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3059 // The message is put into an envelope with the sender's signature
3060 $envelope = self::buildMagicEnvelope($msg, $user);
3062 // Private messages are put into a second envelope, encrypted with the receivers public key
3064 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3071 * @brief Creates a signature for a message
3073 * @param array $owner the array of the owner of the message
3074 * @param array $message The message that is to be signed
3076 * @return string The signature
3078 private static function signature($owner, $message)
3081 unset($sigmsg["author_signature"]);
3082 unset($sigmsg["parent_author_signature"]);
3084 $signed_text = implode(";", $sigmsg);
3086 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3090 * @brief Transmit a message to a target server
3092 * @param array $owner the array of the item owner
3093 * @param array $contact Target of the communication
3094 * @param string $envelope The message that is to be transmitted
3095 * @param bool $public_batch Is it a public post?
3096 * @param bool $queue_run Is the transmission called from the queue?
3097 * @param string $guid message guid
3099 * @return int Result of the transmission
3101 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "")
3105 $enabled = intval(Config::get("system", "diaspora_enabled"));
3110 $logid = random_string(4);
3111 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
3113 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3117 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3119 if (!$queue_run && was_recently_delayed($contact["id"])) {
3122 if (!intval(Config::get("system", "diaspora_test"))) {
3123 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3125 post_url($dest_url."/", $envelope, array("Content-Type: ".$content_type));
3126 $return_code = $a->get_curl_code();
3128 logger("test_mode");
3133 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3135 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3136 logger("queue message");
3139 "SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
3140 intval($contact["id"]),
3141 dbesc(NETWORK_DIASPORA),
3143 intval($public_batch)
3146 logger("add_to_queue ignored - identical item already in queue");
3148 // queue message for redelivery
3149 add_to_queue($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
3151 // The message could not be delivered. We mark the contact as "dead"
3152 Contact::markForArchival($contact);
3154 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3155 // We successfully delivered a message, the contact is alive
3156 Contact::unmarkForArchival($contact);
3159 return(($return_code) ? $return_code : (-1));
3164 * @brief Build the post xml
3166 * @param string $type The message type
3167 * @param array $message The message data
3169 * @return string The post XML
3171 public static function buildPostXml($type, $message)
3173 $data = array($type => $message);
3175 return XML::fromArray($data, $xml);
3179 * @brief Builds and transmit messages
3181 * @param array $owner the array of the item owner
3182 * @param array $contact Target of the communication
3183 * @param string $type The message type
3184 * @param array $message The message data
3185 * @param bool $public_batch Is it a public post?
3186 * @param string $guid message guid
3187 * @param bool $spool Should the transmission be spooled or transmitted?
3189 * @return int Result of the transmission
3191 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3193 $msg = self::buildPostXml($type, $message);
3195 logger('message: '.$msg, LOGGER_DATA);
3196 logger('send guid '.$guid, LOGGER_DEBUG);
3198 // Fallback if the private key wasn't transmitted in the expected field
3199 if ($owner['uprvkey'] == "") {
3200 $owner['uprvkey'] = $owner['prvkey'];
3203 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3206 add_to_queue($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3209 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3212 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
3214 return $return_code;
3218 * @brief sends an account migration
3220 * @param array $owner the array of the item owner
3221 * @param array $contact Target of the communication
3222 * @param int $uid User ID
3224 * @return int The result of the transmission
3226 public static function sendAccountMigration($owner, $contact, $uid)
3228 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3229 $profile = self::createProfileData($uid);
3231 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3232 $signature = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3234 $message = array("author" => $old_handle,
3235 "profile" => $profile,
3236 "signature" => $signature);
3238 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3240 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3244 * @brief Sends a "share" message
3246 * @param array $owner the array of the item owner
3247 * @param array $contact Target of the communication
3249 * @return int The result of the transmission
3251 public static function sendShare($owner, $contact)
3254 * @todo support the different possible combinations of "following" and "sharing"
3255 * Currently, Diaspora only interprets the "sharing" field
3257 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3261 switch ($contact["rel"]) {
3262 case CONTACT_IS_FRIEND:
3265 case CONTACT_IS_SHARING:
3268 case CONTACT_IS_FOLLOWER:
3274 $message = array("author" => self::myHandle($owner),
3275 "recipient" => $contact["addr"],
3276 "following" => "true",
3277 "sharing" => "true");
3279 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3281 return self::buildAndTransmit($owner, $contact, "contact", $message);
3285 * @brief sends an "unshare"
3287 * @param array $owner the array of the item owner
3288 * @param array $contact Target of the communication
3290 * @return int The result of the transmission
3292 public static function sendUnshare($owner, $contact)
3294 $message = array("author" => self::myHandle($owner),
3295 "recipient" => $contact["addr"],
3296 "following" => "false",
3297 "sharing" => "false");
3299 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3301 return self::buildAndTransmit($owner, $contact, "contact", $message);
3305 * @brief Checks a message body if it is a reshare
3307 * @param string $body The message body that is to be check
3308 * @param bool $complete Should it be a complete check or a simple check?
3310 * @return array|bool Reshare details or "false" if no reshare
3312 public static function isReshare($body, $complete = true)
3314 $body = trim($body);
3316 // Skip if it isn't a pure repeated messages
3317 // Does it start with a share?
3318 if ((strpos($body, "[share") > 0) && $complete) {
3322 // Does it end with a share?
3323 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3327 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3328 // Skip if there is no shared message in there
3329 if ($body == $attributes) {
3333 // If we don't do the complete check we quit here
3339 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3340 if ($matches[1] != "") {
3341 $guid = $matches[1];
3344 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3345 if ($matches[1] != "") {
3346 $guid = $matches[1];
3351 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3358 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3359 $ret["root_guid"] = $guid;
3365 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3366 if ($matches[1] != "") {
3367 $profile = $matches[1];
3370 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3371 if ($matches[1] != "") {
3372 $profile = $matches[1];
3377 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3378 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3383 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3384 if ($matches[1] != "") {
3385 $link = $matches[1];
3388 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3389 if ($matches[1] != "") {
3390 $link = $matches[1];
3393 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3394 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3402 * @brief Create an event array
3404 * @param integer $event_id The id of the event
3406 * @return array with event data
3408 private static function buildEvent($event_id)
3410 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3411 if (!DBM::is_result($r)) {
3417 $eventdata = array();
3419 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3420 if (!DBM::is_result($r)) {
3426 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3427 if (!DBM::is_result($r)) {
3433 $eventdata['author'] = self::myHandle($owner);
3435 if ($event['guid']) {
3436 $eventdata['guid'] = $event['guid'];
3439 $mask = 'Y-m-d\TH:i:s\Z';
3441 /// @todo - establish "all day" events in Friendica
3442 $eventdata["all_day"] = "false";
3444 if (!$event['adjust']) {
3445 $eventdata['timezone'] = $user['timezone'];
3447 if ($eventdata['timezone'] == "") {
3448 $eventdata['timezone'] = 'UTC';
3452 if ($event['start']) {
3453 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3455 if ($event['finish'] && !$event['nofinish']) {
3456 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3458 if ($event['summary']) {
3459 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3461 if ($event['desc']) {
3462 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3464 if ($event['location']) {
3465 $location = array();
3466 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3467 $location["lat"] = 0;
3468 $location["lng"] = 0;
3469 $eventdata['location'] = $location;
3476 * @brief Create a post (status message or reshare)
3478 * @param array $item The item that will be exported
3479 * @param array $owner the array of the item owner
3482 * 'type' -> Message type ("status_message" or "reshare")
3483 * 'message' -> Array of XML elements of the status
3485 public static function buildStatus($item, $owner)
3487 $cachekey = "diaspora:buildStatus:".$item['guid'];
3489 $result = Cache::get($cachekey);
3490 if (!is_null($result)) {
3494 $myaddr = self::myHandle($owner);
3496 $public = (($item["private"]) ? "false" : "true");
3498 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3500 // Detect a share element and do a reshare
3501 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3502 $message = array("author" => $myaddr,
3503 "guid" => $item["guid"],
3504 "created_at" => $created,
3505 "root_author" => $ret["root_handle"],
3506 "root_guid" => $ret["root_guid"],
3507 "provider_display_name" => $item["app"],
3508 "public" => $public);
3512 $title = $item["title"];
3513 $body = $item["body"];
3515 // convert to markdown
3516 $body = html_entity_decode(bb2diaspora($body));
3519 if (strlen($title)) {
3520 $body = "## ".html_entity_decode($title)."\n\n".$body;
3523 if ($item["attach"]) {
3524 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3526 $body .= "\n".t("Attachments:")."\n";
3527 foreach ($matches as $mtch) {
3528 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3533 $location = array();
3535 if ($item["location"] != "")
3536 $location["address"] = $item["location"];
3538 if ($item["coord"] != "") {
3539 $coord = explode(" ", $item["coord"]);
3540 $location["lat"] = $coord[0];
3541 $location["lng"] = $coord[1];
3544 $message = array("author" => $myaddr,
3545 "guid" => $item["guid"],
3546 "created_at" => $created,
3547 "public" => $public,
3549 "provider_display_name" => $item["app"],
3550 "location" => $location);
3552 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3553 if (!isset($location["lat"]) || !isset($location["lng"])) {
3554 unset($message["location"]);
3557 if ($item['event-id'] > 0) {
3558 $event = self::buildEvent($item['event-id']);
3559 if (count($event)) {
3560 $message['event'] = $event;
3562 /// @todo Once Diaspora supports it, we will remove the body
3563 // $message['text'] = '';
3567 $type = "status_message";
3570 $msg = array("type" => $type, "message" => $message);
3572 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3578 * @brief Sends a post
3580 * @param array $item The item that will be exported
3581 * @param array $owner the array of the item owner
3582 * @param array $contact Target of the communication
3583 * @param bool $public_batch Is it a public post?
3585 * @return int The result of the transmission
3587 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3589 $status = self::buildStatus($item, $owner);
3591 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3595 * @brief Creates a "like" object
3597 * @param array $item The item that will be exported
3598 * @param array $owner the array of the item owner
3600 * @return array The data for a "like"
3602 private static function constructLike($item, $owner)
3605 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3606 dbesc($item["thr-parent"])
3608 if (!DBM::is_result($p)) {
3614 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3615 if ($item['verb'] === ACTIVITY_LIKE) {
3617 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3618 $positive = "false";
3621 return(array("author" => self::myHandle($owner),
3622 "guid" => $item["guid"],
3623 "parent_guid" => $parent["guid"],
3624 "parent_type" => $target_type,
3625 "positive" => $positive,
3626 "author_signature" => ""));
3630 * @brief Creates an "EventParticipation" object
3632 * @param array $item The item that will be exported
3633 * @param array $owner the array of the item owner
3635 * @return array The data for an "EventParticipation"
3637 private static function constructAttend($item, $owner)
3640 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3641 dbesc($item["thr-parent"])
3643 if (!DBM::is_result($p)) {
3649 switch ($item['verb']) {
3650 case ACTIVITY_ATTEND:
3651 $attend_answer = 'accepted';
3653 case ACTIVITY_ATTENDNO:
3654 $attend_answer = 'declined';
3656 case ACTIVITY_ATTENDMAYBE:
3657 $attend_answer = 'tentative';
3660 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3664 return(array("author" => self::myHandle($owner),
3665 "guid" => $item["guid"],
3666 "parent_guid" => $parent["guid"],
3667 "status" => $attend_answer,
3668 "author_signature" => ""));
3672 * @brief Creates the object for a comment
3674 * @param array $item The item that will be exported
3675 * @param array $owner the array of the item owner
3677 * @return array The data for a comment
3679 private static function constructComment($item, $owner)
3681 $cachekey = "diaspora:constructComment:".$item['guid'];
3683 $result = Cache::get($cachekey);
3684 if (!is_null($result)) {
3689 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3690 intval($item["parent"]),
3691 intval($item["parent"])
3694 if (!DBM::is_result($p)) {
3700 $text = html_entity_decode(bb2diaspora($item["body"]));
3701 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3703 $comment = array("author" => self::myHandle($owner),
3704 "guid" => $item["guid"],
3705 "created_at" => $created,
3706 "parent_guid" => $parent["guid"],
3708 "author_signature" => "");
3710 // Send the thread parent guid only if it is a threaded comment
3711 if ($item['thr-parent'] != $item['parent-uri']) {
3712 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3715 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3721 * @brief Send a like or a comment
3723 * @param array $item The item that will be exported
3724 * @param array $owner the array of the item owner
3725 * @param array $contact Target of the communication
3726 * @param bool $public_batch Is it a public post?
3728 * @return int The result of the transmission
3730 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3732 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3733 $message = self::constructAttend($item, $owner);
3734 $type = "event_participation";
3735 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3736 $message = self::constructLike($item, $owner);
3739 $message = self::constructComment($item, $owner);
3747 $message["author_signature"] = self::signature($owner, $message);
3749 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3753 * @brief Creates a message from a signature record entry
3755 * @param array $item The item that will be exported
3756 * @param array $signature The entry of the "sign" record
3758 * @return string The message
3760 private static function messageFromSignature($item, $signature)
3762 // Split the signed text
3763 $signed_parts = explode(";", $signature['signed_text']);
3765 if ($item["deleted"]) {
3766 $message = array("author" => $signature['signer'],
3767 "target_guid" => $signed_parts[0],
3768 "target_type" => $signed_parts[1]);
3769 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3770 $message = array("author" => $signed_parts[4],
3771 "guid" => $signed_parts[1],
3772 "parent_guid" => $signed_parts[3],
3773 "parent_type" => $signed_parts[2],
3774 "positive" => $signed_parts[0],
3775 "author_signature" => $signature['signature'],
3776 "parent_author_signature" => "");
3778 // Remove the comment guid
3779 $guid = array_shift($signed_parts);
3781 // Remove the parent guid
3782 $parent_guid = array_shift($signed_parts);
3784 // Remove the handle
3785 $handle = array_pop($signed_parts);
3787 // Glue the parts together
3788 $text = implode(";", $signed_parts);
3790 $message = array("author" => $handle,
3792 "parent_guid" => $parent_guid,
3793 "text" => implode(";", $signed_parts),
3794 "author_signature" => $signature['signature'],
3795 "parent_author_signature" => "");
3801 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3803 * @param array $item The item that will be exported
3804 * @param array $owner the array of the item owner
3805 * @param array $contact Target of the communication
3806 * @param bool $public_batch Is it a public post?
3808 * @return int The result of the transmission
3810 public static function sendRelay($item, $owner, $contact, $public_batch = false)
3812 if ($item["deleted"]) {
3813 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3814 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3820 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3822 // fetch the original signature
3825 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3830 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3836 // Old way - is used by the internal Friendica functions
3837 /// @todo Change all signatur storing functions to the new format
3838 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3839 $message = self::messageFromSignature($item, $signature);
3841 $msg = json_decode($signature['signed_text'], true);
3844 if (is_array($msg)) {
3845 foreach ($msg as $field => $data) {
3846 if (!$item["deleted"]) {
3847 if ($field == "diaspora_handle") {
3850 if ($field == "target_type") {
3851 $field = "parent_type";
3855 $message[$field] = $data;
3858 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3862 $message["parent_author_signature"] = self::signature($owner, $message);
3864 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3866 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3870 * @brief Sends a retraction (deletion) of a message, like or comment
3872 * @param array $item The item that will be exported
3873 * @param array $owner the array of the item owner
3874 * @param array $contact Target of the communication
3875 * @param bool $public_batch Is it a public post?
3876 * @param bool $relay Is the retraction transmitted from a relay?
3878 * @return int The result of the transmission
3880 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
3882 $itemaddr = self::handleFromContact($item["contact-id"], $item["gcontact-id"]);
3884 $msg_type = "retraction";
3886 if ($item['id'] == $item['parent']) {
3887 $target_type = "Post";
3888 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3889 $target_type = "Like";
3891 $target_type = "Comment";
3894 $message = array("author" => $itemaddr,
3895 "target_guid" => $item['guid'],
3896 "target_type" => $target_type);
3898 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3900 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3904 * @brief Sends a mail
3906 * @param array $item The item that will be exported
3907 * @param array $owner The owner
3908 * @param array $contact Target of the communication
3910 * @return int The result of the transmission
3912 public static function sendMail($item, $owner, $contact)
3914 $myaddr = self::myHandle($owner);
3917 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3918 intval($item["convid"]),
3919 intval($item["uid"])
3922 if (!DBM::is_result($r)) {
3923 logger("conversation not found.");
3929 "author" => $cnv["creator"],
3930 "guid" => $cnv["guid"],
3931 "subject" => $cnv["subject"],
3932 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3933 "participants" => $cnv["recips"]
3936 $body = bb2diaspora($item["body"]);
3937 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3940 "author" => $myaddr,
3941 "guid" => $item["guid"],
3942 "conversation_guid" => $cnv["guid"],
3944 "created_at" => $created,
3947 if ($item["reply"]) {
3952 "author" => $cnv["creator"],
3953 "guid" => $cnv["guid"],
3954 "subject" => $cnv["subject"],
3955 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3956 "participants" => $cnv["recips"],
3959 $type = "conversation";
3962 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3966 * @brief Create profile data
3968 * @param int $uid The user id
3970 * @return array The profile data
3972 private static function createProfileData($uid)
3975 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3977 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3978 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3979 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3989 $handle = $profile["addr"];
3990 $first = ((strpos($profile['name'], ' ')
3991 ? trim(substr($profile['name'], 0, strpos($profile['name'], ' '))) : $profile['name']));
3992 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3993 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3994 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3995 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3996 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3998 if ($searchable === 'true') {
3999 $dob = '1000-00-00';
4001 if (($profile['dob']) && ($profile['dob'] > '0001-01-01')) {
4002 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC', 'UTC', $profile['dob'],'m-d');
4005 $about = $profile['about'];
4006 $about = strip_tags(bbcode($about));
4008 $location = Profile::formatLocation($profile);
4010 if ($profile['pub_keywords']) {
4011 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4012 $kw = str_replace(' ', ' ', $kw);
4013 $arr = explode(' ', $profile['pub_keywords']);
4015 for ($x = 0; $x < 5; $x ++) {
4016 if (trim($arr[$x])) {
4017 $tags .= '#'. trim($arr[$x]) .' ';
4022 $tags = trim($tags);
4025 return array("author" => $handle,
4026 "first_name" => $first,
4027 "last_name" => $last,
4028 "image_url" => $large,
4029 "image_url_medium" => $medium,
4030 "image_url_small" => $small,
4032 "gender" => $profile['gender'],
4034 "location" => $location,
4035 "searchable" => $searchable,
4037 "tag_string" => $tags);
4041 * @brief Sends profile data
4043 * @param int $uid The user id
4044 * @param bool $recips optional, default false
4047 public static function sendProfile($uid, $recips = false)
4055 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4056 AND `uid` = %d AND `rel` != %d",
4057 dbesc(NETWORK_DIASPORA),
4059 intval(CONTACT_IS_SHARING)
4067 $message = self::createProfileData($uid);
4069 foreach ($recips as $recip) {
4070 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4071 self::buildAndTransmit($profile, $recip, "profile", $message, false, "", true);
4076 * @brief Stores the signature for likes that are created on our system
4078 * @param array $contact The contact array of the "like"
4079 * @param int $post_id The post id of the "like"
4081 * @return bool Success
4083 public static function storeLikeSignature($contact, $post_id)
4085 // Is the contact the owner? Then fetch the private key
4086 if (!$contact['self'] || ($contact['uid'] == 0)) {
4087 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4091 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4092 if (!DBM::is_result($r)) {
4096 $contact["uprvkey"] = $r[0]['prvkey'];
4098 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4099 if (!DBM::is_result($r)) {
4103 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
4107 $message = self::constructLike($r[0], $contact);
4108 $message["author_signature"] = self::signature($contact, $message);
4111 * Now store the signature more flexible to dynamically support new fields.
4112 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4114 dba::insert('sign', array('iid' => $post_id, 'signed_text' => json_encode($message)));
4116 logger('Stored diaspora like signature');
4121 * @brief Stores the signature for comments that are created on our system
4123 * @param array $item The item array of the comment
4124 * @param array $contact The contact array of the item owner
4125 * @param string $uprvkey The private key of the sender
4126 * @param int $message_id The message id of the comment
4128 * @return bool Success
4130 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4132 if ($uprvkey == "") {
4133 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4137 $contact["uprvkey"] = $uprvkey;
4139 $message = self::constructComment($item, $contact);
4140 $message["author_signature"] = self::signature($contact, $message);
4143 * Now store the signature more flexible to dynamically support new fields.
4144 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4146 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($message)));
4148 logger('Stored diaspora comment signature');