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;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Core\Cache;
14 use Friendica\Core\Config;
15 use Friendica\Core\L10n;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\System;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Model\Contact;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Item;
24 use Friendica\Model\Profile;
25 use Friendica\Model\Queue;
26 use Friendica\Model\User;
27 use Friendica\Network\Probe;
28 use Friendica\Util\Crypto;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Network;
31 use Friendica\Util\XML;
32 use Friendica\Util\Map;
36 require_once 'include/dba.php';
37 require_once 'include/items.php';
38 require_once 'include/bb2diaspora.php';
41 * @brief This class contain functions to create and send Diaspora XML files
47 * @brief Return a list of relay servers
49 * This is an experimental Diaspora feature.
51 * @return array of relay servers
53 public static function relayList()
55 $serverdata = Config::get("system", "relay_server");
56 if ($serverdata == "") {
62 $servers = explode(",", $serverdata);
64 foreach ($servers as $server) {
65 $server = trim($server);
66 $addr = "relay@".str_replace("http://", "", normalise_link($server));
67 $batch = $server."/receive/public";
70 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
73 dbesc(normalise_link($server))
78 "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
79 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
80 DateTimeFormat::utcNow(),
84 dbesc(normalise_link($server)),
86 dbesc(NETWORK_DIASPORA),
87 intval(CONTACT_IS_FOLLOWER),
88 dbesc(DateTimeFormat::utcNow()),
89 dbesc(DateTimeFormat::utcNow()),
90 dbesc(DateTimeFormat::utcNow())
93 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
95 $relay[] = $relais[0];
98 $relay[] = $relais[0];
106 * @brief Return a list of participating contacts for a thread
108 * This is used for the participation feature.
109 * One of the parameters is a contact array.
110 * This is done to avoid duplicates.
112 * @param integer $thread The id of the thread
113 * @param array $contacts The previously fetched contacts
115 * @return array of relay servers
117 public static function participantsForThread($thread, $contacts)
119 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
120 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
121 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
122 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
123 WHERE `participation`.`iid` = ?", $thread);
125 while ($contact = dba::fetch($r)) {
126 if (!empty($contact['fnetwork'])) {
127 $contact['network'] = $contact['fnetwork'];
129 unset($contact['fnetwork']);
131 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
132 $contact['batch'] = $contact['fbatch'];
134 unset($contact['fbatch']);
137 foreach ($contacts as $entry) {
138 if ($entry['batch'] == $contact['batch']) {
144 $contacts[] = $contact;
153 * @brief repairs a signature that was double encoded
155 * The function is unused at the moment. It was copied from the old implementation.
157 * @param string $signature The signature
158 * @param string $handle The handle of the signature owner
159 * @param integer $level This value is only set inside this function to avoid endless loops
161 * @return string the repaired signature
163 private static function repairSignature($signature, $handle = "", $level = 1)
165 if ($signature == "") {
169 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
170 $signature = base64_decode($signature);
171 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
173 // Do a recursive call to be able to fix even multiple levels
175 $signature = self::repairSignature($signature, $handle, ++$level);
183 * @brief verify the envelope and return the verified data
185 * @param string $envelope The magic envelope
187 * @return string verified data
189 private static function verifyMagicEnvelope($envelope)
191 $basedom = XML::parseString($envelope);
193 if (!is_object($basedom)) {
194 logger("Envelope is no XML file");
198 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
200 if (sizeof($children) == 0) {
201 logger("XML has no children");
207 $data = base64url_decode($children->data);
208 $type = $children->data->attributes()->type[0];
210 $encoding = $children->encoding;
212 $alg = $children->alg;
214 $sig = base64url_decode($children->sig);
215 $key_id = $children->sig->attributes()->key_id[0];
217 $handle = base64url_decode($key_id);
220 $b64url_data = base64url_encode($data);
221 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
223 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
226 logger('No author could be decoded. Discarding. Message: ' . $envelope);
230 $key = self::key($handle);
232 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
236 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
238 logger('Message from ' . $handle . ' did not verify. Discarding.');
246 * @brief encrypts data via AES
248 * @param string $key The AES key
249 * @param string $iv The IV (is used for CBC encoding)
250 * @param string $data The data that is to be encrypted
252 * @return string encrypted data
254 private static function aesEncrypt($key, $iv, $data)
256 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
260 * @brief decrypts data via AES
262 * @param string $key The AES key
263 * @param string $iv The IV (is used for CBC encoding)
264 * @param string $encrypted The encrypted data
266 * @return string decrypted data
268 private static function aesDecrypt($key, $iv, $encrypted)
270 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
274 * @brief: Decodes incoming Diaspora message in the new format
276 * @param array $importer Array of the importer user
277 * @param string $raw raw post message
280 * 'message' -> decoded Diaspora XML message
281 * 'author' -> author diaspora handle
282 * 'key' -> author public key (converted to pkcs#8)
284 public static function decodeRaw($importer, $raw)
286 $data = json_decode($raw);
288 // Is it a private post? Then decrypt the outer Salmon
289 if (is_object($data)) {
290 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
291 $ciphertext = base64_decode($data->encrypted_magic_envelope);
293 $outer_key_bundle = '';
294 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
295 $j_outer_key_bundle = json_decode($outer_key_bundle);
297 if (!is_object($j_outer_key_bundle)) {
298 logger('Outer Salmon did not verify. Discarding.');
299 System::httpExit(400);
302 $outer_iv = base64_decode($j_outer_key_bundle->iv);
303 $outer_key = base64_decode($j_outer_key_bundle->key);
305 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
310 $basedom = XML::parseString($xml);
312 if (!is_object($basedom)) {
313 logger('Received data does not seem to be an XML. Discarding. '.$xml);
314 System::httpExit(400);
317 $base = $basedom->children(NAMESPACE_SALMON_ME);
319 // Not sure if this cleaning is needed
320 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
322 // Build the signed data
323 $type = $base->data[0]->attributes()->type[0];
324 $encoding = $base->encoding;
326 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
328 // This is the signature
329 $signature = base64url_decode($base->sig);
331 // Get the senders' public key
332 $key_id = $base->sig[0]->attributes()->key_id[0];
333 $author_addr = base64_decode($key_id);
334 if ($author_addr == '') {
335 logger('No author could be decoded. Discarding. Message: ' . $xml);
336 System::httpExit(400);
339 $key = self::key($author_addr);
341 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
342 System::httpExit(400);
345 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
347 logger('Message did not verify. Discarding.');
348 System::httpExit(400);
351 return ['message' => (string)base64url_decode($base->data),
352 'author' => unxmlify($author_addr),
353 'key' => (string)$key];
357 * @brief: Decodes incoming Diaspora message in the deprecated format
359 * @param array $importer Array of the importer user
360 * @param string $xml urldecoded Diaspora salmon
363 * 'message' -> decoded Diaspora XML message
364 * 'author' -> author diaspora handle
365 * 'key' -> author public key (converted to pkcs#8)
367 public static function decode($importer, $xml)
370 $basedom = XML::parseString($xml);
372 if (!is_object($basedom)) {
373 logger("XML is not parseable.");
376 $children = $basedom->children('https://joindiaspora.com/protocol');
378 $inner_aes_key = null;
381 if ($children->header) {
383 $author_link = str_replace('acct:', '', $children->header->author_id);
385 // This happens with posts from a relais
387 logger("This is no private post in the old format", LOGGER_DEBUG);
391 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
393 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
394 $ciphertext = base64_decode($encrypted_header->ciphertext);
396 $outer_key_bundle = '';
397 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
399 $j_outer_key_bundle = json_decode($outer_key_bundle);
401 $outer_iv = base64_decode($j_outer_key_bundle->iv);
402 $outer_key = base64_decode($j_outer_key_bundle->key);
404 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
406 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
407 $idom = XML::parseString($decrypted);
409 $inner_iv = base64_decode($idom->iv);
410 $inner_aes_key = base64_decode($idom->aes_key);
412 $author_link = str_replace('acct:', '', $idom->author_id);
415 $dom = $basedom->children(NAMESPACE_SALMON_ME);
417 // figure out where in the DOM tree our data is hiding
420 if ($dom->provenance->data) {
421 $base = $dom->provenance;
422 } elseif ($dom->env->data) {
424 } elseif ($dom->data) {
429 logger('unable to locate salmon data in xml');
430 System::httpExit(400);
434 // Stash the signature away for now. We have to find their key or it won't be good for anything.
435 $signature = base64url_decode($base->sig);
439 // strip whitespace so our data element will return to one big base64 blob
440 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
443 // stash away some other stuff for later
445 $type = $base->data[0]->attributes()->type[0];
446 $keyhash = $base->sig[0]->attributes()->keyhash[0];
447 $encoding = $base->encoding;
451 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
455 $data = base64url_decode($data);
459 $inner_decrypted = $data;
461 // Decode the encrypted blob
462 $inner_encrypted = base64_decode($data);
463 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
467 logger('Could not retrieve author URI.');
468 System::httpExit(400);
470 // Once we have the author URI, go to the web and try to find their public key
471 // (first this will look it up locally if it is in the fcontact cache)
472 // This will also convert diaspora public key from pkcs#1 to pkcs#8
474 logger('Fetching key for '.$author_link);
475 $key = self::key($author_link);
478 logger('Could not retrieve author key.');
479 System::httpExit(400);
482 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
485 logger('Message did not verify. Discarding.');
486 System::httpExit(400);
489 logger('Message verified.');
491 return ['message' => (string)$inner_decrypted,
492 'author' => unxmlify($author_link),
493 'key' => (string)$key];
498 * @brief Dispatches public messages and find the fitting receivers
500 * @param array $msg The post that will be dispatched
502 * @return int The message id of the generated message, "true" or "false" if there was an error
504 public static function dispatchPublic($msg)
506 $enabled = intval(Config::get("system", "diaspora_enabled"));
508 logger("diaspora is disabled");
512 if (!($postdata = self::validPosting($msg))) {
513 logger("Invalid posting");
517 $fields = $postdata['fields'];
519 // Is it a an action (comment, like, ...) for our own post?
520 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
521 $guid = notags(unxmlify($fields->parent_guid));
522 $importer = self::importerForGuid($guid);
523 if (is_array($importer)) {
524 logger("delivering to origin: ".$importer["name"]);
525 $message_id = self::dispatch($importer, $msg, $fields);
530 // Process item retractions. This has to be done separated from the other stuff,
531 // since retractions for comments could come even from non followers.
532 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
533 $target = notags(unxmlify($fields->target_type));
534 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
535 logger('processing retraction for '.$target, LOGGER_DEBUG);
536 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
537 $message_id = self::dispatch($importer, $msg, $fields);
542 // Now distribute it to the followers
544 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
545 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
546 AND NOT `account_expired` AND NOT `account_removed`",
547 dbesc(NETWORK_DIASPORA),
548 dbesc($msg["author"])
551 if (DBM::is_result($r)) {
552 foreach ($r as $rr) {
553 logger("delivering to: ".$rr["username"]);
554 self::dispatch($rr, $msg, $fields);
556 } elseif (!Config::get('system', 'relay_subscribe', false)) {
557 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
559 // Use a dummy importer to import the data for the public copy
560 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
561 $message_id = self::dispatch($importer, $msg, $fields);
568 * @brief Dispatches the different message types to the different functions
570 * @param array $importer Array of the importer user
571 * @param array $msg The post that will be dispatched
572 * @param object $fields SimpleXML object that contains the message
574 * @return int The message id of the generated message, "true" or "false" if there was an error
576 public static function dispatch($importer, $msg, $fields = null)
578 // The sender is the handle of the contact that sent the message.
579 // This will often be different with relayed messages (for example "like" and "comment")
580 $sender = $msg["author"];
582 // This is only needed for private postings since this is already done for public ones before
583 if (is_null($fields)) {
584 if (!($postdata = self::validPosting($msg))) {
585 logger("Invalid posting");
588 $fields = $postdata['fields'];
591 $type = $fields->getName();
593 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
596 case "account_migration":
597 return self::receiveAccountMigration($importer, $fields);
599 case "account_deletion":
600 return self::receiveAccountDeletion($importer, $fields);
603 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
606 return self::receiveContactRequest($importer, $fields);
609 return self::receiveConversation($importer, $msg, $fields);
612 return self::receiveLike($importer, $sender, $fields);
615 return self::receiveMessage($importer, $fields);
617 case "participation":
618 return self::receiveParticipation($importer, $fields);
620 case "photo": // Not implemented
621 return self::receivePhoto($importer, $fields);
623 case "poll_participation": // Not implemented
624 return self::receivePollParticipation($importer, $fields);
627 return self::receiveProfile($importer, $fields);
630 return self::receiveReshare($importer, $fields, $msg["message"]);
633 return self::receiveRetraction($importer, $sender, $fields);
635 case "status_message":
636 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
639 logger("Unknown message type ".$type);
647 * @brief Checks if a posting is valid and fetches the data fields.
649 * This function does not only check the signature.
650 * It also does the conversion between the old and the new diaspora format.
652 * @param array $msg Array with the XML, the sender handle and the sender signature
654 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
656 private static function validPosting($msg)
658 $data = XML::parseString($msg["message"]);
660 if (!is_object($data)) {
661 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
665 // Is this the new or the old version?
666 if ($data->getName() == "XML") {
668 foreach ($data->post->children() as $child) {
676 $type = $element->getName();
679 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
681 // All retractions are handled identically from now on.
682 // In the new version there will only be "retraction".
683 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
684 $type = "retraction";
686 if ($type == "request") {
690 $fields = new SimpleXMLElement("<".$type."/>");
693 $author_signature = null;
694 $parent_author_signature = null;
696 foreach ($element->children() as $fieldname => $entry) {
698 // Translation for the old XML structure
699 if ($fieldname == "diaspora_handle") {
700 $fieldname = "author";
702 if ($fieldname == "participant_handles") {
703 $fieldname = "participants";
705 if (in_array($type, ["like", "participation"])) {
706 if ($fieldname == "target_type") {
707 $fieldname = "parent_type";
710 if ($fieldname == "sender_handle") {
711 $fieldname = "author";
713 if ($fieldname == "recipient_handle") {
714 $fieldname = "recipient";
716 if ($fieldname == "root_diaspora_id") {
717 $fieldname = "root_author";
719 if ($type == "status_message") {
720 if ($fieldname == "raw_message") {
724 if ($type == "retraction") {
725 if ($fieldname == "post_guid") {
726 $fieldname = "target_guid";
728 if ($fieldname == "type") {
729 $fieldname = "target_type";
734 if (($fieldname == "author_signature") && ($entry != "")) {
735 $author_signature = base64_decode($entry);
736 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
737 $parent_author_signature = base64_decode($entry);
738 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
739 if ($signed_data != "") {
743 $signed_data .= $entry;
745 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
746 || ($orig_type == "relayable_retraction")
748 XML::copy($entry, $fields, $fieldname);
752 // This is something that shouldn't happen at all.
753 if (in_array($type, ["status_message", "reshare", "profile"])) {
754 if ($msg["author"] != $fields->author) {
755 logger("Message handle is not the same as envelope sender. Quitting this message.");
760 // Only some message types have signatures. So we quit here for the other types.
761 if (!in_array($type, ["comment", "like"])) {
762 return ["fields" => $fields, "relayed" => false];
764 // No author_signature? This is a must, so we quit.
765 if (!isset($author_signature)) {
766 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
770 if (isset($parent_author_signature)) {
773 $key = self::key($msg["author"]);
775 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
776 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);
783 $key = self::key($fields->author);
785 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
786 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
789 return ["fields" => $fields, "relayed" => $relayed];
794 * @brief Fetches the public key for a given handle
796 * @param string $handle The handle
798 * @return string The public key
800 private static function key($handle)
802 $handle = strval($handle);
804 logger("Fetching diaspora key for: ".$handle);
806 $r = self::personByHandle($handle);
815 * @brief Fetches data for a given handle
817 * @param string $handle The handle
819 * @return array the queried data
821 public static function personByHandle($handle)
825 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
826 if (DBM::is_result($person)) {
827 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
829 // update record occasionally so it doesn't get stale
830 $d = strtotime($person["updated"]." +00:00");
831 if ($d < strtotime("now - 14 days")) {
835 if ($person["guid"] == "") {
840 if (!DBM::is_result($person) || $update) {
841 logger("create or refresh", LOGGER_DEBUG);
842 $r = Probe::uri($handle, NETWORK_DIASPORA);
844 // Note that Friendica contacts will return a "Diaspora person"
845 // if Diaspora connectivity is enabled on their server
846 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
847 self::addFContact($r, $update);
849 // Fetch the updated or added contact
850 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
851 if (!DBM::is_result($person)) {
861 * @brief Updates the fcontact table
863 * @param array $arr The fcontact data
864 * @param bool $update Update or insert?
866 * @return string The id of the fcontact entry
868 private static function addFContact($arr, $update = false)
872 "UPDATE `fcontact` SET
886 WHERE `url` = '%s' AND `network` = '%s'",
888 dbesc($arr["photo"]),
889 dbesc($arr["request"]),
891 dbesc(strtolower($arr["addr"])),
893 dbesc($arr["batch"]),
894 dbesc($arr["notify"]),
896 dbesc($arr["confirm"]),
897 dbesc($arr["alias"]),
898 dbesc($arr["pubkey"]),
899 dbesc(DateTimeFormat::utcNow()),
901 dbesc($arr["network"])
905 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
906 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
907 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
910 dbesc($arr["photo"]),
911 dbesc($arr["request"]),
915 dbesc($arr["batch"]),
916 dbesc($arr["notify"]),
918 dbesc($arr["confirm"]),
919 dbesc($arr["network"]),
920 dbesc($arr["alias"]),
921 dbesc($arr["pubkey"]),
922 dbesc(DateTimeFormat::utcNow())
930 * @brief get a handle (user@domain.tld) from a given contact id
932 * @param int $contact_id The id in the contact table
933 * @param int $pcontact_id The id in the contact table (Used for the public contact)
935 * @return string the handle
937 private static function handleFromContact($contact_id, $pcontact_id = 0)
941 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
943 if ($pcontact_id != 0) {
945 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
949 if (DBM::is_result($r)) {
950 return strtolower($r[0]["addr"]);
955 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
959 if (DBM::is_result($r)) {
962 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
964 if ($contact['addr'] != "") {
965 $handle = $contact['addr'];
967 $baseurl_start = strpos($contact['url'], '://') + 3;
968 // allows installations in a subdirectory--not sure how Diaspora will handle
969 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
970 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
971 $handle = $contact['nick'].'@'.$baseurl;
975 return strtolower($handle);
979 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
982 * @param mixed $fcontact_guid Hexadecimal string guid
984 * @return string the contact url or null
986 public static function urlFromContactGuid($fcontact_guid)
988 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
991 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
992 dbesc(NETWORK_DIASPORA),
993 dbesc($fcontact_guid)
996 if (DBM::is_result($r)) {
1004 * @brief Get a contact id for a given handle
1006 * @todo Move to Friendica\Model\Contact
1008 * @param int $uid The user id
1009 * @param string $handle The handle in the format user@domain.tld
1011 * @return int Contact id
1013 private static function contactByHandle($uid, $handle)
1015 // First do a direct search on the contact table
1017 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1022 if (DBM::is_result($r)) {
1026 * We haven't found it?
1027 * We use another function for it that will possibly create a contact entry.
1029 $cid = Contact::getIdForURL($handle, $uid);
1032 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1033 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1035 if (DBM::is_result($r)) {
1041 $handle_parts = explode("@", $handle);
1042 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1044 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1045 dbesc(NETWORK_DFRN),
1049 if (DBM::is_result($r)) {
1053 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1058 * @brief Check if posting is allowed for this contact
1060 * @param array $importer Array of the importer user
1061 * @param array $contact The contact that is checked
1062 * @param bool $is_comment Is the check for a comment?
1064 * @return bool is the contact allowed to post?
1066 private static function postAllow($importer, $contact, $is_comment = false)
1069 * Perhaps we were already sharing with this person. Now they're sharing with us.
1070 * That makes us friends.
1071 * Normally this should have handled by getting a request - but this could get lost
1073 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1074 // It is not removed by now. Possibly the code is needed?
1075 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1078 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1079 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1082 // $contact["rel"] = CONTACT_IS_FRIEND;
1083 // logger("defining user ".$contact["nick"]." as friend");
1086 // We don't seem to like that person
1087 if ($contact["blocked"] || $contact["readonly"]) {
1088 // Maybe blocked, don't accept.
1090 // We are following this person?
1091 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1092 // Yes, then it is fine.
1094 // Is it a post to a community?
1095 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1098 // Is the message a global user or a comment?
1099 } elseif (($importer["uid"] == 0) || $is_comment) {
1100 // Messages for the global users and comments are always accepted
1108 * @brief Fetches the contact id for a handle and checks if posting is allowed
1110 * @param array $importer Array of the importer user
1111 * @param string $handle The checked handle in the format user@domain.tld
1112 * @param bool $is_comment Is the check for a comment?
1114 * @return array The contact data
1116 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1118 $contact = self::contactByHandle($importer["uid"], $handle);
1120 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1121 // If a contact isn't found, we accept it anyway if it is a comment
1129 if (!self::postAllow($importer, $contact, $is_comment)) {
1130 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1137 * @brief Does the message already exists on the system?
1139 * @param int $uid The user id
1140 * @param string $guid The guid of the message
1142 * @return int|bool message id if the message already was stored into the system - or false.
1144 private static function messageExists($uid, $guid)
1147 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1152 if (DBM::is_result($r)) {
1153 logger("message ".$guid." already exists for user ".$uid);
1161 * @brief Checks for links to posts in a message
1163 * @param array $item The item array
1166 private static function fetchGuid($item)
1168 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1169 preg_replace_callback(
1171 function ($match) use ($item) {
1172 self::fetchGuidSub($match, $item);
1177 preg_replace_callback(
1178 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1179 function ($match) use ($item) {
1180 self::fetchGuidSub($match, $item);
1187 * @brief Checks for relative /people/* links in an item body to match local
1188 * contacts or prepends the remote host taken from the author link.
1190 * @param string $body The item body to replace links from
1191 * @param string $author_link The author link for missing local contact fallback
1193 * @return string the replaced string
1195 public static function replacePeopleGuid($body, $author_link)
1197 $return = preg_replace_callback(
1198 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1199 function ($match) use ($author_link) {
1201 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1202 // 1 => '0123456789abcdef'
1204 $handle = self::urlFromContactGuid($match[1]);
1207 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1209 // No local match, restoring absolute remote URL from author scheme and host
1210 $author_url = parse_url($author_link);
1211 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1223 * @brief sub function of "fetchGuid" which checks for links in messages
1225 * @param array $match array containing a link that has to be checked for a message link
1226 * @param array $item The item array
1229 private static function fetchGuidSub($match, $item)
1231 if (!self::storeByGuid($match[1], $item["author-link"])) {
1232 self::storeByGuid($match[1], $item["owner-link"]);
1237 * @brief Fetches an item with a given guid from a given server
1239 * @param string $guid the message guid
1240 * @param string $server The server address
1241 * @param int $uid The user id of the user
1243 * @return int the message id of the stored message or false
1245 private static function storeByGuid($guid, $server, $uid = 0)
1247 $serverparts = parse_url($server);
1248 $server = $serverparts["scheme"]."://".$serverparts["host"];
1250 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1252 $msg = self::message($guid, $server);
1258 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1260 // Now call the dispatcher
1261 return self::dispatchPublic($msg);
1265 * @brief Fetches a message from a server
1267 * @param string $guid message guid
1268 * @param string $server The url of the server
1269 * @param int $level Endless loop prevention
1272 * 'message' => The message XML
1273 * 'author' => The author handle
1274 * 'key' => The public key of the author
1276 private static function message($guid, $server, $level = 0)
1282 // This will work for new Diaspora servers and Friendica servers from 3.5
1283 $source_url = $server."/fetch/post/".urlencode($guid);
1285 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1287 $envelope = Network::fetchUrl($source_url);
1289 logger("Envelope was fetched.", LOGGER_DEBUG);
1290 $x = self::verifyMagicEnvelope($envelope);
1292 logger("Envelope could not be verified.", LOGGER_DEBUG);
1294 logger("Envelope was verified.", LOGGER_DEBUG);
1300 // This will work for older Diaspora and Friendica servers
1302 $source_url = $server."/p/".urlencode($guid).".xml";
1303 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1305 $x = Network::fetchUrl($source_url);
1311 $source_xml = XML::parseString($x);
1313 if (!is_object($source_xml)) {
1317 if ($source_xml->post->reshare) {
1318 // Reshare of a reshare - old Diaspora version
1319 logger("Message is a reshare", LOGGER_DEBUG);
1320 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1321 } elseif ($source_xml->getName() == "reshare") {
1322 // Reshare of a reshare - new Diaspora version
1323 logger("Message is a new reshare", LOGGER_DEBUG);
1324 return self::message($source_xml->root_guid, $server, ++$level);
1329 // Fetch the author - for the old and the new Diaspora version
1330 if ($source_xml->post->status_message->diaspora_handle) {
1331 $author = (string)$source_xml->post->status_message->diaspora_handle;
1332 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1333 $author = (string)$source_xml->author;
1336 // If this isn't a "status_message" then quit
1338 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1342 $msg = ["message" => $x, "author" => $author];
1344 $msg["key"] = self::key($msg["author"]);
1350 * @brief Fetches the item record of a given guid
1352 * @param int $uid The user id
1353 * @param string $guid message guid
1354 * @param string $author The handle of the item
1355 * @param array $contact The contact of the item owner
1357 * @return array the item record
1359 private static function parentItem($uid, $guid, $author, $contact)
1362 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1363 `author-name`, `author-link`, `author-avatar`,
1364 `owner-name`, `owner-link`, `owner-avatar`
1365 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1371 $result = self::storeByGuid($guid, $contact["url"], $uid);
1374 $person = self::personByHandle($author);
1375 $result = self::storeByGuid($guid, $person["url"], $uid);
1379 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1382 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1383 `author-name`, `author-link`, `author-avatar`,
1384 `owner-name`, `owner-link`, `owner-avatar`
1385 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1393 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1396 logger("parent item found: parent: ".$guid." - user: ".$uid);
1402 * @brief returns contact details
1404 * @param array $def_contact The default contact if the person isn't found
1405 * @param array $person The record of the person
1406 * @param int $uid The user id
1409 * 'cid' => contact id
1410 * 'network' => network type
1412 private static function authorContactByUrl($def_contact, $person, $uid)
1414 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1415 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1416 if (DBM::is_result($contact)) {
1417 $cid = $contact["id"];
1418 $network = $contact["network"];
1420 $cid = $def_contact["id"];
1421 $network = NETWORK_DIASPORA;
1424 return ["cid" => $cid, "network" => $network];
1428 * @brief Is the profile a hubzilla profile?
1430 * @param string $url The profile link
1432 * @return bool is it a hubzilla server?
1434 public static function isRedmatrix($url)
1436 return(strstr($url, "/channel/"));
1440 * @brief Generate a post link with a given handle and message guid
1442 * @param string $addr The user handle
1443 * @param string $guid message guid
1444 * @param string $parent_guid optional parent guid
1446 * @return string the post link
1448 private static function plink($addr, $guid, $parent_guid = '')
1450 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1453 if (!DBM::is_result($r)) {
1454 if ($parent_guid != '') {
1455 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1457 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1461 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1462 // So we try another way as well.
1463 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1464 if (DBM::is_result($s)) {
1465 $r[0]["network"] = $s[0]["network"];
1468 if ($r[0]["network"] == NETWORK_DFRN) {
1469 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1472 if (self::isRedmatrix($r[0]["url"])) {
1473 return $r[0]["url"]."/?f=&mid=".$guid;
1476 if ($parent_guid != '') {
1477 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1479 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1484 * @brief Receives account migration
1486 * @param array $importer Array of the importer user
1487 * @param object $data The message object
1489 * @return bool Success
1491 private static function receiveAccountMigration($importer, $data)
1493 $old_handle = notags(unxmlify($data->author));
1494 $new_handle = notags(unxmlify($data->profile->author));
1495 $signature = notags(unxmlify($data->signature));
1497 $contact = self::contactByHandle($importer["uid"], $old_handle);
1499 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1503 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1506 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1507 $key = self::key($old_handle);
1508 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1509 logger('No valid signature for migration.');
1513 // Update the profile
1514 self::receiveProfile($importer, $data->profile);
1516 // change the technical stuff in contact and gcontact
1517 $data = Probe::uri($new_handle);
1518 if ($data['network'] == NETWORK_PHANTOM) {
1519 logger('Account for '.$new_handle." couldn't be probed.");
1523 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1524 'name' => $data['name'], 'nick' => $data['nick'],
1525 'addr' => $data['addr'], 'batch' => $data['batch'],
1526 'notify' => $data['notify'], 'poll' => $data['poll'],
1527 'network' => $data['network']];
1529 dba::update('contact', $fields, ['addr' => $old_handle]);
1531 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1532 'name' => $data['name'], 'nick' => $data['nick'],
1533 'addr' => $data['addr'], 'connect' => $data['addr'],
1534 'notify' => $data['notify'], 'photo' => $data['photo'],
1535 'server_url' => $data['baseurl'], 'network' => $data['network']];
1537 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1539 logger('Contacts are updated.');
1542 /// @todo This is an extreme performance killer
1544 'owner-link' => [$contact["url"], $data["url"]],
1545 'author-link' => [$contact["url"], $data["url"]],
1547 foreach ($fields as $n => $f) {
1549 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1552 intval($importer["uid"])
1555 if (DBM::is_result($r)) {
1557 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1562 intval($importer["uid"])
1571 logger('Items are updated.');
1577 * @brief Processes an account deletion
1579 * @param array $importer Array of the importer user
1580 * @param object $data The message object
1582 * @return bool Success
1584 private static function receiveAccountDeletion($importer, $data)
1586 /// @todo Account deletion should remove the contact from the global contacts as well
1588 $author = notags(unxmlify($data->author));
1590 $contact = self::contactByHandle($importer["uid"], $author);
1592 logger("cannot find contact for author: ".$author);
1596 // We now remove the contact
1597 Contact::remove($contact["id"]);
1602 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1604 * @param string $author Author handle
1605 * @param string $guid Message guid
1606 * @param boolean $onlyfound Only return uri when found in the database
1608 * @return string The constructed uri or the one from our database
1610 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1612 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1613 if (DBM::is_result($r)) {
1614 return $r[0]["uri"];
1615 } elseif (!$onlyfound) {
1616 return $author.":".$guid;
1623 * @brief Fetch the guid from our database with a given uri
1625 * @param string $uri Message uri
1626 * @param string $uid Author handle
1628 * @return string The post guid
1630 private static function getGuidFromUri($uri, $uid)
1632 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1633 if (DBM::is_result($r)) {
1634 return $r[0]["guid"];
1641 * @brief Find the best importer for a comment, like, ...
1643 * @param string $guid The guid of the item
1645 * @return array|boolean the origin owner of that post - or false
1647 private static function importerForGuid($guid)
1649 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1651 if (DBM::is_result($item)) {
1652 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1653 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1654 if (DBM::is_result($contact)) {
1662 * @brief Processes an incoming comment
1664 * @param array $importer Array of the importer user
1665 * @param string $sender The sender of the message
1666 * @param object $data The message object
1667 * @param string $xml The original XML of the message
1669 * @return int The message id of the generated comment or "false" if there was an error
1671 private static function receiveComment($importer, $sender, $data, $xml)
1673 $author = notags(unxmlify($data->author));
1674 $guid = notags(unxmlify($data->guid));
1675 $parent_guid = notags(unxmlify($data->parent_guid));
1676 $text = unxmlify($data->text);
1678 if (isset($data->created_at)) {
1679 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1681 $created_at = DateTimeFormat::utcNow();
1684 if (isset($data->thread_parent_guid)) {
1685 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1686 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1691 $contact = self::allowedContactByHandle($importer, $sender, true);
1696 $message_id = self::messageExists($importer["uid"], $guid);
1701 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1702 if (!$parent_item) {
1706 $person = self::personByHandle($author);
1707 if (!is_array($person)) {
1708 logger("unable to find author details");
1712 // Fetch the contact id - if we know this contact
1713 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1717 $datarray["uid"] = $importer["uid"];
1718 $datarray["contact-id"] = $author_contact["cid"];
1719 $datarray["network"] = $author_contact["network"];
1721 $datarray["author-name"] = $person["name"];
1722 $datarray["author-link"] = $person["url"];
1723 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1725 $datarray["owner-name"] = $contact["name"];
1726 $datarray["owner-link"] = $contact["url"];
1727 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1729 $datarray["guid"] = $guid;
1730 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1732 $datarray["type"] = "remote-comment";
1733 $datarray["verb"] = ACTIVITY_POST;
1734 $datarray["gravity"] = GRAVITY_COMMENT;
1736 if ($thr_uri != "") {
1737 $datarray["parent-uri"] = $thr_uri;
1739 $datarray["parent-uri"] = $parent_item["uri"];
1742 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1744 $datarray["protocol"] = PROTOCOL_DIASPORA;
1745 $datarray["source"] = $xml;
1747 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1749 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1751 $body = diaspora2bb($text);
1753 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1755 self::fetchGuid($datarray);
1757 $message_id = Item::insert($datarray);
1759 if ($message_id <= 0) {
1764 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1767 // If we are the origin of the parent we store the original data and notify our followers
1768 if ($message_id && $parent_item["origin"]) {
1769 // Formerly we stored the signed text, the signature and the author in different fields.
1770 // We now store the raw data so that we are more flexible.
1771 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1774 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1781 * @brief processes and stores private messages
1783 * @param array $importer Array of the importer user
1784 * @param array $contact The contact of the message
1785 * @param object $data The message object
1786 * @param array $msg Array of the processed message, author handle and key
1787 * @param object $mesg The private message
1788 * @param array $conversation The conversation record to which this message belongs
1790 * @return bool "true" if it was successful
1792 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1794 $author = notags(unxmlify($data->author));
1795 $guid = notags(unxmlify($data->guid));
1796 $subject = notags(unxmlify($data->subject));
1798 // "diaspora_handle" is the element name from the old version
1799 // "author" is the element name from the new version
1800 if ($mesg->author) {
1801 $msg_author = notags(unxmlify($mesg->author));
1802 } elseif ($mesg->diaspora_handle) {
1803 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1808 $msg_guid = notags(unxmlify($mesg->guid));
1809 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1810 $msg_text = unxmlify($mesg->text);
1811 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1813 if ($msg_conversation_guid != $guid) {
1814 logger("message conversation guid does not belong to the current conversation.");
1818 $body = diaspora2bb($msg_text);
1819 $message_uri = $msg_author.":".$msg_guid;
1821 $person = self::personByHandle($msg_author);
1826 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1828 intval($importer["uid"])
1830 if (DBM::is_result($r)) {
1831 logger("duplicate message already delivered.", LOGGER_DEBUG);
1836 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1837 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1838 intval($importer["uid"]),
1840 intval($conversation["id"]),
1841 dbesc($person["name"]),
1842 dbesc($person["photo"]),
1843 dbesc($person["url"]),
1844 intval($contact["id"]),
1849 dbesc($message_uri),
1850 dbesc($author.":".$guid),
1851 dbesc($msg_created_at)
1856 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1860 "type" => NOTIFY_MAIL,
1861 "notify_flags" => $importer["notify-flags"],
1862 "language" => $importer["language"],
1863 "to_name" => $importer["username"],
1864 "to_email" => $importer["email"],
1865 "uid" =>$importer["uid"],
1866 "item" => ["subject" => $subject, "body" => $body],
1867 "source_name" => $person["name"],
1868 "source_link" => $person["url"],
1869 "source_photo" => $person["thumb"],
1870 "verb" => ACTIVITY_POST,
1877 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1879 * @param array $importer Array of the importer user
1880 * @param array $msg Array of the processed message, author handle and key
1881 * @param object $data The message object
1883 * @return bool Success
1885 private static function receiveConversation($importer, $msg, $data)
1887 $author = notags(unxmlify($data->author));
1888 $guid = notags(unxmlify($data->guid));
1889 $subject = notags(unxmlify($data->subject));
1890 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1891 $participants = notags(unxmlify($data->participants));
1893 $messages = $data->message;
1895 if (!count($messages)) {
1896 logger("empty conversation");
1900 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1905 $conversation = null;
1908 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1909 intval($importer["uid"]),
1913 $conversation = $c[0];
1916 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1917 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1918 intval($importer["uid"]),
1922 dbesc(DateTimeFormat::utcNow()),
1924 dbesc($participants)
1928 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1929 intval($importer["uid"]),
1935 $conversation = $c[0];
1938 if (!$conversation) {
1939 logger("unable to create conversation.");
1943 foreach ($messages as $mesg) {
1944 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1951 * @brief Creates the body for a "like" message
1953 * @param array $contact The contact that send us the "like"
1954 * @param array $parent_item The item array of the parent item
1955 * @param string $guid message guid
1957 * @return string the body
1959 private static function constructLikeBody($contact, $parent_item, $guid)
1961 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1963 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1964 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1965 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
1967 return sprintf($bodyverb, $ulink, $alink, $plink);
1971 * @brief Creates a XML object for a "like"
1973 * @param array $importer Array of the importer user
1974 * @param array $parent_item The item array of the parent item
1976 * @return string The XML
1978 private static function constructLikeObject($importer, $parent_item)
1980 $objtype = ACTIVITY_OBJ_NOTE;
1981 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1982 $parent_body = $parent_item["body"];
1984 $xmldata = ["object" => ["type" => $objtype,
1986 "id" => $parent_item["uri"],
1989 "content" => $parent_body]];
1991 return XML::fromArray($xmldata, $xml, true);
1995 * @brief Processes "like" messages
1997 * @param array $importer Array of the importer user
1998 * @param string $sender The sender of the message
1999 * @param object $data The message object
2001 * @return int The message id of the generated like or "false" if there was an error
2003 private static function receiveLike($importer, $sender, $data)
2005 $author = notags(unxmlify($data->author));
2006 $guid = notags(unxmlify($data->guid));
2007 $parent_guid = notags(unxmlify($data->parent_guid));
2008 $parent_type = notags(unxmlify($data->parent_type));
2009 $positive = notags(unxmlify($data->positive));
2011 // likes on comments aren't supported by Diaspora - only on posts
2012 // But maybe this will be supported in the future, so we will accept it.
2013 if (!in_array($parent_type, ["Post", "Comment"])) {
2017 $contact = self::allowedContactByHandle($importer, $sender, true);
2022 $message_id = self::messageExists($importer["uid"], $guid);
2027 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2028 if (!$parent_item) {
2032 $person = self::personByHandle($author);
2033 if (!is_array($person)) {
2034 logger("unable to find author details");
2038 // Fetch the contact id - if we know this contact
2039 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2041 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2042 // We would accept this anyhow.
2043 if ($positive == "true") {
2044 $verb = ACTIVITY_LIKE;
2046 $verb = ACTIVITY_DISLIKE;
2051 $datarray["protocol"] = PROTOCOL_DIASPORA;
2053 $datarray["uid"] = $importer["uid"];
2054 $datarray["contact-id"] = $author_contact["cid"];
2055 $datarray["network"] = $author_contact["network"];
2057 $datarray["author-name"] = $person["name"];
2058 $datarray["author-link"] = $person["url"];
2059 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2061 $datarray["owner-name"] = $contact["name"];
2062 $datarray["owner-link"] = $contact["url"];
2063 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2065 $datarray["guid"] = $guid;
2066 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2068 $datarray["type"] = "activity";
2069 $datarray["verb"] = $verb;
2070 $datarray["gravity"] = GRAVITY_LIKE;
2071 $datarray["parent-uri"] = $parent_item["uri"];
2073 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2074 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2076 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2078 $message_id = Item::insert($datarray);
2080 if ($message_id <= 0) {
2085 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2088 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2089 if ($parent_item["id"] != $parent_item["parent"]) {
2090 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2091 $origin = $toplevel["origin"];
2093 $origin = $parent_item["origin"];
2096 // If we are the origin of the parent we store the original data and notify our followers
2097 if ($message_id && $origin) {
2098 // Formerly we stored the signed text, the signature and the author in different fields.
2099 // We now store the raw data so that we are more flexible.
2100 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2103 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2110 * @brief Processes private messages
2112 * @param array $importer Array of the importer user
2113 * @param object $data The message object
2115 * @return bool Success?
2117 private static function receiveMessage($importer, $data)
2119 $author = notags(unxmlify($data->author));
2120 $guid = notags(unxmlify($data->guid));
2121 $conversation_guid = notags(unxmlify($data->conversation_guid));
2122 $text = unxmlify($data->text);
2123 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2125 $contact = self::allowedContactByHandle($importer, $author, true);
2130 $conversation = null;
2133 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2134 intval($importer["uid"]),
2135 dbesc($conversation_guid)
2138 $conversation = $c[0];
2140 logger("conversation not available.");
2144 $message_uri = $author.":".$guid;
2146 $person = self::personByHandle($author);
2148 logger("unable to find author details");
2152 $body = diaspora2bb($text);
2154 $body = self::replacePeopleGuid($body, $person["url"]);
2159 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2161 intval($importer["uid"])
2163 if (DBM::is_result($r)) {
2164 logger("duplicate message already delivered.", LOGGER_DEBUG);
2169 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2170 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2171 intval($importer["uid"]),
2173 intval($conversation["id"]),
2174 dbesc($person["name"]),
2175 dbesc($person["photo"]),
2176 dbesc($person["url"]),
2177 intval($contact["id"]),
2178 dbesc($conversation["subject"]),
2182 dbesc($message_uri),
2183 dbesc($author.":".$conversation["guid"]),
2189 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2194 * @brief Processes participations - unsupported by now
2196 * @param array $importer Array of the importer user
2197 * @param object $data The message object
2199 * @return bool always true
2201 private static function receiveParticipation($importer, $data)
2203 $author = strtolower(notags(unxmlify($data->author)));
2204 $parent_guid = notags(unxmlify($data->parent_guid));
2206 $contact_id = Contact::getIdForURL($author);
2208 logger('Contact not found: '.$author);
2212 $person = self::personByHandle($author);
2213 if (!is_array($person)) {
2214 logger("Person not found: ".$author);
2218 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2219 if (!DBM::is_result($item)) {
2220 logger('Item not found, no origin or private: '.$parent_guid);
2224 $author_parts = explode('@', $author);
2225 if (isset($author_parts[1])) {
2226 $server = $author_parts[1];
2228 // Should never happen
2232 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2234 if (!dba::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2235 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2238 // Send all existing comments and likes to the requesting server
2239 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2241 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2242 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2243 while ($comment = dba::fetch($comments)) {
2244 if ($comment['verb'] == ACTIVITY_POST) {
2245 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2247 $cmd = $comment['self'] ? 'like' : 'comment-import';
2249 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2250 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2252 dba::close($comments);
2258 * @brief Processes photos - unneeded
2260 * @param array $importer Array of the importer user
2261 * @param object $data The message object
2263 * @return bool always true
2265 private static function receivePhoto($importer, $data)
2267 // There doesn't seem to be a reason for this function,
2268 // since the photo data is transmitted in the status message as well
2273 * @brief Processes poll participations - unssupported
2275 * @param array $importer Array of the importer user
2276 * @param object $data The message object
2278 * @return bool always true
2280 private static function receivePollParticipation($importer, $data)
2282 // We don't support polls by now
2287 * @brief Processes incoming profile updates
2289 * @param array $importer Array of the importer user
2290 * @param object $data The message object
2292 * @return bool Success
2294 private static function receiveProfile($importer, $data)
2296 $author = strtolower(notags(unxmlify($data->author)));
2298 $contact = self::contactByHandle($importer["uid"], $author);
2303 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2304 $image_url = unxmlify($data->image_url);
2305 $birthday = unxmlify($data->birthday);
2306 $gender = unxmlify($data->gender);
2307 $about = diaspora2bb(unxmlify($data->bio));
2308 $location = diaspora2bb(unxmlify($data->location));
2309 $searchable = (unxmlify($data->searchable) == "true");
2310 $nsfw = (unxmlify($data->nsfw) == "true");
2311 $tags = unxmlify($data->tag_string);
2313 $tags = explode("#", $tags);
2316 foreach ($tags as $tag) {
2317 $tag = trim(strtolower($tag));
2323 $keywords = implode(", ", $keywords);
2325 $handle_parts = explode("@", $author);
2326 $nick = $handle_parts[0];
2329 $name = $handle_parts[0];
2332 if (preg_match("|^https?://|", $image_url) === 0) {
2333 $image_url = "http://".$handle_parts[1].$image_url;
2336 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2338 // Generic birthday. We don't know the timezone. The year is irrelevant.
2340 $birthday = str_replace("1000", "1901", $birthday);
2342 if ($birthday != "") {
2343 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2346 // this is to prevent multiple birthday notifications in a single year
2347 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2349 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2350 $birthday = $contact["bd"];
2354 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2355 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2359 dbesc(DateTimeFormat::utcNow()),
2365 intval($contact["id"]),
2366 intval($importer["uid"])
2369 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2370 "photo" => $image_url, "name" => $name, "location" => $location,
2371 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2372 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2373 "hide" => !$searchable, "nsfw" => $nsfw];
2375 $gcid = GContact::update($gcontact);
2377 GContact::link($gcid, $importer["uid"], $contact["id"]);
2379 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2385 * @brief Processes incoming friend requests
2387 * @param array $importer Array of the importer user
2388 * @param array $contact The contact that send the request
2391 private static function receiveRequestMakeFriend($importer, $contact)
2395 if ($contact["rel"] == CONTACT_IS_SHARING) {
2398 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2399 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2402 // send notification
2405 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2406 intval($importer["uid"])
2409 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2411 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2412 intval($importer["uid"])
2415 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2417 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2419 $arr["protocol"] = PROTOCOL_DIASPORA;
2420 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2421 $arr["uid"] = $importer["uid"];
2422 $arr["contact-id"] = $self[0]["id"];
2424 $arr["type"] = 'wall';
2425 $arr["gravity"] = 0;
2427 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2428 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2429 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2430 $arr["verb"] = ACTIVITY_FRIEND;
2431 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2433 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2434 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2435 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2436 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2438 $arr["object"] = self::constructNewFriendObject($contact);
2440 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2442 $arr["allow_cid"] = $user["allow_cid"];
2443 $arr["allow_gid"] = $user["allow_gid"];
2444 $arr["deny_cid"] = $user["deny_cid"];
2445 $arr["deny_gid"] = $user["deny_gid"];
2447 $i = Item::insert($arr);
2449 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2456 * @brief Creates a XML object for a "new friend" message
2458 * @param array $contact Array of the contact
2460 * @return string The XML
2462 private static function constructNewFriendObject($contact)
2464 $objtype = ACTIVITY_OBJ_PERSON;
2465 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2466 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2468 $xmldata = ["object" => ["type" => $objtype,
2469 "title" => $contact["name"],
2470 "id" => $contact["url"]."/".$contact["name"],
2473 return XML::fromArray($xmldata, $xml, true);
2477 * @brief Processes incoming sharing notification
2479 * @param array $importer Array of the importer user
2480 * @param object $data The message object
2482 * @return bool Success
2484 private static function receiveContactRequest($importer, $data)
2486 $author = unxmlify($data->author);
2487 $recipient = unxmlify($data->recipient);
2489 if (!$author || !$recipient) {
2493 // the current protocol version doesn't know these fields
2494 // That means that we will assume their existance
2495 if (isset($data->following)) {
2496 $following = (unxmlify($data->following) == "true");
2501 if (isset($data->sharing)) {
2502 $sharing = (unxmlify($data->sharing) == "true");
2507 $contact = self::contactByHandle($importer["uid"], $author);
2509 // perhaps we were already sharing with this person. Now they're sharing with us.
2510 // That makes us friends.
2513 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2514 self::receiveRequestMakeFriend($importer, $contact);
2516 // refetch the contact array
2517 $contact = self::contactByHandle($importer["uid"], $author);
2519 // If we are now friends, we are sending a share message.
2520 // Normally we needn't to do so, but the first message could have been vanished.
2521 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2522 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2524 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2525 $ret = self::sendShare($u[0], $contact);
2530 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2531 Contact::removeFollower($importer, $contact);
2536 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2537 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2539 } elseif (!$following && !$sharing) {
2540 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2542 } elseif (!$following && $sharing) {
2543 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2544 } elseif ($following && $sharing) {
2545 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2546 } elseif ($following && !$sharing) {
2547 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2550 $ret = self::personByHandle($author);
2552 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2553 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2557 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2560 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2561 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2562 intval($importer["uid"]),
2563 dbesc($ret["network"]),
2564 dbesc($ret["addr"]),
2565 DateTimeFormat::utcNow(),
2567 dbesc(normalise_link($ret["url"])),
2569 dbesc($ret["name"]),
2570 dbesc($ret["nick"]),
2571 dbesc($ret["photo"]),
2572 dbesc($ret["pubkey"]),
2573 dbesc($ret["notify"]),
2574 dbesc($ret["poll"]),
2579 // find the contact record we just created
2581 $contact_record = self::contactByHandle($importer["uid"], $author);
2583 if (!$contact_record) {
2584 logger("unable to locate newly created contact record.");
2588 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2590 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2592 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2594 if ($importer["page-flags"] == PAGE_NORMAL) {
2595 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2597 $hash = random_string().(string)time(); // Generate a confirm_key
2600 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2601 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2602 intval($importer["uid"]),
2603 intval($contact_record["id"]),
2606 dbesc(L10n::t("Sharing notification from Diaspora network")),
2608 dbesc(DateTimeFormat::utcNow())
2611 // automatic friend approval
2613 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2615 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2617 // technically they are sharing with us (CONTACT_IS_SHARING),
2618 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2619 // we are going to change the relationship and make them a follower.
2621 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2622 $new_relation = CONTACT_IS_FRIEND;
2623 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2624 $new_relation = CONTACT_IS_SHARING;
2626 $new_relation = CONTACT_IS_FOLLOWER;
2630 "UPDATE `contact` SET `rel` = %d,
2638 intval($new_relation),
2639 dbesc(DateTimeFormat::utcNow()),
2640 dbesc(DateTimeFormat::utcNow()),
2641 intval($contact_record["id"])
2644 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2646 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2647 $ret = self::sendShare($u[0], $contact_record);
2649 // Send the profile data, maybe it weren't transmitted before
2650 self::sendProfile($importer["uid"], [$contact_record]);
2658 * @brief Fetches a message with a given guid
2660 * @param string $guid message guid
2661 * @param string $orig_author handle of the original post
2662 * @param string $author handle of the sharer
2664 * @return array The fetched item
2666 private static function originalItem($guid, $orig_author, $author)
2668 // Do we already have this item?
2670 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2671 `author-name`, `author-link`, `author-avatar`
2672 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2676 if (DBM::is_result($r)) {
2677 logger("reshared message ".$guid." already exists on system.");
2679 // Maybe it is already a reshared item?
2680 // Then refetch the content, if it is a reshare from a reshare.
2681 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2682 if (self::isReshare($r[0]["body"], true)) {
2684 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2685 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2687 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2689 // Add OEmbed and other information to the body
2690 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2698 if (!DBM::is_result($r)) {
2699 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2700 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2701 $item_id = self::storeByGuid($guid, $server);
2704 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2705 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2706 $item_id = self::storeByGuid($guid, $server);
2711 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2712 `author-name`, `author-link`, `author-avatar`
2713 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2717 if (DBM::is_result($r)) {
2718 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2719 if (self::isReshare($r[0]["body"], false)) {
2720 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2721 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2732 * @brief Processes a reshare message
2734 * @param array $importer Array of the importer user
2735 * @param object $data The message object
2736 * @param string $xml The original XML of the message
2738 * @return int the message id
2740 private static function receiveReshare($importer, $data, $xml)
2742 $author = notags(unxmlify($data->author));
2743 $guid = notags(unxmlify($data->guid));
2744 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2745 $root_author = notags(unxmlify($data->root_author));
2746 $root_guid = notags(unxmlify($data->root_guid));
2747 /// @todo handle unprocessed property "provider_display_name"
2748 $public = notags(unxmlify($data->public));
2750 $contact = self::allowedContactByHandle($importer, $author, false);
2755 $message_id = self::messageExists($importer["uid"], $guid);
2760 $original_item = self::originalItem($root_guid, $root_author, $author);
2761 if (!$original_item) {
2765 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2769 $datarray["uid"] = $importer["uid"];
2770 $datarray["contact-id"] = $contact["id"];
2771 $datarray["network"] = NETWORK_DIASPORA;
2773 $datarray["author-name"] = $contact["name"];
2774 $datarray["author-link"] = $contact["url"];
2775 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2777 $datarray["owner-name"] = $datarray["author-name"];
2778 $datarray["owner-link"] = $datarray["author-link"];
2779 $datarray["owner-avatar"] = $datarray["author-avatar"];
2781 $datarray["guid"] = $guid;
2782 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2784 $datarray["verb"] = ACTIVITY_POST;
2785 $datarray["gravity"] = GRAVITY_PARENT;
2787 $datarray["protocol"] = PROTOCOL_DIASPORA;
2788 $datarray["source"] = $xml;
2790 $prefix = share_header(
2791 $original_item["author-name"],
2792 $original_item["author-link"],
2793 $original_item["author-avatar"],
2794 $original_item["guid"],
2795 $original_item["created"],
2798 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2800 $datarray["tag"] = $original_item["tag"];
2801 $datarray["app"] = $original_item["app"];
2803 $datarray["plink"] = self::plink($author, $guid);
2804 $datarray["private"] = (($public == "false") ? 1 : 0);
2805 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2807 $datarray["object-type"] = $original_item["object-type"];
2809 self::fetchGuid($datarray);
2810 $message_id = Item::insert($datarray);
2812 self::sendParticipation($contact, $datarray);
2815 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2823 * @brief Processes retractions
2825 * @param array $importer Array of the importer user
2826 * @param array $contact The contact of the item owner
2827 * @param object $data The message object
2829 * @return bool success
2831 private static function itemRetraction($importer, $contact, $data)
2833 $author = notags(unxmlify($data->author));
2834 $target_guid = notags(unxmlify($data->target_guid));
2835 $target_type = notags(unxmlify($data->target_type));
2837 $person = self::personByHandle($author);
2838 if (!is_array($person)) {
2839 logger("unable to find author detail for ".$author);
2843 if (empty($contact["url"])) {
2844 $contact["url"] = $person["url"];
2847 // Fetch items that are about to be deleted
2848 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2850 // When we receive a public retraction, we delete every item that we find.
2851 if ($importer['uid'] == 0) {
2852 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2854 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2856 $r = dba::select('item', $fields, $condition);
2857 if (!DBM::is_result($r)) {
2858 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2862 while ($item = dba::fetch($r)) {
2863 // Fetch the parent item
2864 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2866 // Only delete it if the parent author really fits
2867 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2868 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2872 Item::deleteById($item["id"]);
2874 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2876 // Now check if the retraction needs to be relayed by us
2877 if ($parent["origin"]) {
2879 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2887 * @brief Receives retraction messages
2889 * @param array $importer Array of the importer user
2890 * @param string $sender The sender of the message
2891 * @param object $data The message object
2893 * @return bool Success
2895 private static function receiveRetraction($importer, $sender, $data)
2897 $target_type = notags(unxmlify($data->target_type));
2899 $contact = self::contactByHandle($importer["uid"], $sender);
2900 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2901 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2905 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2907 switch ($target_type) {
2912 case "StatusMessage":
2913 return self::itemRetraction($importer, $contact, $data);
2917 /// @todo What should we do with an "unshare"?
2918 // Removing the contact isn't correct since we still can read the public items
2919 Contact::remove($contact["id"]);
2923 logger("Unknown target type ".$target_type);
2930 * @brief Receives status messages
2932 * @param array $importer Array of the importer user
2933 * @param object $data The message object
2934 * @param string $xml The original XML of the message
2936 * @return int The message id of the newly created item
2938 private static function receiveStatusMessage($importer, $data, $xml)
2940 $author = notags(unxmlify($data->author));
2941 $guid = notags(unxmlify($data->guid));
2942 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2943 $public = notags(unxmlify($data->public));
2944 $text = unxmlify($data->text);
2945 $provider_display_name = notags(unxmlify($data->provider_display_name));
2947 $contact = self::allowedContactByHandle($importer, $author, false);
2952 $message_id = self::messageExists($importer["uid"], $guid);
2958 if ($data->location) {
2959 foreach ($data->location->children() as $fieldname => $data) {
2960 $address[$fieldname] = notags(unxmlify($data));
2964 $body = diaspora2bb($text);
2968 // Attach embedded pictures to the body
2970 foreach ($data->photo as $photo) {
2971 $body = "[img]".unxmlify($photo->remote_photo_path).
2972 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2975 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2977 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2979 // Add OEmbed and other information to the body
2980 if (!self::isRedmatrix($contact["url"])) {
2981 $body = add_page_info_to_body($body, false, true);
2985 /// @todo enable support for polls
2986 //if ($data->poll) {
2987 // foreach ($data->poll AS $poll)
2992 /// @todo enable support for events
2994 $datarray["uid"] = $importer["uid"];
2995 $datarray["contact-id"] = $contact["id"];
2996 $datarray["network"] = NETWORK_DIASPORA;
2998 $datarray["author-name"] = $contact["name"];
2999 $datarray["author-link"] = $contact["url"];
3000 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
3002 $datarray["owner-name"] = $datarray["author-name"];
3003 $datarray["owner-link"] = $datarray["author-link"];
3004 $datarray["owner-avatar"] = $datarray["author-avatar"];
3006 $datarray["guid"] = $guid;
3007 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3009 $datarray["verb"] = ACTIVITY_POST;
3010 $datarray["gravity"] = GRAVITY_PARENT;
3012 $datarray["protocol"] = PROTOCOL_DIASPORA;
3013 $datarray["source"] = $xml;
3015 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3017 if ($provider_display_name != "") {
3018 $datarray["app"] = $provider_display_name;
3021 $datarray["plink"] = self::plink($author, $guid);
3022 $datarray["private"] = (($public == "false") ? 1 : 0);
3023 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3025 if (isset($address["address"])) {
3026 $datarray["location"] = $address["address"];
3029 if (isset($address["lat"]) && isset($address["lng"])) {
3030 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3033 self::fetchGuid($datarray);
3034 $message_id = Item::insert($datarray);
3036 self::sendParticipation($contact, $datarray);
3039 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3046 /* ************************************************************************************** *
3047 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3048 * ************************************************************************************** */
3051 * @brief returnes the handle of a contact
3053 * @param array $contact contact array
3055 * @return string the handle in the format user@domain.tld
3057 private static function myHandle($contact)
3059 if ($contact["addr"] != "") {
3060 return $contact["addr"];
3063 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3064 // So - just in case - we build the the address here.
3065 if ($contact["nickname"] != "") {
3066 $nick = $contact["nickname"];
3068 $nick = $contact["nick"];
3071 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3076 * @brief Creates the data for a private message in the new format
3078 * @param string $msg The message that is to be transmitted
3079 * @param array $user The record of the sender
3080 * @param array $contact Target of the communication
3081 * @param string $prvkey The private key of the sender
3082 * @param string $pubkey The public key of the receiver
3084 * @return string The encrypted data
3086 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3088 logger("Message: ".$msg, LOGGER_DATA);
3090 // without a public key nothing will work
3092 logger("pubkey missing: contact id: ".$contact["id"]);
3096 $aes_key = openssl_random_pseudo_bytes(32);
3097 $b_aes_key = base64_encode($aes_key);
3098 $iv = openssl_random_pseudo_bytes(16);
3099 $b_iv = base64_encode($iv);
3101 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3103 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3105 $encrypted_key_bundle = "";
3106 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3108 $json_object = json_encode(
3109 ["aes_key" => base64_encode($encrypted_key_bundle),
3110 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3113 return $json_object;
3117 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3119 * @param string $msg The message that is to be transmitted
3120 * @param array $user The record of the sender
3122 * @return string The envelope
3124 public static function buildMagicEnvelope($msg, $user)
3126 $b64url_data = base64url_encode($msg);
3127 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3129 $key_id = base64url_encode(self::myHandle($user));
3130 $type = "application/xml";
3131 $encoding = "base64url";
3132 $alg = "RSA-SHA256";
3133 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3135 // Fallback if the private key wasn't transmitted in the expected field
3136 if ($user['uprvkey'] == "") {
3137 $user['uprvkey'] = $user['prvkey'];
3140 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3141 $sig = base64url_encode($signature);
3143 $xmldata = ["me:env" => ["me:data" => $data,
3144 "@attributes" => ["type" => $type],
3145 "me:encoding" => $encoding,
3148 "@attributes2" => ["key_id" => $key_id]]];
3150 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3152 return XML::fromArray($xmldata, $xml, false, $namespaces);
3156 * @brief Create the envelope for a message
3158 * @param string $msg The message that is to be transmitted
3159 * @param array $user The record of the sender
3160 * @param array $contact Target of the communication
3161 * @param string $prvkey The private key of the sender
3162 * @param string $pubkey The public key of the receiver
3163 * @param bool $public Is the message public?
3165 * @return string The message that will be transmitted to other servers
3167 private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3169 // The message is put into an envelope with the sender's signature
3170 $envelope = self::buildMagicEnvelope($msg, $user);
3172 // Private messages are put into a second envelope, encrypted with the receivers public key
3174 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3181 * @brief Creates a signature for a message
3183 * @param array $owner the array of the owner of the message
3184 * @param array $message The message that is to be signed
3186 * @return string The signature
3188 private static function signature($owner, $message)
3191 unset($sigmsg["author_signature"]);
3192 unset($sigmsg["parent_author_signature"]);
3194 $signed_text = implode(";", $sigmsg);
3196 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3200 * @brief Transmit a message to a target server
3202 * @param array $owner the array of the item owner
3203 * @param array $contact Target of the communication
3204 * @param string $envelope The message that is to be transmitted
3205 * @param bool $public_batch Is it a public post?
3206 * @param bool $queue_run Is the transmission called from the queue?
3207 * @param string $guid message guid
3209 * @return int Result of the transmission
3211 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3215 $enabled = intval(Config::get("system", "diaspora_enabled"));
3220 $logid = random_string(4);
3222 // We always try to use the data from the fcontact table.
3223 // This is important for transmitting data to Friendica servers.
3224 if (!empty($contact['addr'])) {
3225 $fcontact = self::personByHandle($contact['addr']);
3226 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3228 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3232 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3236 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3238 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3241 if (!intval(Config::get("system", "diaspora_test"))) {
3242 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3244 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3245 $return_code = $a->get_curl_code();
3247 logger("test_mode");
3252 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3254 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3256 logger("queue message");
3257 // queue message for redelivery
3258 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3261 // The message could not be delivered. We mark the contact as "dead"
3262 Contact::markForArchival($contact);
3263 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3264 // We successfully delivered a message, the contact is alive
3265 Contact::unmarkForArchival($contact);
3268 return $return_code ? $return_code : -1;
3273 * @brief Build the post xml
3275 * @param string $type The message type
3276 * @param array $message The message data
3278 * @return string The post XML
3280 public static function buildPostXml($type, $message)
3282 $data = [$type => $message];
3284 return XML::fromArray($data, $xml);
3288 * @brief Builds and transmit messages
3290 * @param array $owner the array of the item owner
3291 * @param array $contact Target of the communication
3292 * @param string $type The message type
3293 * @param array $message The message data
3294 * @param bool $public_batch Is it a public post?
3295 * @param string $guid message guid
3296 * @param bool $spool Should the transmission be spooled or transmitted?
3298 * @return int Result of the transmission
3300 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3302 $msg = self::buildPostXml($type, $message);
3304 logger('message: '.$msg, LOGGER_DATA);
3305 logger('send guid '.$guid, LOGGER_DEBUG);
3307 // Fallback if the private key wasn't transmitted in the expected field
3308 if ($owner['uprvkey'] == "") {
3309 $owner['uprvkey'] = $owner['prvkey'];
3312 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3315 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3318 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3321 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3323 return $return_code;
3327 * @brief sends a participation (Used to get all further updates)
3329 * @param array $contact Target of the communication
3330 * @param array $item Item array
3332 * @return int The result of the transmission
3334 private static function sendParticipation($contact, $item)
3336 // Don't send notifications for private postings
3337 if ($item['private']) {
3341 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3343 $result = Cache::get($cachekey);
3344 if (!is_null($result)) {
3348 // Fetch some user id to have a valid handle to transmit the participation.
3349 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3350 // If the item belongs to a user, we take this user id.
3351 if ($item['uid'] == 0) {
3352 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3353 $first_user = dba::selectFirst('user', ['uid'], $condition);
3354 $owner = User::getOwnerDataById($first_user['uid']);
3356 $owner = User::getOwnerDataById($item['uid']);
3359 $author = self::myHandle($owner);
3361 $message = ["author" => $author,
3362 "guid" => get_guid(32),
3363 "parent_type" => "Post",
3364 "parent_guid" => $item["guid"]];
3366 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3368 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3369 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3371 return self::buildAndTransmit($owner, $contact, "participation", $message);
3375 * @brief sends an account migration
3377 * @param array $owner the array of the item owner
3378 * @param array $contact Target of the communication
3379 * @param int $uid User ID
3381 * @return int The result of the transmission
3383 public static function sendAccountMigration($owner, $contact, $uid)
3385 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3386 $profile = self::createProfileData($uid);
3388 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3389 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3391 $message = ["author" => $old_handle,
3392 "profile" => $profile,
3393 "signature" => $signature];
3395 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3397 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3401 * @brief Sends a "share" message
3403 * @param array $owner the array of the item owner
3404 * @param array $contact Target of the communication
3406 * @return int The result of the transmission
3408 public static function sendShare($owner, $contact)
3411 * @todo support the different possible combinations of "following" and "sharing"
3412 * Currently, Diaspora only interprets the "sharing" field
3414 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3418 switch ($contact["rel"]) {
3419 case CONTACT_IS_FRIEND:
3422 case CONTACT_IS_SHARING:
3425 case CONTACT_IS_FOLLOWER:
3431 $message = ["author" => self::myHandle($owner),
3432 "recipient" => $contact["addr"],
3433 "following" => "true",
3434 "sharing" => "true"];
3436 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3438 return self::buildAndTransmit($owner, $contact, "contact", $message);
3442 * @brief sends an "unshare"
3444 * @param array $owner the array of the item owner
3445 * @param array $contact Target of the communication
3447 * @return int The result of the transmission
3449 public static function sendUnshare($owner, $contact)
3451 $message = ["author" => self::myHandle($owner),
3452 "recipient" => $contact["addr"],
3453 "following" => "false",
3454 "sharing" => "false"];
3456 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3458 return self::buildAndTransmit($owner, $contact, "contact", $message);
3462 * @brief Checks a message body if it is a reshare
3464 * @param string $body The message body that is to be check
3465 * @param bool $complete Should it be a complete check or a simple check?
3467 * @return array|bool Reshare details or "false" if no reshare
3469 public static function isReshare($body, $complete = true)
3471 $body = trim($body);
3473 // Skip if it isn't a pure repeated messages
3474 // Does it start with a share?
3475 if ((strpos($body, "[share") > 0) && $complete) {
3479 // Does it end with a share?
3480 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3484 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3485 // Skip if there is no shared message in there
3486 if ($body == $attributes) {
3490 // If we don't do the complete check we quit here
3496 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3497 if ($matches[1] != "") {
3498 $guid = $matches[1];
3501 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3502 if ($matches[1] != "") {
3503 $guid = $matches[1];
3508 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3515 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3516 $ret["root_guid"] = $guid;
3522 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3523 if ($matches[1] != "") {
3524 $profile = $matches[1];
3527 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3528 if ($matches[1] != "") {
3529 $profile = $matches[1];
3534 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3535 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3540 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3541 if ($matches[1] != "") {
3542 $link = $matches[1];
3545 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3546 if ($matches[1] != "") {
3547 $link = $matches[1];
3550 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3551 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3559 * @brief Create an event array
3561 * @param integer $event_id The id of the event
3563 * @return array with event data
3565 private static function buildEvent($event_id)
3567 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3568 if (!DBM::is_result($r)) {
3576 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3577 if (!DBM::is_result($r)) {
3583 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3584 if (!DBM::is_result($r)) {
3590 $eventdata['author'] = self::myHandle($owner);
3592 if ($event['guid']) {
3593 $eventdata['guid'] = $event['guid'];
3596 $mask = DateTimeFormat::ATOM;
3598 /// @todo - establish "all day" events in Friendica
3599 $eventdata["all_day"] = "false";
3601 if (!$event['adjust']) {
3602 $eventdata['timezone'] = $user['timezone'];
3604 if ($eventdata['timezone'] == "") {
3605 $eventdata['timezone'] = 'UTC';
3609 if ($event['start']) {
3610 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3612 if ($event['finish'] && !$event['nofinish']) {
3613 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3615 if ($event['summary']) {
3616 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3618 if ($event['desc']) {
3619 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3621 if ($event['location']) {
3622 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3623 $coord = Map::getCoordinates($event['location']);
3626 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3627 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3628 $location["lat"] = $coord['lat'];
3629 $location["lng"] = $coord['lon'];
3631 $location["lat"] = 0;
3632 $location["lng"] = 0;
3634 $eventdata['location'] = $location;
3641 * @brief Create a post (status message or reshare)
3643 * @param array $item The item that will be exported
3644 * @param array $owner the array of the item owner
3647 * 'type' -> Message type ("status_message" or "reshare")
3648 * 'message' -> Array of XML elements of the status
3650 public static function buildStatus($item, $owner)
3652 $cachekey = "diaspora:buildStatus:".$item['guid'];
3654 $result = Cache::get($cachekey);
3655 if (!is_null($result)) {
3659 $myaddr = self::myHandle($owner);
3661 $public = (($item["private"]) ? "false" : "true");
3663 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3665 // Detect a share element and do a reshare
3666 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3667 $message = ["author" => $myaddr,
3668 "guid" => $item["guid"],
3669 "created_at" => $created,
3670 "root_author" => $ret["root_handle"],
3671 "root_guid" => $ret["root_guid"],
3672 "provider_display_name" => $item["app"],
3673 "public" => $public];
3677 $title = $item["title"];
3678 $body = $item["body"];
3680 // convert to markdown
3681 $body = html_entity_decode(bb2diaspora($body));
3684 if (strlen($title)) {
3685 $body = "## ".html_entity_decode($title)."\n\n".$body;
3688 if ($item["attach"]) {
3689 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3691 $body .= "\n".L10n::t("Attachments:")."\n";
3692 foreach ($matches as $mtch) {
3693 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3700 if ($item["location"] != "")
3701 $location["address"] = $item["location"];
3703 if ($item["coord"] != "") {
3704 $coord = explode(" ", $item["coord"]);
3705 $location["lat"] = $coord[0];
3706 $location["lng"] = $coord[1];
3709 $message = ["author" => $myaddr,
3710 "guid" => $item["guid"],
3711 "created_at" => $created,
3712 "public" => $public,
3714 "provider_display_name" => $item["app"],
3715 "location" => $location];
3717 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3718 if (!isset($location["lat"]) || !isset($location["lng"])) {
3719 unset($message["location"]);
3722 if ($item['event-id'] > 0) {
3723 $event = self::buildEvent($item['event-id']);
3724 if (count($event)) {
3725 $message['event'] = $event;
3727 if (!empty($event['location']['address']) &&
3728 !empty($event['location']['lat']) &&
3729 !empty($event['location']['lng'])) {
3730 $message['location'] = $event['location'];
3733 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3734 // $message['text'] = '';
3738 $type = "status_message";
3741 $msg = ["type" => $type, "message" => $message];
3743 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3749 * @brief Sends a post
3751 * @param array $item The item that will be exported
3752 * @param array $owner the array of the item owner
3753 * @param array $contact Target of the communication
3754 * @param bool $public_batch Is it a public post?
3756 * @return int The result of the transmission
3758 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3760 $status = self::buildStatus($item, $owner);
3762 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3766 * @brief Creates a "like" object
3768 * @param array $item The item that will be exported
3769 * @param array $owner the array of the item owner
3771 * @return array The data for a "like"
3773 private static function constructLike($item, $owner)
3776 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3777 dbesc($item["thr-parent"])
3779 if (!DBM::is_result($p)) {
3785 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3787 if ($item['verb'] === ACTIVITY_LIKE) {
3789 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3790 $positive = "false";
3793 return(["author" => self::myHandle($owner),
3794 "guid" => $item["guid"],
3795 "parent_guid" => $parent["guid"],
3796 "parent_type" => $target_type,
3797 "positive" => $positive,
3798 "author_signature" => ""]);
3802 * @brief Creates an "EventParticipation" object
3804 * @param array $item The item that will be exported
3805 * @param array $owner the array of the item owner
3807 * @return array The data for an "EventParticipation"
3809 private static function constructAttend($item, $owner)
3812 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3813 dbesc($item["thr-parent"])
3815 if (!DBM::is_result($p)) {
3821 switch ($item['verb']) {
3822 case ACTIVITY_ATTEND:
3823 $attend_answer = 'accepted';
3825 case ACTIVITY_ATTENDNO:
3826 $attend_answer = 'declined';
3828 case ACTIVITY_ATTENDMAYBE:
3829 $attend_answer = 'tentative';
3832 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3836 return(["author" => self::myHandle($owner),
3837 "guid" => $item["guid"],
3838 "parent_guid" => $parent["guid"],
3839 "status" => $attend_answer,
3840 "author_signature" => ""]);
3844 * @brief Creates the object for a comment
3846 * @param array $item The item that will be exported
3847 * @param array $owner the array of the item owner
3849 * @return array The data for a comment
3851 private static function constructComment($item, $owner)
3853 $cachekey = "diaspora:constructComment:".$item['guid'];
3855 $result = Cache::get($cachekey);
3856 if (!is_null($result)) {
3861 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3862 intval($item["parent"]),
3863 intval($item["parent"])
3866 if (!DBM::is_result($p)) {
3872 $text = html_entity_decode(bb2diaspora($item["body"]));
3873 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3875 $comment = ["author" => self::myHandle($owner),
3876 "guid" => $item["guid"],
3877 "created_at" => $created,
3878 "parent_guid" => $parent["guid"],
3880 "author_signature" => ""];
3882 // Send the thread parent guid only if it is a threaded comment
3883 if ($item['thr-parent'] != $item['parent-uri']) {
3884 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3887 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3893 * @brief Send a like or a comment
3895 * @param array $item The item that will be exported
3896 * @param array $owner the array of the item owner
3897 * @param array $contact Target of the communication
3898 * @param bool $public_batch Is it a public post?
3900 * @return int The result of the transmission
3902 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3904 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3905 $message = self::constructAttend($item, $owner);
3906 $type = "event_participation";
3907 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3908 $message = self::constructLike($item, $owner);
3911 $message = self::constructComment($item, $owner);
3919 $message["author_signature"] = self::signature($owner, $message);
3921 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3925 * @brief Creates a message from a signature record entry
3927 * @param array $item The item that will be exported
3928 * @param array $signature The entry of the "sign" record
3930 * @return string The message
3932 private static function messageFromSignature($item, $signature)
3934 // Split the signed text
3935 $signed_parts = explode(";", $signature['signed_text']);
3937 if ($item["deleted"]) {
3938 $message = ["author" => $signature['signer'],
3939 "target_guid" => $signed_parts[0],
3940 "target_type" => $signed_parts[1]];
3941 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3942 $message = ["author" => $signed_parts[4],
3943 "guid" => $signed_parts[1],
3944 "parent_guid" => $signed_parts[3],
3945 "parent_type" => $signed_parts[2],
3946 "positive" => $signed_parts[0],
3947 "author_signature" => $signature['signature'],
3948 "parent_author_signature" => ""];
3950 // Remove the comment guid
3951 $guid = array_shift($signed_parts);
3953 // Remove the parent guid
3954 $parent_guid = array_shift($signed_parts);
3956 // Remove the handle
3957 $handle = array_pop($signed_parts);
3959 // Glue the parts together
3960 $text = implode(";", $signed_parts);
3962 $message = ["author" => $handle,
3964 "parent_guid" => $parent_guid,
3965 "text" => implode(";", $signed_parts),
3966 "author_signature" => $signature['signature'],
3967 "parent_author_signature" => ""];
3973 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3975 * @param array $item The item that will be exported
3976 * @param array $owner the array of the item owner
3977 * @param array $contact Target of the communication
3978 * @param bool $public_batch Is it a public post?
3980 * @return int The result of the transmission
3982 public static function sendRelay($item, $owner, $contact, $public_batch = false)
3984 if ($item["deleted"]) {
3985 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3986 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3992 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3994 // fetch the original signature
3997 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
4002 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4008 // Old way - is used by the internal Friendica functions
4009 /// @todo Change all signatur storing functions to the new format
4010 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
4011 $message = self::messageFromSignature($item, $signature);
4013 $msg = json_decode($signature['signed_text'], true);
4016 if (is_array($msg)) {
4017 foreach ($msg as $field => $data) {
4018 if (!$item["deleted"]) {
4019 if ($field == "diaspora_handle") {
4022 if ($field == "target_type") {
4023 $field = "parent_type";
4027 $message[$field] = $data;
4030 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4034 $message["parent_author_signature"] = self::signature($owner, $message);
4036 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4038 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4042 * @brief Sends a retraction (deletion) of a message, like or comment
4044 * @param array $item The item that will be exported
4045 * @param array $owner the array of the item owner
4046 * @param array $contact Target of the communication
4047 * @param bool $public_batch Is it a public post?
4048 * @param bool $relay Is the retraction transmitted from a relay?
4050 * @return int The result of the transmission
4052 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4054 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4056 $msg_type = "retraction";
4058 if ($item['id'] == $item['parent']) {
4059 $target_type = "Post";
4060 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4061 $target_type = "Like";
4063 $target_type = "Comment";
4066 $message = ["author" => $itemaddr,
4067 "target_guid" => $item['guid'],
4068 "target_type" => $target_type];
4070 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4072 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4076 * @brief Sends a mail
4078 * @param array $item The item that will be exported
4079 * @param array $owner The owner
4080 * @param array $contact Target of the communication
4082 * @return int The result of the transmission
4084 public static function sendMail($item, $owner, $contact)
4086 $myaddr = self::myHandle($owner);
4089 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4090 intval($item["convid"]),
4091 intval($item["uid"])
4094 if (!DBM::is_result($r)) {
4095 logger("conversation not found.");
4101 "author" => $cnv["creator"],
4102 "guid" => $cnv["guid"],
4103 "subject" => $cnv["subject"],
4104 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4105 "participants" => $cnv["recips"]
4108 $body = bb2diaspora($item["body"]);
4109 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4112 "author" => $myaddr,
4113 "guid" => $item["guid"],
4114 "conversation_guid" => $cnv["guid"],
4116 "created_at" => $created,
4119 if ($item["reply"]) {
4124 "author" => $cnv["creator"],
4125 "guid" => $cnv["guid"],
4126 "subject" => $cnv["subject"],
4127 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4128 "participants" => $cnv["recips"],
4131 $type = "conversation";
4134 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4138 * @brief Split a name into first name and last name
4140 * @param string $name The name
4142 * @return array The array with "first" and "last"
4144 public static function splitName($name) {
4145 $name = trim($name);
4147 // Is the name longer than 64 characters? Then cut the rest of it.
4148 if (strlen($name) > 64) {
4149 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4150 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4152 $name = substr($name, 0, 64);
4156 // Take the first word as first name
4157 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4158 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4159 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4160 return ['first' => $first, 'last' => $last];
4163 // Take the last word as last name
4164 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4165 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4167 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4168 return ['first' => $first, 'last' => $last];
4171 // Take the first 32 characters if there is no space in the first 32 characters
4172 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4173 $first = substr($name, 0, 32);
4174 $last = substr($name, 32);
4175 return ['first' => $first, 'last' => $last];
4178 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4179 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4181 // Check if the last name is longer than 32 characters
4182 if (strlen($last) > 32) {
4183 if (strpos($last, ' ') <= 32) {
4184 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4186 $last = substr($last, 0, 32);
4190 return ['first' => $first, 'last' => $last];
4194 * @brief Create profile data
4196 * @param int $uid The user id
4198 * @return array The profile data
4200 private static function createProfileData($uid)
4203 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4205 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4206 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4207 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4216 $handle = $profile["addr"];
4218 $split_name = self::splitName($profile['name']);
4219 $first = $split_name['first'];
4220 $last = $split_name['last'];
4222 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4223 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4224 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4225 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4231 if ($searchable === 'true') {
4234 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4235 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4239 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4242 $about = $profile['about'];
4243 $about = strip_tags(BBCode::convert($about));
4245 $location = Profile::formatLocation($profile);
4247 if ($profile['pub_keywords']) {
4248 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4249 $kw = str_replace(' ', ' ', $kw);
4250 $arr = explode(' ', $profile['pub_keywords']);
4252 for ($x = 0; $x < 5; $x ++) {
4253 if (trim($arr[$x])) {
4254 $tags .= '#'. trim($arr[$x]) .' ';
4259 $tags = trim($tags);
4262 return ["author" => $handle,
4263 "first_name" => $first,
4264 "last_name" => $last,
4265 "image_url" => $large,
4266 "image_url_medium" => $medium,
4267 "image_url_small" => $small,
4269 "gender" => $profile['gender'],
4271 "location" => $location,
4272 "searchable" => $searchable,
4274 "tag_string" => $tags];
4278 * @brief Sends profile data
4280 * @param int $uid The user id
4281 * @param bool $recips optional, default false
4284 public static function sendProfile($uid, $recips = false)
4290 $owner = User::getOwnerDataById($uid);
4297 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4298 AND `uid` = %d AND `rel` != %d",
4299 dbesc(NETWORK_DIASPORA),
4301 intval(CONTACT_IS_SHARING)
4309 $message = self::createProfileData($uid);
4311 foreach ($recips as $recip) {
4312 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4313 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4318 * @brief Stores the signature for likes that are created on our system
4320 * @param array $contact The contact array of the "like"
4321 * @param int $post_id The post id of the "like"
4323 * @return bool Success
4325 public static function storeLikeSignature($contact, $post_id)
4327 // Is the contact the owner? Then fetch the private key
4328 if (!$contact['self'] || ($contact['uid'] == 0)) {
4329 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4333 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4334 if (!DBM::is_result($r)) {
4338 $contact["uprvkey"] = $r[0]['prvkey'];
4340 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4341 if (!DBM::is_result($r)) {
4345 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4349 $message = self::constructLike($r[0], $contact);
4350 if ($message === false) {
4354 $message["author_signature"] = self::signature($contact, $message);
4357 * Now store the signature more flexible to dynamically support new fields.
4358 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4360 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4362 logger('Stored diaspora like signature');
4367 * @brief Stores the signature for comments that are created on our system
4369 * @param array $item The item array of the comment
4370 * @param array $contact The contact array of the item owner
4371 * @param string $uprvkey The private key of the sender
4372 * @param int $message_id The message id of the comment
4374 * @return bool Success
4376 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4378 if ($uprvkey == "") {
4379 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4383 $contact["uprvkey"] = $uprvkey;
4385 $message = self::constructComment($item, $contact);
4386 if ($message === false) {
4390 $message["author_signature"] = self::signature($contact, $message);
4393 * Now store the signature more flexible to dynamically support new fields.
4394 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4396 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4398 logger('Stored diaspora comment signature');