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.
11 namespace Friendica\Protocol;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\Markdown;
15 use Friendica\Core\Cache;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\Queue;
28 use Friendica\Model\User;
29 use Friendica\Network\Probe;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Util\Map;
38 require_once 'include/dba.php';
39 require_once 'include/items.php';
42 * @brief This class contain functions to create and send Diaspora XML files
48 * @brief Return a list of relay servers
50 * This is an experimental Diaspora feature.
52 * @return array of relay servers
54 public static function relayList()
56 $serverdata = Config::get("system", "relay_server");
57 if ($serverdata == "") {
63 $servers = explode(",", $serverdata);
65 foreach ($servers as $server) {
66 $server = trim($server);
67 $addr = "relay@".str_replace("http://", "", normalise_link($server));
68 $batch = $server."/receive/public";
71 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
74 dbesc(normalise_link($server))
79 "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
80 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
81 DateTimeFormat::utcNow(),
85 dbesc(normalise_link($server)),
87 dbesc(NETWORK_DIASPORA),
88 intval(CONTACT_IS_FOLLOWER),
89 dbesc(DateTimeFormat::utcNow()),
90 dbesc(DateTimeFormat::utcNow()),
91 dbesc(DateTimeFormat::utcNow())
94 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
96 $relay[] = $relais[0];
99 $relay[] = $relais[0];
107 * @brief Return a list of participating contacts for a thread
109 * This is used for the participation feature.
110 * One of the parameters is a contact array.
111 * This is done to avoid duplicates.
113 * @param integer $thread The id of the thread
114 * @param array $contacts The previously fetched contacts
116 * @return array of relay servers
118 public static function participantsForThread($thread, $contacts)
120 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
121 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
122 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
123 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
124 WHERE `participation`.`iid` = ?", $thread);
126 while ($contact = dba::fetch($r)) {
127 if (!empty($contact['fnetwork'])) {
128 $contact['network'] = $contact['fnetwork'];
130 unset($contact['fnetwork']);
132 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
133 $contact['batch'] = $contact['fbatch'];
135 unset($contact['fbatch']);
138 foreach ($contacts as $entry) {
139 if ($entry['batch'] == $contact['batch']) {
145 $contacts[] = $contact;
154 * @brief repairs a signature that was double encoded
156 * The function is unused at the moment. It was copied from the old implementation.
158 * @param string $signature The signature
159 * @param string $handle The handle of the signature owner
160 * @param integer $level This value is only set inside this function to avoid endless loops
162 * @return string the repaired signature
164 private static function repairSignature($signature, $handle = "", $level = 1)
166 if ($signature == "") {
170 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
171 $signature = base64_decode($signature);
172 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
174 // Do a recursive call to be able to fix even multiple levels
176 $signature = self::repairSignature($signature, $handle, ++$level);
184 * @brief verify the envelope and return the verified data
186 * @param string $envelope The magic envelope
188 * @return string verified data
190 private static function verifyMagicEnvelope($envelope)
192 $basedom = XML::parseString($envelope);
194 if (!is_object($basedom)) {
195 logger("Envelope is no XML file");
199 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
201 if (sizeof($children) == 0) {
202 logger("XML has no children");
208 $data = base64url_decode($children->data);
209 $type = $children->data->attributes()->type[0];
211 $encoding = $children->encoding;
213 $alg = $children->alg;
215 $sig = base64url_decode($children->sig);
216 $key_id = $children->sig->attributes()->key_id[0];
218 $handle = base64url_decode($key_id);
221 $b64url_data = base64url_encode($data);
222 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
224 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
227 logger('No author could be decoded. Discarding. Message: ' . $envelope);
231 $key = self::key($handle);
233 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
237 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
239 logger('Message from ' . $handle . ' did not verify. Discarding.');
247 * @brief encrypts data via AES
249 * @param string $key The AES key
250 * @param string $iv The IV (is used for CBC encoding)
251 * @param string $data The data that is to be encrypted
253 * @return string encrypted data
255 private static function aesEncrypt($key, $iv, $data)
257 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
261 * @brief decrypts data via AES
263 * @param string $key The AES key
264 * @param string $iv The IV (is used for CBC encoding)
265 * @param string $encrypted The encrypted data
267 * @return string decrypted data
269 private static function aesDecrypt($key, $iv, $encrypted)
271 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
275 * @brief: Decodes incoming Diaspora message in the new format
277 * @param array $importer Array of the importer user
278 * @param string $raw raw post message
281 * 'message' -> decoded Diaspora XML message
282 * 'author' -> author diaspora handle
283 * 'key' -> author public key (converted to pkcs#8)
285 public static function decodeRaw($importer, $raw)
287 $data = json_decode($raw);
289 // Is it a private post? Then decrypt the outer Salmon
290 if (is_object($data)) {
291 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
292 $ciphertext = base64_decode($data->encrypted_magic_envelope);
294 $outer_key_bundle = '';
295 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
296 $j_outer_key_bundle = json_decode($outer_key_bundle);
298 if (!is_object($j_outer_key_bundle)) {
299 logger('Outer Salmon did not verify. Discarding.');
300 System::httpExit(400);
303 $outer_iv = base64_decode($j_outer_key_bundle->iv);
304 $outer_key = base64_decode($j_outer_key_bundle->key);
306 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
311 $basedom = XML::parseString($xml);
313 if (!is_object($basedom)) {
314 logger('Received data does not seem to be an XML. Discarding. '.$xml);
315 System::httpExit(400);
318 $base = $basedom->children(NAMESPACE_SALMON_ME);
320 // Not sure if this cleaning is needed
321 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
323 // Build the signed data
324 $type = $base->data[0]->attributes()->type[0];
325 $encoding = $base->encoding;
327 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
329 // This is the signature
330 $signature = base64url_decode($base->sig);
332 // Get the senders' public key
333 $key_id = $base->sig[0]->attributes()->key_id[0];
334 $author_addr = base64_decode($key_id);
335 if ($author_addr == '') {
336 logger('No author could be decoded. Discarding. Message: ' . $xml);
337 System::httpExit(400);
340 $key = self::key($author_addr);
342 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
343 System::httpExit(400);
346 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
348 logger('Message did not verify. Discarding.');
349 System::httpExit(400);
352 return ['message' => (string)base64url_decode($base->data),
353 'author' => unxmlify($author_addr),
354 'key' => (string)$key];
358 * @brief: Decodes incoming Diaspora message in the deprecated format
360 * @param array $importer Array of the importer user
361 * @param string $xml urldecoded Diaspora salmon
364 * 'message' -> decoded Diaspora XML message
365 * 'author' -> author diaspora handle
366 * 'key' -> author public key (converted to pkcs#8)
368 public static function decode($importer, $xml)
371 $basedom = XML::parseString($xml);
373 if (!is_object($basedom)) {
374 logger("XML is not parseable.");
377 $children = $basedom->children('https://joindiaspora.com/protocol');
379 $inner_aes_key = null;
382 if ($children->header) {
384 $author_link = str_replace('acct:', '', $children->header->author_id);
386 // This happens with posts from a relais
388 logger("This is no private post in the old format", LOGGER_DEBUG);
392 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
394 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
395 $ciphertext = base64_decode($encrypted_header->ciphertext);
397 $outer_key_bundle = '';
398 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
400 $j_outer_key_bundle = json_decode($outer_key_bundle);
402 $outer_iv = base64_decode($j_outer_key_bundle->iv);
403 $outer_key = base64_decode($j_outer_key_bundle->key);
405 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
407 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
408 $idom = XML::parseString($decrypted);
410 $inner_iv = base64_decode($idom->iv);
411 $inner_aes_key = base64_decode($idom->aes_key);
413 $author_link = str_replace('acct:', '', $idom->author_id);
416 $dom = $basedom->children(NAMESPACE_SALMON_ME);
418 // figure out where in the DOM tree our data is hiding
421 if ($dom->provenance->data) {
422 $base = $dom->provenance;
423 } elseif ($dom->env->data) {
425 } elseif ($dom->data) {
430 logger('unable to locate salmon data in xml');
431 System::httpExit(400);
435 // Stash the signature away for now. We have to find their key or it won't be good for anything.
436 $signature = base64url_decode($base->sig);
440 // strip whitespace so our data element will return to one big base64 blob
441 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
444 // stash away some other stuff for later
446 $type = $base->data[0]->attributes()->type[0];
447 $keyhash = $base->sig[0]->attributes()->keyhash[0];
448 $encoding = $base->encoding;
452 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
456 $data = base64url_decode($data);
460 $inner_decrypted = $data;
462 // Decode the encrypted blob
463 $inner_encrypted = base64_decode($data);
464 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
468 logger('Could not retrieve author URI.');
469 System::httpExit(400);
471 // Once we have the author URI, go to the web and try to find their public key
472 // (first this will look it up locally if it is in the fcontact cache)
473 // This will also convert diaspora public key from pkcs#1 to pkcs#8
475 logger('Fetching key for '.$author_link);
476 $key = self::key($author_link);
479 logger('Could not retrieve author key.');
480 System::httpExit(400);
483 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
486 logger('Message did not verify. Discarding.');
487 System::httpExit(400);
490 logger('Message verified.');
492 return ['message' => (string)$inner_decrypted,
493 'author' => unxmlify($author_link),
494 'key' => (string)$key];
499 * @brief Dispatches public messages and find the fitting receivers
501 * @param array $msg The post that will be dispatched
503 * @return int The message id of the generated message, "true" or "false" if there was an error
505 public static function dispatchPublic($msg)
507 $enabled = intval(Config::get("system", "diaspora_enabled"));
509 logger("diaspora is disabled");
513 if (!($postdata = self::validPosting($msg))) {
514 logger("Invalid posting");
518 $fields = $postdata['fields'];
520 // Is it a an action (comment, like, ...) for our own post?
521 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
522 $guid = notags(unxmlify($fields->parent_guid));
523 $importer = self::importerForGuid($guid);
524 if (is_array($importer)) {
525 logger("delivering to origin: ".$importer["name"]);
526 $message_id = self::dispatch($importer, $msg, $fields);
531 // Process item retractions. This has to be done separated from the other stuff,
532 // since retractions for comments could come even from non followers.
533 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
534 $target = notags(unxmlify($fields->target_type));
535 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
536 logger('processing retraction for '.$target, LOGGER_DEBUG);
537 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
538 $message_id = self::dispatch($importer, $msg, $fields);
543 // Now distribute it to the followers
545 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
546 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
547 AND NOT `account_expired` AND NOT `account_removed`",
548 dbesc(NETWORK_DIASPORA),
549 dbesc($msg["author"])
552 if (DBM::is_result($r)) {
553 foreach ($r as $rr) {
554 logger("delivering to: ".$rr["username"]);
555 self::dispatch($rr, $msg, $fields);
557 } elseif (!Config::get('system', 'relay_subscribe', false)) {
558 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
560 // Use a dummy importer to import the data for the public copy
561 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
562 $message_id = self::dispatch($importer, $msg, $fields);
569 * @brief Dispatches the different message types to the different functions
571 * @param array $importer Array of the importer user
572 * @param array $msg The post that will be dispatched
573 * @param object $fields SimpleXML object that contains the message
575 * @return int The message id of the generated message, "true" or "false" if there was an error
577 public static function dispatch($importer, $msg, $fields = null)
579 // The sender is the handle of the contact that sent the message.
580 // This will often be different with relayed messages (for example "like" and "comment")
581 $sender = $msg["author"];
583 // This is only needed for private postings since this is already done for public ones before
584 if (is_null($fields)) {
585 if (!($postdata = self::validPosting($msg))) {
586 logger("Invalid posting");
589 $fields = $postdata['fields'];
592 $type = $fields->getName();
594 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
597 case "account_migration":
598 return self::receiveAccountMigration($importer, $fields);
600 case "account_deletion":
601 return self::receiveAccountDeletion($importer, $fields);
604 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
607 return self::receiveContactRequest($importer, $fields);
610 return self::receiveConversation($importer, $msg, $fields);
613 return self::receiveLike($importer, $sender, $fields);
616 return self::receiveMessage($importer, $fields);
618 case "participation":
619 return self::receiveParticipation($importer, $fields);
621 case "photo": // Not implemented
622 return self::receivePhoto($importer, $fields);
624 case "poll_participation": // Not implemented
625 return self::receivePollParticipation($importer, $fields);
628 return self::receiveProfile($importer, $fields);
631 return self::receiveReshare($importer, $fields, $msg["message"]);
634 return self::receiveRetraction($importer, $sender, $fields);
636 case "status_message":
637 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
640 logger("Unknown message type ".$type);
648 * @brief Checks if a posting is valid and fetches the data fields.
650 * This function does not only check the signature.
651 * It also does the conversion between the old and the new diaspora format.
653 * @param array $msg Array with the XML, the sender handle and the sender signature
655 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
657 private static function validPosting($msg)
659 $data = XML::parseString($msg["message"]);
661 if (!is_object($data)) {
662 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
666 // Is this the new or the old version?
667 if ($data->getName() == "XML") {
669 foreach ($data->post->children() as $child) {
677 $type = $element->getName();
680 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
682 // All retractions are handled identically from now on.
683 // In the new version there will only be "retraction".
684 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
685 $type = "retraction";
687 if ($type == "request") {
691 $fields = new SimpleXMLElement("<".$type."/>");
694 $author_signature = null;
695 $parent_author_signature = null;
697 foreach ($element->children() as $fieldname => $entry) {
699 // Translation for the old XML structure
700 if ($fieldname == "diaspora_handle") {
701 $fieldname = "author";
703 if ($fieldname == "participant_handles") {
704 $fieldname = "participants";
706 if (in_array($type, ["like", "participation"])) {
707 if ($fieldname == "target_type") {
708 $fieldname = "parent_type";
711 if ($fieldname == "sender_handle") {
712 $fieldname = "author";
714 if ($fieldname == "recipient_handle") {
715 $fieldname = "recipient";
717 if ($fieldname == "root_diaspora_id") {
718 $fieldname = "root_author";
720 if ($type == "status_message") {
721 if ($fieldname == "raw_message") {
725 if ($type == "retraction") {
726 if ($fieldname == "post_guid") {
727 $fieldname = "target_guid";
729 if ($fieldname == "type") {
730 $fieldname = "target_type";
735 if (($fieldname == "author_signature") && ($entry != "")) {
736 $author_signature = base64_decode($entry);
737 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
738 $parent_author_signature = base64_decode($entry);
739 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
740 if ($signed_data != "") {
744 $signed_data .= $entry;
746 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
747 || ($orig_type == "relayable_retraction")
749 XML::copy($entry, $fields, $fieldname);
753 // This is something that shouldn't happen at all.
754 if (in_array($type, ["status_message", "reshare", "profile"])) {
755 if ($msg["author"] != $fields->author) {
756 logger("Message handle is not the same as envelope sender. Quitting this message.");
761 // Only some message types have signatures. So we quit here for the other types.
762 if (!in_array($type, ["comment", "like"])) {
763 return ["fields" => $fields, "relayed" => false];
765 // No author_signature? This is a must, so we quit.
766 if (!isset($author_signature)) {
767 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
771 if (isset($parent_author_signature)) {
774 $key = self::key($msg["author"]);
776 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
777 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);
784 $key = self::key($fields->author);
786 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
787 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
790 return ["fields" => $fields, "relayed" => $relayed];
795 * @brief Fetches the public key for a given handle
797 * @param string $handle The handle
799 * @return string The public key
801 private static function key($handle)
803 $handle = strval($handle);
805 logger("Fetching diaspora key for: ".$handle);
807 $r = self::personByHandle($handle);
816 * @brief Fetches data for a given handle
818 * @param string $handle The handle
820 * @return array the queried data
822 public static function personByHandle($handle)
826 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
827 if (DBM::is_result($person)) {
828 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
830 // update record occasionally so it doesn't get stale
831 $d = strtotime($person["updated"]." +00:00");
832 if ($d < strtotime("now - 14 days")) {
836 if ($person["guid"] == "") {
841 if (!DBM::is_result($person) || $update) {
842 logger("create or refresh", LOGGER_DEBUG);
843 $r = Probe::uri($handle, NETWORK_DIASPORA);
845 // Note that Friendica contacts will return a "Diaspora person"
846 // if Diaspora connectivity is enabled on their server
847 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
848 self::addFContact($r, $update);
850 // Fetch the updated or added contact
851 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
852 if (!DBM::is_result($person)) {
862 * @brief Updates the fcontact table
864 * @param array $arr The fcontact data
865 * @param bool $update Update or insert?
867 * @return string The id of the fcontact entry
869 private static function addFContact($arr, $update = false)
873 "UPDATE `fcontact` SET
887 WHERE `url` = '%s' AND `network` = '%s'",
889 dbesc($arr["photo"]),
890 dbesc($arr["request"]),
892 dbesc(strtolower($arr["addr"])),
894 dbesc($arr["batch"]),
895 dbesc($arr["notify"]),
897 dbesc($arr["confirm"]),
898 dbesc($arr["alias"]),
899 dbesc($arr["pubkey"]),
900 dbesc(DateTimeFormat::utcNow()),
902 dbesc($arr["network"])
906 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
907 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
908 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
911 dbesc($arr["photo"]),
912 dbesc($arr["request"]),
916 dbesc($arr["batch"]),
917 dbesc($arr["notify"]),
919 dbesc($arr["confirm"]),
920 dbesc($arr["network"]),
921 dbesc($arr["alias"]),
922 dbesc($arr["pubkey"]),
923 dbesc(DateTimeFormat::utcNow())
931 * @brief get a handle (user@domain.tld) from a given contact id
933 * @param int $contact_id The id in the contact table
934 * @param int $pcontact_id The id in the contact table (Used for the public contact)
936 * @return string the handle
938 private static function handleFromContact($contact_id, $pcontact_id = 0)
942 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
944 if ($pcontact_id != 0) {
946 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
950 if (DBM::is_result($r)) {
951 return strtolower($r[0]["addr"]);
956 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
960 if (DBM::is_result($r)) {
963 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
965 if ($contact['addr'] != "") {
966 $handle = $contact['addr'];
968 $baseurl_start = strpos($contact['url'], '://') + 3;
969 // allows installations in a subdirectory--not sure how Diaspora will handle
970 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
971 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
972 $handle = $contact['nick'].'@'.$baseurl;
976 return strtolower($handle);
980 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
983 * @param mixed $fcontact_guid Hexadecimal string guid
985 * @return string the contact url or null
987 public static function urlFromContactGuid($fcontact_guid)
989 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
992 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
993 dbesc(NETWORK_DIASPORA),
994 dbesc($fcontact_guid)
997 if (DBM::is_result($r)) {
1005 * @brief Get a contact id for a given handle
1007 * @todo Move to Friendica\Model\Contact
1009 * @param int $uid The user id
1010 * @param string $handle The handle in the format user@domain.tld
1012 * @return int Contact id
1014 private static function contactByHandle($uid, $handle)
1016 // First do a direct search on the contact table
1018 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1023 if (DBM::is_result($r)) {
1027 * We haven't found it?
1028 * We use another function for it that will possibly create a contact entry.
1030 $cid = Contact::getIdForURL($handle, $uid);
1033 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1034 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1036 if (DBM::is_result($r)) {
1042 $handle_parts = explode("@", $handle);
1043 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1045 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1046 dbesc(NETWORK_DFRN),
1050 if (DBM::is_result($r)) {
1054 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1059 * @brief Check if posting is allowed for this contact
1061 * @param array $importer Array of the importer user
1062 * @param array $contact The contact that is checked
1063 * @param bool $is_comment Is the check for a comment?
1065 * @return bool is the contact allowed to post?
1067 private static function postAllow($importer, $contact, $is_comment = false)
1070 * Perhaps we were already sharing with this person. Now they're sharing with us.
1071 * That makes us friends.
1072 * Normally this should have handled by getting a request - but this could get lost
1074 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1075 // It is not removed by now. Possibly the code is needed?
1076 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1079 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1080 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1083 // $contact["rel"] = CONTACT_IS_FRIEND;
1084 // logger("defining user ".$contact["nick"]." as friend");
1087 // We don't seem to like that person
1088 if ($contact["blocked"] || $contact["readonly"]) {
1089 // Maybe blocked, don't accept.
1091 // We are following this person?
1092 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1093 // Yes, then it is fine.
1095 // Is it a post to a community?
1096 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1099 // Is the message a global user or a comment?
1100 } elseif (($importer["uid"] == 0) || $is_comment) {
1101 // Messages for the global users and comments are always accepted
1109 * @brief Fetches the contact id for a handle and checks if posting is allowed
1111 * @param array $importer Array of the importer user
1112 * @param string $handle The checked handle in the format user@domain.tld
1113 * @param bool $is_comment Is the check for a comment?
1115 * @return array The contact data
1117 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1119 $contact = self::contactByHandle($importer["uid"], $handle);
1121 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1122 // If a contact isn't found, we accept it anyway if it is a comment
1130 if (!self::postAllow($importer, $contact, $is_comment)) {
1131 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1138 * @brief Does the message already exists on the system?
1140 * @param int $uid The user id
1141 * @param string $guid The guid of the message
1143 * @return int|bool message id if the message already was stored into the system - or false.
1145 private static function messageExists($uid, $guid)
1148 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1153 if (DBM::is_result($r)) {
1154 logger("message ".$guid." already exists for user ".$uid);
1162 * @brief Checks for links to posts in a message
1164 * @param array $item The item array
1167 private static function fetchGuid($item)
1169 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1170 preg_replace_callback(
1172 function ($match) use ($item) {
1173 self::fetchGuidSub($match, $item);
1178 preg_replace_callback(
1179 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1180 function ($match) use ($item) {
1181 self::fetchGuidSub($match, $item);
1188 * @brief Checks for relative /people/* links in an item body to match local
1189 * contacts or prepends the remote host taken from the author link.
1191 * @param string $body The item body to replace links from
1192 * @param string $author_link The author link for missing local contact fallback
1194 * @return string the replaced string
1196 public static function replacePeopleGuid($body, $author_link)
1198 $return = preg_replace_callback(
1199 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1200 function ($match) use ($author_link) {
1202 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1203 // 1 => '0123456789abcdef'
1205 $handle = self::urlFromContactGuid($match[1]);
1208 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1210 // No local match, restoring absolute remote URL from author scheme and host
1211 $author_url = parse_url($author_link);
1212 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1224 * @brief sub function of "fetchGuid" which checks for links in messages
1226 * @param array $match array containing a link that has to be checked for a message link
1227 * @param array $item The item array
1230 private static function fetchGuidSub($match, $item)
1232 if (!self::storeByGuid($match[1], $item["author-link"])) {
1233 self::storeByGuid($match[1], $item["owner-link"]);
1238 * @brief Fetches an item with a given guid from a given server
1240 * @param string $guid the message guid
1241 * @param string $server The server address
1242 * @param int $uid The user id of the user
1244 * @return int the message id of the stored message or false
1246 private static function storeByGuid($guid, $server, $uid = 0)
1248 $serverparts = parse_url($server);
1249 $server = $serverparts["scheme"]."://".$serverparts["host"];
1251 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1253 $msg = self::message($guid, $server);
1259 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1261 // Now call the dispatcher
1262 return self::dispatchPublic($msg);
1266 * @brief Fetches a message from a server
1268 * @param string $guid message guid
1269 * @param string $server The url of the server
1270 * @param int $level Endless loop prevention
1273 * 'message' => The message XML
1274 * 'author' => The author handle
1275 * 'key' => The public key of the author
1277 private static function message($guid, $server, $level = 0)
1283 // This will work for new Diaspora servers and Friendica servers from 3.5
1284 $source_url = $server."/fetch/post/".urlencode($guid);
1286 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1288 $envelope = Network::fetchUrl($source_url);
1290 logger("Envelope was fetched.", LOGGER_DEBUG);
1291 $x = self::verifyMagicEnvelope($envelope);
1293 logger("Envelope could not be verified.", LOGGER_DEBUG);
1295 logger("Envelope was verified.", LOGGER_DEBUG);
1301 // This will work for older Diaspora and Friendica servers
1303 $source_url = $server."/p/".urlencode($guid).".xml";
1304 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1306 $x = Network::fetchUrl($source_url);
1312 $source_xml = XML::parseString($x);
1314 if (!is_object($source_xml)) {
1318 if ($source_xml->post->reshare) {
1319 // Reshare of a reshare - old Diaspora version
1320 logger("Message is a reshare", LOGGER_DEBUG);
1321 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1322 } elseif ($source_xml->getName() == "reshare") {
1323 // Reshare of a reshare - new Diaspora version
1324 logger("Message is a new reshare", LOGGER_DEBUG);
1325 return self::message($source_xml->root_guid, $server, ++$level);
1330 // Fetch the author - for the old and the new Diaspora version
1331 if ($source_xml->post->status_message->diaspora_handle) {
1332 $author = (string)$source_xml->post->status_message->diaspora_handle;
1333 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1334 $author = (string)$source_xml->author;
1337 // If this isn't a "status_message" then quit
1339 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1343 $msg = ["message" => $x, "author" => $author];
1345 $msg["key"] = self::key($msg["author"]);
1351 * @brief Fetches the item record of a given guid
1353 * @param int $uid The user id
1354 * @param string $guid message guid
1355 * @param string $author The handle of the item
1356 * @param array $contact The contact of the item owner
1358 * @return array the item record
1360 private static function parentItem($uid, $guid, $author, $contact)
1363 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1364 `author-name`, `author-link`, `author-avatar`,
1365 `owner-name`, `owner-link`, `owner-avatar`
1366 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1372 $result = self::storeByGuid($guid, $contact["url"], $uid);
1375 $person = self::personByHandle($author);
1376 $result = self::storeByGuid($guid, $person["url"], $uid);
1380 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1383 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1384 `author-name`, `author-link`, `author-avatar`,
1385 `owner-name`, `owner-link`, `owner-avatar`
1386 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1394 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1397 logger("parent item found: parent: ".$guid." - user: ".$uid);
1403 * @brief returns contact details
1405 * @param array $def_contact The default contact if the person isn't found
1406 * @param array $person The record of the person
1407 * @param int $uid The user id
1410 * 'cid' => contact id
1411 * 'network' => network type
1413 private static function authorContactByUrl($def_contact, $person, $uid)
1415 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1416 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1417 if (DBM::is_result($contact)) {
1418 $cid = $contact["id"];
1419 $network = $contact["network"];
1421 $cid = $def_contact["id"];
1422 $network = NETWORK_DIASPORA;
1425 return ["cid" => $cid, "network" => $network];
1429 * @brief Is the profile a hubzilla profile?
1431 * @param string $url The profile link
1433 * @return bool is it a hubzilla server?
1435 public static function isRedmatrix($url)
1437 return(strstr($url, "/channel/"));
1441 * @brief Generate a post link with a given handle and message guid
1443 * @param string $addr The user handle
1444 * @param string $guid message guid
1445 * @param string $parent_guid optional parent guid
1447 * @return string the post link
1449 private static function plink($addr, $guid, $parent_guid = '')
1451 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1454 if (!DBM::is_result($r)) {
1455 if ($parent_guid != '') {
1456 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1458 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1462 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1463 // So we try another way as well.
1464 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1465 if (DBM::is_result($s)) {
1466 $r[0]["network"] = $s[0]["network"];
1469 if ($r[0]["network"] == NETWORK_DFRN) {
1470 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1473 if (self::isRedmatrix($r[0]["url"])) {
1474 return $r[0]["url"]."/?f=&mid=".$guid;
1477 if ($parent_guid != '') {
1478 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1480 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1485 * @brief Receives account migration
1487 * @param array $importer Array of the importer user
1488 * @param object $data The message object
1490 * @return bool Success
1492 private static function receiveAccountMigration($importer, $data)
1494 $old_handle = notags(unxmlify($data->author));
1495 $new_handle = notags(unxmlify($data->profile->author));
1496 $signature = notags(unxmlify($data->signature));
1498 $contact = self::contactByHandle($importer["uid"], $old_handle);
1500 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1504 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1507 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1508 $key = self::key($old_handle);
1509 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1510 logger('No valid signature for migration.');
1514 // Update the profile
1515 self::receiveProfile($importer, $data->profile);
1517 // change the technical stuff in contact and gcontact
1518 $data = Probe::uri($new_handle);
1519 if ($data['network'] == NETWORK_PHANTOM) {
1520 logger('Account for '.$new_handle." couldn't be probed.");
1524 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1525 'name' => $data['name'], 'nick' => $data['nick'],
1526 'addr' => $data['addr'], 'batch' => $data['batch'],
1527 'notify' => $data['notify'], 'poll' => $data['poll'],
1528 'network' => $data['network']];
1530 dba::update('contact', $fields, ['addr' => $old_handle]);
1532 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1533 'name' => $data['name'], 'nick' => $data['nick'],
1534 'addr' => $data['addr'], 'connect' => $data['addr'],
1535 'notify' => $data['notify'], 'photo' => $data['photo'],
1536 'server_url' => $data['baseurl'], 'network' => $data['network']];
1538 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1540 logger('Contacts are updated.');
1543 /// @todo This is an extreme performance killer
1545 'owner-link' => [$contact["url"], $data["url"]],
1546 'author-link' => [$contact["url"], $data["url"]],
1548 foreach ($fields as $n => $f) {
1550 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1553 intval($importer["uid"])
1556 if (DBM::is_result($r)) {
1558 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1563 intval($importer["uid"])
1572 logger('Items are updated.');
1578 * @brief Processes an account deletion
1580 * @param array $importer Array of the importer user
1581 * @param object $data The message object
1583 * @return bool Success
1585 private static function receiveAccountDeletion($importer, $data)
1587 /// @todo Account deletion should remove the contact from the global contacts as well
1589 $author = notags(unxmlify($data->author));
1591 $contact = self::contactByHandle($importer["uid"], $author);
1593 logger("cannot find contact for author: ".$author);
1597 // We now remove the contact
1598 Contact::remove($contact["id"]);
1603 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1605 * @param string $author Author handle
1606 * @param string $guid Message guid
1607 * @param boolean $onlyfound Only return uri when found in the database
1609 * @return string The constructed uri or the one from our database
1611 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1613 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1614 if (DBM::is_result($r)) {
1615 return $r[0]["uri"];
1616 } elseif (!$onlyfound) {
1617 return $author.":".$guid;
1624 * @brief Fetch the guid from our database with a given uri
1626 * @param string $uri Message uri
1627 * @param string $uid Author handle
1629 * @return string The post guid
1631 private static function getGuidFromUri($uri, $uid)
1633 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1634 if (DBM::is_result($r)) {
1635 return $r[0]["guid"];
1642 * @brief Find the best importer for a comment, like, ...
1644 * @param string $guid The guid of the item
1646 * @return array|boolean the origin owner of that post - or false
1648 private static function importerForGuid($guid)
1650 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1652 if (DBM::is_result($item)) {
1653 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1654 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1655 if (DBM::is_result($contact)) {
1663 * @brief Processes an incoming comment
1665 * @param array $importer Array of the importer user
1666 * @param string $sender The sender of the message
1667 * @param object $data The message object
1668 * @param string $xml The original XML of the message
1670 * @return int The message id of the generated comment or "false" if there was an error
1672 private static function receiveComment($importer, $sender, $data, $xml)
1674 $author = notags(unxmlify($data->author));
1675 $guid = notags(unxmlify($data->guid));
1676 $parent_guid = notags(unxmlify($data->parent_guid));
1677 $text = unxmlify($data->text);
1679 if (isset($data->created_at)) {
1680 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1682 $created_at = DateTimeFormat::utcNow();
1685 if (isset($data->thread_parent_guid)) {
1686 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1687 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1692 $contact = self::allowedContactByHandle($importer, $sender, true);
1697 $message_id = self::messageExists($importer["uid"], $guid);
1702 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1703 if (!$parent_item) {
1707 $person = self::personByHandle($author);
1708 if (!is_array($person)) {
1709 logger("unable to find author details");
1713 // Fetch the contact id - if we know this contact
1714 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1718 $datarray["uid"] = $importer["uid"];
1719 $datarray["contact-id"] = $author_contact["cid"];
1720 $datarray["network"] = $author_contact["network"];
1722 $datarray["author-name"] = $person["name"];
1723 $datarray["author-link"] = $person["url"];
1724 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1726 $datarray["owner-name"] = $contact["name"];
1727 $datarray["owner-link"] = $contact["url"];
1728 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1730 $datarray["guid"] = $guid;
1731 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1733 $datarray["type"] = "remote-comment";
1734 $datarray["verb"] = ACTIVITY_POST;
1735 $datarray["gravity"] = GRAVITY_COMMENT;
1737 if ($thr_uri != "") {
1738 $datarray["parent-uri"] = $thr_uri;
1740 $datarray["parent-uri"] = $parent_item["uri"];
1743 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1745 $datarray["protocol"] = PROTOCOL_DIASPORA;
1746 $datarray["source"] = $xml;
1748 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1750 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1752 $body = Markdown::toBBCode($text);
1754 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1756 self::fetchGuid($datarray);
1758 $message_id = Item::insert($datarray);
1760 if ($message_id <= 0) {
1765 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1768 // If we are the origin of the parent we store the original data and notify our followers
1769 if ($message_id && $parent_item["origin"]) {
1770 // Formerly we stored the signed text, the signature and the author in different fields.
1771 // We now store the raw data so that we are more flexible.
1772 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1775 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1782 * @brief processes and stores private messages
1784 * @param array $importer Array of the importer user
1785 * @param array $contact The contact of the message
1786 * @param object $data The message object
1787 * @param array $msg Array of the processed message, author handle and key
1788 * @param object $mesg The private message
1789 * @param array $conversation The conversation record to which this message belongs
1791 * @return bool "true" if it was successful
1793 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1795 $author = notags(unxmlify($data->author));
1796 $guid = notags(unxmlify($data->guid));
1797 $subject = notags(unxmlify($data->subject));
1799 // "diaspora_handle" is the element name from the old version
1800 // "author" is the element name from the new version
1801 if ($mesg->author) {
1802 $msg_author = notags(unxmlify($mesg->author));
1803 } elseif ($mesg->diaspora_handle) {
1804 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1809 $msg_guid = notags(unxmlify($mesg->guid));
1810 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1811 $msg_text = unxmlify($mesg->text);
1812 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1814 if ($msg_conversation_guid != $guid) {
1815 logger("message conversation guid does not belong to the current conversation.");
1819 $body = Markdown::toBBCode($msg_text);
1820 $message_uri = $msg_author.":".$msg_guid;
1822 $person = self::personByHandle($msg_author);
1827 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1829 intval($importer["uid"])
1831 if (DBM::is_result($r)) {
1832 logger("duplicate message already delivered.", LOGGER_DEBUG);
1837 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1838 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1839 intval($importer["uid"]),
1841 intval($conversation["id"]),
1842 dbesc($person["name"]),
1843 dbesc($person["photo"]),
1844 dbesc($person["url"]),
1845 intval($contact["id"]),
1850 dbesc($message_uri),
1851 dbesc($author.":".$guid),
1852 dbesc($msg_created_at)
1857 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1861 "type" => NOTIFY_MAIL,
1862 "notify_flags" => $importer["notify-flags"],
1863 "language" => $importer["language"],
1864 "to_name" => $importer["username"],
1865 "to_email" => $importer["email"],
1866 "uid" =>$importer["uid"],
1867 "item" => ["subject" => $subject, "body" => $body],
1868 "source_name" => $person["name"],
1869 "source_link" => $person["url"],
1870 "source_photo" => $person["thumb"],
1871 "verb" => ACTIVITY_POST,
1878 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1880 * @param array $importer Array of the importer user
1881 * @param array $msg Array of the processed message, author handle and key
1882 * @param object $data The message object
1884 * @return bool Success
1886 private static function receiveConversation($importer, $msg, $data)
1888 $author = notags(unxmlify($data->author));
1889 $guid = notags(unxmlify($data->guid));
1890 $subject = notags(unxmlify($data->subject));
1891 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1892 $participants = notags(unxmlify($data->participants));
1894 $messages = $data->message;
1896 if (!count($messages)) {
1897 logger("empty conversation");
1901 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1906 $conversation = null;
1909 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1910 intval($importer["uid"]),
1914 $conversation = $c[0];
1917 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1918 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1919 intval($importer["uid"]),
1923 dbesc(DateTimeFormat::utcNow()),
1925 dbesc($participants)
1929 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1930 intval($importer["uid"]),
1936 $conversation = $c[0];
1939 if (!$conversation) {
1940 logger("unable to create conversation.");
1944 foreach ($messages as $mesg) {
1945 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1952 * @brief Creates the body for a "like" message
1954 * @param array $contact The contact that send us the "like"
1955 * @param array $parent_item The item array of the parent item
1956 * @param string $guid message guid
1958 * @return string the body
1960 private static function constructLikeBody($contact, $parent_item, $guid)
1962 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1964 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1965 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1966 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
1968 return sprintf($bodyverb, $ulink, $alink, $plink);
1972 * @brief Creates a XML object for a "like"
1974 * @param array $importer Array of the importer user
1975 * @param array $parent_item The item array of the parent item
1977 * @return string The XML
1979 private static function constructLikeObject($importer, $parent_item)
1981 $objtype = ACTIVITY_OBJ_NOTE;
1982 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1983 $parent_body = $parent_item["body"];
1985 $xmldata = ["object" => ["type" => $objtype,
1987 "id" => $parent_item["uri"],
1990 "content" => $parent_body]];
1992 return XML::fromArray($xmldata, $xml, true);
1996 * @brief Processes "like" messages
1998 * @param array $importer Array of the importer user
1999 * @param string $sender The sender of the message
2000 * @param object $data The message object
2002 * @return int The message id of the generated like or "false" if there was an error
2004 private static function receiveLike($importer, $sender, $data)
2006 $author = notags(unxmlify($data->author));
2007 $guid = notags(unxmlify($data->guid));
2008 $parent_guid = notags(unxmlify($data->parent_guid));
2009 $parent_type = notags(unxmlify($data->parent_type));
2010 $positive = notags(unxmlify($data->positive));
2012 // likes on comments aren't supported by Diaspora - only on posts
2013 // But maybe this will be supported in the future, so we will accept it.
2014 if (!in_array($parent_type, ["Post", "Comment"])) {
2018 $contact = self::allowedContactByHandle($importer, $sender, true);
2023 $message_id = self::messageExists($importer["uid"], $guid);
2028 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2029 if (!$parent_item) {
2033 $person = self::personByHandle($author);
2034 if (!is_array($person)) {
2035 logger("unable to find author details");
2039 // Fetch the contact id - if we know this contact
2040 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2042 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2043 // We would accept this anyhow.
2044 if ($positive == "true") {
2045 $verb = ACTIVITY_LIKE;
2047 $verb = ACTIVITY_DISLIKE;
2052 $datarray["protocol"] = PROTOCOL_DIASPORA;
2054 $datarray["uid"] = $importer["uid"];
2055 $datarray["contact-id"] = $author_contact["cid"];
2056 $datarray["network"] = $author_contact["network"];
2058 $datarray["author-name"] = $person["name"];
2059 $datarray["author-link"] = $person["url"];
2060 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2062 $datarray["owner-name"] = $contact["name"];
2063 $datarray["owner-link"] = $contact["url"];
2064 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2066 $datarray["guid"] = $guid;
2067 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2069 $datarray["type"] = "activity";
2070 $datarray["verb"] = $verb;
2071 $datarray["gravity"] = GRAVITY_LIKE;
2072 $datarray["parent-uri"] = $parent_item["uri"];
2074 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2075 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2077 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2079 $message_id = Item::insert($datarray);
2081 if ($message_id <= 0) {
2086 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2089 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2090 if ($parent_item["id"] != $parent_item["parent"]) {
2091 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2092 $origin = $toplevel["origin"];
2094 $origin = $parent_item["origin"];
2097 // If we are the origin of the parent we store the original data and notify our followers
2098 if ($message_id && $origin) {
2099 // Formerly we stored the signed text, the signature and the author in different fields.
2100 // We now store the raw data so that we are more flexible.
2101 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2104 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2111 * @brief Processes private messages
2113 * @param array $importer Array of the importer user
2114 * @param object $data The message object
2116 * @return bool Success?
2118 private static function receiveMessage($importer, $data)
2120 $author = notags(unxmlify($data->author));
2121 $guid = notags(unxmlify($data->guid));
2122 $conversation_guid = notags(unxmlify($data->conversation_guid));
2123 $text = unxmlify($data->text);
2124 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2126 $contact = self::allowedContactByHandle($importer, $author, true);
2131 $conversation = null;
2134 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2135 intval($importer["uid"]),
2136 dbesc($conversation_guid)
2139 $conversation = $c[0];
2141 logger("conversation not available.");
2145 $message_uri = $author.":".$guid;
2147 $person = self::personByHandle($author);
2149 logger("unable to find author details");
2153 $body = Markdown::toBBCode($text);
2155 $body = self::replacePeopleGuid($body, $person["url"]);
2160 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2162 intval($importer["uid"])
2164 if (DBM::is_result($r)) {
2165 logger("duplicate message already delivered.", LOGGER_DEBUG);
2170 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2171 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2172 intval($importer["uid"]),
2174 intval($conversation["id"]),
2175 dbesc($person["name"]),
2176 dbesc($person["photo"]),
2177 dbesc($person["url"]),
2178 intval($contact["id"]),
2179 dbesc($conversation["subject"]),
2183 dbesc($message_uri),
2184 dbesc($author.":".$conversation["guid"]),
2190 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2195 * @brief Processes participations - unsupported by now
2197 * @param array $importer Array of the importer user
2198 * @param object $data The message object
2200 * @return bool always true
2202 private static function receiveParticipation($importer, $data)
2204 $author = strtolower(notags(unxmlify($data->author)));
2205 $parent_guid = notags(unxmlify($data->parent_guid));
2207 $contact_id = Contact::getIdForURL($author);
2209 logger('Contact not found: '.$author);
2213 $person = self::personByHandle($author);
2214 if (!is_array($person)) {
2215 logger("Person not found: ".$author);
2219 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2220 if (!DBM::is_result($item)) {
2221 logger('Item not found, no origin or private: '.$parent_guid);
2225 $author_parts = explode('@', $author);
2226 if (isset($author_parts[1])) {
2227 $server = $author_parts[1];
2229 // Should never happen
2233 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2235 if (!dba::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2236 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2239 // Send all existing comments and likes to the requesting server
2240 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2242 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2243 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2244 while ($comment = dba::fetch($comments)) {
2245 if ($comment['verb'] == ACTIVITY_POST) {
2246 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2248 $cmd = $comment['self'] ? 'like' : 'comment-import';
2250 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2251 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2253 dba::close($comments);
2259 * @brief Processes photos - unneeded
2261 * @param array $importer Array of the importer user
2262 * @param object $data The message object
2264 * @return bool always true
2266 private static function receivePhoto($importer, $data)
2268 // There doesn't seem to be a reason for this function,
2269 // since the photo data is transmitted in the status message as well
2274 * @brief Processes poll participations - unssupported
2276 * @param array $importer Array of the importer user
2277 * @param object $data The message object
2279 * @return bool always true
2281 private static function receivePollParticipation($importer, $data)
2283 // We don't support polls by now
2288 * @brief Processes incoming profile updates
2290 * @param array $importer Array of the importer user
2291 * @param object $data The message object
2293 * @return bool Success
2295 private static function receiveProfile($importer, $data)
2297 $author = strtolower(notags(unxmlify($data->author)));
2299 $contact = self::contactByHandle($importer["uid"], $author);
2304 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2305 $image_url = unxmlify($data->image_url);
2306 $birthday = unxmlify($data->birthday);
2307 $gender = unxmlify($data->gender);
2308 $about = Markdown::toBBCode(unxmlify($data->bio));
2309 $location = Markdown::toBBCode(unxmlify($data->location));
2310 $searchable = (unxmlify($data->searchable) == "true");
2311 $nsfw = (unxmlify($data->nsfw) == "true");
2312 $tags = unxmlify($data->tag_string);
2314 $tags = explode("#", $tags);
2317 foreach ($tags as $tag) {
2318 $tag = trim(strtolower($tag));
2324 $keywords = implode(", ", $keywords);
2326 $handle_parts = explode("@", $author);
2327 $nick = $handle_parts[0];
2330 $name = $handle_parts[0];
2333 if (preg_match("|^https?://|", $image_url) === 0) {
2334 $image_url = "http://".$handle_parts[1].$image_url;
2337 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2339 // Generic birthday. We don't know the timezone. The year is irrelevant.
2341 $birthday = str_replace("1000", "1901", $birthday);
2343 if ($birthday != "") {
2344 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2347 // this is to prevent multiple birthday notifications in a single year
2348 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2350 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2351 $birthday = $contact["bd"];
2355 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2356 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2360 dbesc(DateTimeFormat::utcNow()),
2366 intval($contact["id"]),
2367 intval($importer["uid"])
2370 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2371 "photo" => $image_url, "name" => $name, "location" => $location,
2372 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2373 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2374 "hide" => !$searchable, "nsfw" => $nsfw];
2376 $gcid = GContact::update($gcontact);
2378 GContact::link($gcid, $importer["uid"], $contact["id"]);
2380 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2386 * @brief Processes incoming friend requests
2388 * @param array $importer Array of the importer user
2389 * @param array $contact The contact that send the request
2392 private static function receiveRequestMakeFriend($importer, $contact)
2396 if ($contact["rel"] == CONTACT_IS_SHARING) {
2399 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2400 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2403 // send notification
2406 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2407 intval($importer["uid"])
2410 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2412 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2413 intval($importer["uid"])
2416 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2418 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2420 $arr["protocol"] = PROTOCOL_DIASPORA;
2421 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2422 $arr["uid"] = $importer["uid"];
2423 $arr["contact-id"] = $self[0]["id"];
2425 $arr["type"] = 'wall';
2426 $arr["gravity"] = 0;
2428 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2429 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2430 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2431 $arr["verb"] = ACTIVITY_FRIEND;
2432 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2434 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2435 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2436 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2437 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2439 $arr["object"] = self::constructNewFriendObject($contact);
2441 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2443 $arr["allow_cid"] = $user["allow_cid"];
2444 $arr["allow_gid"] = $user["allow_gid"];
2445 $arr["deny_cid"] = $user["deny_cid"];
2446 $arr["deny_gid"] = $user["deny_gid"];
2448 $i = Item::insert($arr);
2450 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2457 * @brief Creates a XML object for a "new friend" message
2459 * @param array $contact Array of the contact
2461 * @return string The XML
2463 private static function constructNewFriendObject($contact)
2465 $objtype = ACTIVITY_OBJ_PERSON;
2466 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2467 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2469 $xmldata = ["object" => ["type" => $objtype,
2470 "title" => $contact["name"],
2471 "id" => $contact["url"]."/".$contact["name"],
2474 return XML::fromArray($xmldata, $xml, true);
2478 * @brief Processes incoming sharing notification
2480 * @param array $importer Array of the importer user
2481 * @param object $data The message object
2483 * @return bool Success
2485 private static function receiveContactRequest($importer, $data)
2487 $author = unxmlify($data->author);
2488 $recipient = unxmlify($data->recipient);
2490 if (!$author || !$recipient) {
2494 // the current protocol version doesn't know these fields
2495 // That means that we will assume their existance
2496 if (isset($data->following)) {
2497 $following = (unxmlify($data->following) == "true");
2502 if (isset($data->sharing)) {
2503 $sharing = (unxmlify($data->sharing) == "true");
2508 $contact = self::contactByHandle($importer["uid"], $author);
2510 // perhaps we were already sharing with this person. Now they're sharing with us.
2511 // That makes us friends.
2514 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2515 self::receiveRequestMakeFriend($importer, $contact);
2517 // refetch the contact array
2518 $contact = self::contactByHandle($importer["uid"], $author);
2520 // If we are now friends, we are sending a share message.
2521 // Normally we needn't to do so, but the first message could have been vanished.
2522 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2523 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2525 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2526 $ret = self::sendShare($u[0], $contact);
2531 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2532 Contact::removeFollower($importer, $contact);
2537 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2538 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2540 } elseif (!$following && !$sharing) {
2541 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2543 } elseif (!$following && $sharing) {
2544 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2545 } elseif ($following && $sharing) {
2546 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2547 } elseif ($following && !$sharing) {
2548 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2551 $ret = self::personByHandle($author);
2553 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2554 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2558 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2561 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2562 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2563 intval($importer["uid"]),
2564 dbesc($ret["network"]),
2565 dbesc($ret["addr"]),
2566 DateTimeFormat::utcNow(),
2568 dbesc(normalise_link($ret["url"])),
2570 dbesc($ret["name"]),
2571 dbesc($ret["nick"]),
2572 dbesc($ret["photo"]),
2573 dbesc($ret["pubkey"]),
2574 dbesc($ret["notify"]),
2575 dbesc($ret["poll"]),
2580 // find the contact record we just created
2582 $contact_record = self::contactByHandle($importer["uid"], $author);
2584 if (!$contact_record) {
2585 logger("unable to locate newly created contact record.");
2589 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2591 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2593 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2595 if ($importer["page-flags"] == PAGE_NORMAL) {
2596 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2598 $hash = random_string().(string)time(); // Generate a confirm_key
2601 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2602 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2603 intval($importer["uid"]),
2604 intval($contact_record["id"]),
2607 dbesc(L10n::t("Sharing notification from Diaspora network")),
2609 dbesc(DateTimeFormat::utcNow())
2612 // automatic friend approval
2614 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2616 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2618 // technically they are sharing with us (CONTACT_IS_SHARING),
2619 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2620 // we are going to change the relationship and make them a follower.
2622 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2623 $new_relation = CONTACT_IS_FRIEND;
2624 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2625 $new_relation = CONTACT_IS_SHARING;
2627 $new_relation = CONTACT_IS_FOLLOWER;
2631 "UPDATE `contact` SET `rel` = %d,
2639 intval($new_relation),
2640 dbesc(DateTimeFormat::utcNow()),
2641 dbesc(DateTimeFormat::utcNow()),
2642 intval($contact_record["id"])
2645 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2647 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2648 $ret = self::sendShare($u[0], $contact_record);
2650 // Send the profile data, maybe it weren't transmitted before
2651 self::sendProfile($importer["uid"], [$contact_record]);
2659 * @brief Fetches a message with a given guid
2661 * @param string $guid message guid
2662 * @param string $orig_author handle of the original post
2663 * @param string $author handle of the sharer
2665 * @return array The fetched item
2667 private static function originalItem($guid, $orig_author, $author)
2669 // Do we already have this item?
2671 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2672 `author-name`, `author-link`, `author-avatar`
2673 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2677 if (DBM::is_result($r)) {
2678 logger("reshared message ".$guid." already exists on system.");
2680 // Maybe it is already a reshared item?
2681 // Then refetch the content, if it is a reshare from a reshare.
2682 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2683 if (self::isReshare($r[0]["body"], true)) {
2685 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2686 $r[0]["body"] = Markdown::toBBCode(BBCode::toMarkdown($r[0]["body"]));
2688 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2690 // Add OEmbed and other information to the body
2691 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2699 if (!DBM::is_result($r)) {
2700 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2701 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2702 $item_id = self::storeByGuid($guid, $server);
2705 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2706 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2707 $item_id = self::storeByGuid($guid, $server);
2712 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2713 `author-name`, `author-link`, `author-avatar`
2714 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2718 if (DBM::is_result($r)) {
2719 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2720 if (self::isReshare($r[0]["body"], false)) {
2721 $r[0]["body"] = Markdown::toBBCode(BBCode::toMarkdown($r[0]["body"]));
2722 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2733 * @brief Processes a reshare message
2735 * @param array $importer Array of the importer user
2736 * @param object $data The message object
2737 * @param string $xml The original XML of the message
2739 * @return int the message id
2741 private static function receiveReshare($importer, $data, $xml)
2743 $author = notags(unxmlify($data->author));
2744 $guid = notags(unxmlify($data->guid));
2745 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2746 $root_author = notags(unxmlify($data->root_author));
2747 $root_guid = notags(unxmlify($data->root_guid));
2748 /// @todo handle unprocessed property "provider_display_name"
2749 $public = notags(unxmlify($data->public));
2751 $contact = self::allowedContactByHandle($importer, $author, false);
2756 $message_id = self::messageExists($importer["uid"], $guid);
2761 $original_item = self::originalItem($root_guid, $root_author, $author);
2762 if (!$original_item) {
2766 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2770 $datarray["uid"] = $importer["uid"];
2771 $datarray["contact-id"] = $contact["id"];
2772 $datarray["network"] = NETWORK_DIASPORA;
2774 $datarray["author-name"] = $contact["name"];
2775 $datarray["author-link"] = $contact["url"];
2776 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2778 $datarray["owner-name"] = $datarray["author-name"];
2779 $datarray["owner-link"] = $datarray["author-link"];
2780 $datarray["owner-avatar"] = $datarray["author-avatar"];
2782 $datarray["guid"] = $guid;
2783 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2785 $datarray["verb"] = ACTIVITY_POST;
2786 $datarray["gravity"] = GRAVITY_PARENT;
2788 $datarray["protocol"] = PROTOCOL_DIASPORA;
2789 $datarray["source"] = $xml;
2791 $prefix = share_header(
2792 $original_item["author-name"],
2793 $original_item["author-link"],
2794 $original_item["author-avatar"],
2795 $original_item["guid"],
2796 $original_item["created"],
2799 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2801 $datarray["tag"] = $original_item["tag"];
2802 $datarray["app"] = $original_item["app"];
2804 $datarray["plink"] = self::plink($author, $guid);
2805 $datarray["private"] = (($public == "false") ? 1 : 0);
2806 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2808 $datarray["object-type"] = $original_item["object-type"];
2810 self::fetchGuid($datarray);
2811 $message_id = Item::insert($datarray);
2813 self::sendParticipation($contact, $datarray);
2816 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2824 * @brief Processes retractions
2826 * @param array $importer Array of the importer user
2827 * @param array $contact The contact of the item owner
2828 * @param object $data The message object
2830 * @return bool success
2832 private static function itemRetraction($importer, $contact, $data)
2834 $author = notags(unxmlify($data->author));
2835 $target_guid = notags(unxmlify($data->target_guid));
2836 $target_type = notags(unxmlify($data->target_type));
2838 $person = self::personByHandle($author);
2839 if (!is_array($person)) {
2840 logger("unable to find author detail for ".$author);
2844 if (empty($contact["url"])) {
2845 $contact["url"] = $person["url"];
2848 // Fetch items that are about to be deleted
2849 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2851 // When we receive a public retraction, we delete every item that we find.
2852 if ($importer['uid'] == 0) {
2853 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2855 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2857 $r = dba::select('item', $fields, $condition);
2858 if (!DBM::is_result($r)) {
2859 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2863 while ($item = dba::fetch($r)) {
2864 // Fetch the parent item
2865 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2867 // Only delete it if the parent author really fits
2868 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2869 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2873 Item::deleteById($item["id"]);
2875 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2877 // Now check if the retraction needs to be relayed by us
2878 if ($parent["origin"]) {
2880 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2888 * @brief Receives retraction messages
2890 * @param array $importer Array of the importer user
2891 * @param string $sender The sender of the message
2892 * @param object $data The message object
2894 * @return bool Success
2896 private static function receiveRetraction($importer, $sender, $data)
2898 $target_type = notags(unxmlify($data->target_type));
2900 $contact = self::contactByHandle($importer["uid"], $sender);
2901 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2902 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2906 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2908 switch ($target_type) {
2913 case "StatusMessage":
2914 return self::itemRetraction($importer, $contact, $data);
2918 /// @todo What should we do with an "unshare"?
2919 // Removing the contact isn't correct since we still can read the public items
2920 Contact::remove($contact["id"]);
2924 logger("Unknown target type ".$target_type);
2931 * @brief Receives status messages
2933 * @param array $importer Array of the importer user
2934 * @param object $data The message object
2935 * @param string $xml The original XML of the message
2937 * @return int The message id of the newly created item
2939 private static function receiveStatusMessage($importer, $data, $xml)
2941 $author = notags(unxmlify($data->author));
2942 $guid = notags(unxmlify($data->guid));
2943 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2944 $public = notags(unxmlify($data->public));
2945 $text = unxmlify($data->text);
2946 $provider_display_name = notags(unxmlify($data->provider_display_name));
2948 $contact = self::allowedContactByHandle($importer, $author, false);
2953 $message_id = self::messageExists($importer["uid"], $guid);
2959 if ($data->location) {
2960 foreach ($data->location->children() as $fieldname => $data) {
2961 $address[$fieldname] = notags(unxmlify($data));
2965 $body = Markdown::toBBCode($text);
2969 // Attach embedded pictures to the body
2971 foreach ($data->photo as $photo) {
2972 $body = "[img]".unxmlify($photo->remote_photo_path).
2973 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2976 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2978 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2980 // Add OEmbed and other information to the body
2981 if (!self::isRedmatrix($contact["url"])) {
2982 $body = add_page_info_to_body($body, false, true);
2986 /// @todo enable support for polls
2987 //if ($data->poll) {
2988 // foreach ($data->poll AS $poll)
2993 /// @todo enable support for events
2995 $datarray["uid"] = $importer["uid"];
2996 $datarray["contact-id"] = $contact["id"];
2997 $datarray["network"] = NETWORK_DIASPORA;
2999 $datarray["author-name"] = $contact["name"];
3000 $datarray["author-link"] = $contact["url"];
3001 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
3003 $datarray["owner-name"] = $datarray["author-name"];
3004 $datarray["owner-link"] = $datarray["author-link"];
3005 $datarray["owner-avatar"] = $datarray["author-avatar"];
3007 $datarray["guid"] = $guid;
3008 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3010 $datarray["verb"] = ACTIVITY_POST;
3011 $datarray["gravity"] = GRAVITY_PARENT;
3013 $datarray["protocol"] = PROTOCOL_DIASPORA;
3014 $datarray["source"] = $xml;
3016 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3018 if ($provider_display_name != "") {
3019 $datarray["app"] = $provider_display_name;
3022 $datarray["plink"] = self::plink($author, $guid);
3023 $datarray["private"] = (($public == "false") ? 1 : 0);
3024 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3026 if (isset($address["address"])) {
3027 $datarray["location"] = $address["address"];
3030 if (isset($address["lat"]) && isset($address["lng"])) {
3031 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3034 self::fetchGuid($datarray);
3035 $message_id = Item::insert($datarray);
3037 self::sendParticipation($contact, $datarray);
3040 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3047 /* ************************************************************************************** *
3048 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3049 * ************************************************************************************** */
3052 * @brief returnes the handle of a contact
3054 * @param array $contact contact array
3056 * @return string the handle in the format user@domain.tld
3058 private static function myHandle($contact)
3060 if ($contact["addr"] != "") {
3061 return $contact["addr"];
3064 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3065 // So - just in case - we build the the address here.
3066 if ($contact["nickname"] != "") {
3067 $nick = $contact["nickname"];
3069 $nick = $contact["nick"];
3072 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3077 * @brief Creates the data for a private message in the new format
3079 * @param string $msg The message that is to be transmitted
3080 * @param array $user The record of the sender
3081 * @param array $contact Target of the communication
3082 * @param string $prvkey The private key of the sender
3083 * @param string $pubkey The public key of the receiver
3085 * @return string The encrypted data
3087 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3089 logger("Message: ".$msg, LOGGER_DATA);
3091 // without a public key nothing will work
3093 logger("pubkey missing: contact id: ".$contact["id"]);
3097 $aes_key = openssl_random_pseudo_bytes(32);
3098 $b_aes_key = base64_encode($aes_key);
3099 $iv = openssl_random_pseudo_bytes(16);
3100 $b_iv = base64_encode($iv);
3102 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3104 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3106 $encrypted_key_bundle = "";
3107 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3109 $json_object = json_encode(
3110 ["aes_key" => base64_encode($encrypted_key_bundle),
3111 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3114 return $json_object;
3118 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3120 * @param string $msg The message that is to be transmitted
3121 * @param array $user The record of the sender
3123 * @return string The envelope
3125 public static function buildMagicEnvelope($msg, $user)
3127 $b64url_data = base64url_encode($msg);
3128 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3130 $key_id = base64url_encode(self::myHandle($user));
3131 $type = "application/xml";
3132 $encoding = "base64url";
3133 $alg = "RSA-SHA256";
3134 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3136 // Fallback if the private key wasn't transmitted in the expected field
3137 if ($user['uprvkey'] == "") {
3138 $user['uprvkey'] = $user['prvkey'];
3141 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3142 $sig = base64url_encode($signature);
3144 $xmldata = ["me:env" => ["me:data" => $data,
3145 "@attributes" => ["type" => $type],
3146 "me:encoding" => $encoding,
3149 "@attributes2" => ["key_id" => $key_id]]];
3151 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3153 return XML::fromArray($xmldata, $xml, false, $namespaces);
3157 * @brief Create the envelope for a message
3159 * @param string $msg The message that is to be transmitted
3160 * @param array $user The record of the sender
3161 * @param array $contact Target of the communication
3162 * @param string $prvkey The private key of the sender
3163 * @param string $pubkey The public key of the receiver
3164 * @param bool $public Is the message public?
3166 * @return string The message that will be transmitted to other servers
3168 private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3170 // The message is put into an envelope with the sender's signature
3171 $envelope = self::buildMagicEnvelope($msg, $user);
3173 // Private messages are put into a second envelope, encrypted with the receivers public key
3175 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3182 * @brief Creates a signature for a message
3184 * @param array $owner the array of the owner of the message
3185 * @param array $message The message that is to be signed
3187 * @return string The signature
3189 private static function signature($owner, $message)
3192 unset($sigmsg["author_signature"]);
3193 unset($sigmsg["parent_author_signature"]);
3195 $signed_text = implode(";", $sigmsg);
3197 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3201 * @brief Transmit a message to a target server
3203 * @param array $owner the array of the item owner
3204 * @param array $contact Target of the communication
3205 * @param string $envelope The message that is to be transmitted
3206 * @param bool $public_batch Is it a public post?
3207 * @param bool $queue_run Is the transmission called from the queue?
3208 * @param string $guid message guid
3210 * @return int Result of the transmission
3212 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3216 $enabled = intval(Config::get("system", "diaspora_enabled"));
3221 $logid = random_string(4);
3223 // We always try to use the data from the fcontact table.
3224 // This is important for transmitting data to Friendica servers.
3225 if (!empty($contact['addr'])) {
3226 $fcontact = self::personByHandle($contact['addr']);
3227 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3229 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3233 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3237 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3239 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3242 if (!intval(Config::get("system", "diaspora_test"))) {
3243 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3245 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3246 $return_code = $a->get_curl_code();
3248 logger("test_mode");
3253 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3255 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3257 logger("queue message");
3258 // queue message for redelivery
3259 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3262 // The message could not be delivered. We mark the contact as "dead"
3263 Contact::markForArchival($contact);
3264 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3265 // We successfully delivered a message, the contact is alive
3266 Contact::unmarkForArchival($contact);
3269 return $return_code ? $return_code : -1;
3274 * @brief Build the post xml
3276 * @param string $type The message type
3277 * @param array $message The message data
3279 * @return string The post XML
3281 public static function buildPostXml($type, $message)
3283 $data = [$type => $message];
3285 return XML::fromArray($data, $xml);
3289 * @brief Builds and transmit messages
3291 * @param array $owner the array of the item owner
3292 * @param array $contact Target of the communication
3293 * @param string $type The message type
3294 * @param array $message The message data
3295 * @param bool $public_batch Is it a public post?
3296 * @param string $guid message guid
3297 * @param bool $spool Should the transmission be spooled or transmitted?
3299 * @return int Result of the transmission
3301 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3303 $msg = self::buildPostXml($type, $message);
3305 logger('message: '.$msg, LOGGER_DATA);
3306 logger('send guid '.$guid, LOGGER_DEBUG);
3308 // Fallback if the private key wasn't transmitted in the expected field
3309 if ($owner['uprvkey'] == "") {
3310 $owner['uprvkey'] = $owner['prvkey'];
3313 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3316 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3319 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3322 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3324 return $return_code;
3328 * @brief sends a participation (Used to get all further updates)
3330 * @param array $contact Target of the communication
3331 * @param array $item Item array
3333 * @return int The result of the transmission
3335 private static function sendParticipation($contact, $item)
3337 // Don't send notifications for private postings
3338 if ($item['private']) {
3342 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3344 $result = Cache::get($cachekey);
3345 if (!is_null($result)) {
3349 // Fetch some user id to have a valid handle to transmit the participation.
3350 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3351 // If the item belongs to a user, we take this user id.
3352 if ($item['uid'] == 0) {
3353 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3354 $first_user = dba::selectFirst('user', ['uid'], $condition);
3355 $owner = User::getOwnerDataById($first_user['uid']);
3357 $owner = User::getOwnerDataById($item['uid']);
3360 $author = self::myHandle($owner);
3362 $message = ["author" => $author,
3363 "guid" => get_guid(32),
3364 "parent_type" => "Post",
3365 "parent_guid" => $item["guid"]];
3367 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3369 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3370 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3372 return self::buildAndTransmit($owner, $contact, "participation", $message);
3376 * @brief sends an account migration
3378 * @param array $owner the array of the item owner
3379 * @param array $contact Target of the communication
3380 * @param int $uid User ID
3382 * @return int The result of the transmission
3384 public static function sendAccountMigration($owner, $contact, $uid)
3386 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3387 $profile = self::createProfileData($uid);
3389 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3390 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3392 $message = ["author" => $old_handle,
3393 "profile" => $profile,
3394 "signature" => $signature];
3396 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3398 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3402 * @brief Sends a "share" message
3404 * @param array $owner the array of the item owner
3405 * @param array $contact Target of the communication
3407 * @return int The result of the transmission
3409 public static function sendShare($owner, $contact)
3412 * @todo support the different possible combinations of "following" and "sharing"
3413 * Currently, Diaspora only interprets the "sharing" field
3415 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3419 switch ($contact["rel"]) {
3420 case CONTACT_IS_FRIEND:
3423 case CONTACT_IS_SHARING:
3426 case CONTACT_IS_FOLLOWER:
3432 $message = ["author" => self::myHandle($owner),
3433 "recipient" => $contact["addr"],
3434 "following" => "true",
3435 "sharing" => "true"];
3437 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3439 return self::buildAndTransmit($owner, $contact, "contact", $message);
3443 * @brief sends an "unshare"
3445 * @param array $owner the array of the item owner
3446 * @param array $contact Target of the communication
3448 * @return int The result of the transmission
3450 public static function sendUnshare($owner, $contact)
3452 $message = ["author" => self::myHandle($owner),
3453 "recipient" => $contact["addr"],
3454 "following" => "false",
3455 "sharing" => "false"];
3457 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3459 return self::buildAndTransmit($owner, $contact, "contact", $message);
3463 * @brief Checks a message body if it is a reshare
3465 * @param string $body The message body that is to be check
3466 * @param bool $complete Should it be a complete check or a simple check?
3468 * @return array|bool Reshare details or "false" if no reshare
3470 public static function isReshare($body, $complete = true)
3472 $body = trim($body);
3474 // Skip if it isn't a pure repeated messages
3475 // Does it start with a share?
3476 if ((strpos($body, "[share") > 0) && $complete) {
3480 // Does it end with a share?
3481 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3485 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3486 // Skip if there is no shared message in there
3487 if ($body == $attributes) {
3491 // If we don't do the complete check we quit here
3497 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3498 if ($matches[1] != "") {
3499 $guid = $matches[1];
3502 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3503 if ($matches[1] != "") {
3504 $guid = $matches[1];
3509 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3516 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3517 $ret["root_guid"] = $guid;
3523 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3524 if ($matches[1] != "") {
3525 $profile = $matches[1];
3528 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3529 if ($matches[1] != "") {
3530 $profile = $matches[1];
3535 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3536 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3541 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3542 if ($matches[1] != "") {
3543 $link = $matches[1];
3546 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3547 if ($matches[1] != "") {
3548 $link = $matches[1];
3551 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3552 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3560 * @brief Create an event array
3562 * @param integer $event_id The id of the event
3564 * @return array with event data
3566 private static function buildEvent($event_id)
3568 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3569 if (!DBM::is_result($r)) {
3577 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3578 if (!DBM::is_result($r)) {
3584 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3585 if (!DBM::is_result($r)) {
3591 $eventdata['author'] = self::myHandle($owner);
3593 if ($event['guid']) {
3594 $eventdata['guid'] = $event['guid'];
3597 $mask = DateTimeFormat::ATOM;
3599 /// @todo - establish "all day" events in Friendica
3600 $eventdata["all_day"] = "false";
3602 if (!$event['adjust']) {
3603 $eventdata['timezone'] = $user['timezone'];
3605 if ($eventdata['timezone'] == "") {
3606 $eventdata['timezone'] = 'UTC';
3610 if ($event['start']) {
3611 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3613 if ($event['finish'] && !$event['nofinish']) {
3614 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3616 if ($event['summary']) {
3617 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3619 if ($event['desc']) {
3620 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3622 if ($event['location']) {
3623 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3624 $coord = Map::getCoordinates($event['location']);
3627 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3628 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3629 $location["lat"] = $coord['lat'];
3630 $location["lng"] = $coord['lon'];
3632 $location["lat"] = 0;
3633 $location["lng"] = 0;
3635 $eventdata['location'] = $location;
3642 * @brief Create a post (status message or reshare)
3644 * @param array $item The item that will be exported
3645 * @param array $owner the array of the item owner
3648 * 'type' -> Message type ("status_message" or "reshare")
3649 * 'message' -> Array of XML elements of the status
3651 public static function buildStatus($item, $owner)
3653 $cachekey = "diaspora:buildStatus:".$item['guid'];
3655 $result = Cache::get($cachekey);
3656 if (!is_null($result)) {
3660 $myaddr = self::myHandle($owner);
3662 $public = (($item["private"]) ? "false" : "true");
3664 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3666 // Detect a share element and do a reshare
3667 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3668 $message = ["author" => $myaddr,
3669 "guid" => $item["guid"],
3670 "created_at" => $created,
3671 "root_author" => $ret["root_handle"],
3672 "root_guid" => $ret["root_guid"],
3673 "provider_display_name" => $item["app"],
3674 "public" => $public];
3678 $title = $item["title"];
3679 $body = $item["body"];
3681 // convert to markdown
3682 $body = html_entity_decode(BBCode::toMarkdown($body));
3685 if (strlen($title)) {
3686 $body = "## ".html_entity_decode($title)."\n\n".$body;
3689 if ($item["attach"]) {
3690 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3692 $body .= "\n".L10n::t("Attachments:")."\n";
3693 foreach ($matches as $mtch) {
3694 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3701 if ($item["location"] != "")
3702 $location["address"] = $item["location"];
3704 if ($item["coord"] != "") {
3705 $coord = explode(" ", $item["coord"]);
3706 $location["lat"] = $coord[0];
3707 $location["lng"] = $coord[1];
3710 $message = ["author" => $myaddr,
3711 "guid" => $item["guid"],
3712 "created_at" => $created,
3713 "public" => $public,
3715 "provider_display_name" => $item["app"],
3716 "location" => $location];
3718 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3719 if (!isset($location["lat"]) || !isset($location["lng"])) {
3720 unset($message["location"]);
3723 if ($item['event-id'] > 0) {
3724 $event = self::buildEvent($item['event-id']);
3725 if (count($event)) {
3726 $message['event'] = $event;
3728 if (!empty($event['location']['address']) &&
3729 !empty($event['location']['lat']) &&
3730 !empty($event['location']['lng'])) {
3731 $message['location'] = $event['location'];
3734 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3735 // $message['text'] = '';
3739 $type = "status_message";
3742 $msg = ["type" => $type, "message" => $message];
3744 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3750 * @brief Sends a post
3752 * @param array $item The item that will be exported
3753 * @param array $owner the array of the item owner
3754 * @param array $contact Target of the communication
3755 * @param bool $public_batch Is it a public post?
3757 * @return int The result of the transmission
3759 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3761 $status = self::buildStatus($item, $owner);
3763 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3767 * @brief Creates a "like" object
3769 * @param array $item The item that will be exported
3770 * @param array $owner the array of the item owner
3772 * @return array The data for a "like"
3774 private static function constructLike($item, $owner)
3777 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3778 dbesc($item["thr-parent"])
3780 if (!DBM::is_result($p)) {
3786 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3788 if ($item['verb'] === ACTIVITY_LIKE) {
3790 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3791 $positive = "false";
3794 return(["author" => self::myHandle($owner),
3795 "guid" => $item["guid"],
3796 "parent_guid" => $parent["guid"],
3797 "parent_type" => $target_type,
3798 "positive" => $positive,
3799 "author_signature" => ""]);
3803 * @brief Creates an "EventParticipation" object
3805 * @param array $item The item that will be exported
3806 * @param array $owner the array of the item owner
3808 * @return array The data for an "EventParticipation"
3810 private static function constructAttend($item, $owner)
3813 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3814 dbesc($item["thr-parent"])
3816 if (!DBM::is_result($p)) {
3822 switch ($item['verb']) {
3823 case ACTIVITY_ATTEND:
3824 $attend_answer = 'accepted';
3826 case ACTIVITY_ATTENDNO:
3827 $attend_answer = 'declined';
3829 case ACTIVITY_ATTENDMAYBE:
3830 $attend_answer = 'tentative';
3833 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3837 return(["author" => self::myHandle($owner),
3838 "guid" => $item["guid"],
3839 "parent_guid" => $parent["guid"],
3840 "status" => $attend_answer,
3841 "author_signature" => ""]);
3845 * @brief Creates the object for a comment
3847 * @param array $item The item that will be exported
3848 * @param array $owner the array of the item owner
3850 * @return array The data for a comment
3852 private static function constructComment($item, $owner)
3854 $cachekey = "diaspora:constructComment:".$item['guid'];
3856 $result = Cache::get($cachekey);
3857 if (!is_null($result)) {
3862 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3863 intval($item["parent"]),
3864 intval($item["parent"])
3867 if (!DBM::is_result($p)) {
3873 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3874 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3876 $comment = ["author" => self::myHandle($owner),
3877 "guid" => $item["guid"],
3878 "created_at" => $created,
3879 "parent_guid" => $parent["guid"],
3881 "author_signature" => ""];
3883 // Send the thread parent guid only if it is a threaded comment
3884 if ($item['thr-parent'] != $item['parent-uri']) {
3885 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3888 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3894 * @brief Send a like or a comment
3896 * @param array $item The item that will be exported
3897 * @param array $owner the array of the item owner
3898 * @param array $contact Target of the communication
3899 * @param bool $public_batch Is it a public post?
3901 * @return int The result of the transmission
3903 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3905 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3906 $message = self::constructAttend($item, $owner);
3907 $type = "event_participation";
3908 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3909 $message = self::constructLike($item, $owner);
3912 $message = self::constructComment($item, $owner);
3920 $message["author_signature"] = self::signature($owner, $message);
3922 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3926 * @brief Creates a message from a signature record entry
3928 * @param array $item The item that will be exported
3929 * @param array $signature The entry of the "sign" record
3931 * @return string The message
3933 private static function messageFromSignature($item, $signature)
3935 // Split the signed text
3936 $signed_parts = explode(";", $signature['signed_text']);
3938 if ($item["deleted"]) {
3939 $message = ["author" => $signature['signer'],
3940 "target_guid" => $signed_parts[0],
3941 "target_type" => $signed_parts[1]];
3942 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3943 $message = ["author" => $signed_parts[4],
3944 "guid" => $signed_parts[1],
3945 "parent_guid" => $signed_parts[3],
3946 "parent_type" => $signed_parts[2],
3947 "positive" => $signed_parts[0],
3948 "author_signature" => $signature['signature'],
3949 "parent_author_signature" => ""];
3951 // Remove the comment guid
3952 $guid = array_shift($signed_parts);
3954 // Remove the parent guid
3955 $parent_guid = array_shift($signed_parts);
3957 // Remove the handle
3958 $handle = array_pop($signed_parts);
3960 // Glue the parts together
3961 $text = implode(";", $signed_parts);
3963 $message = ["author" => $handle,
3965 "parent_guid" => $parent_guid,
3966 "text" => implode(";", $signed_parts),
3967 "author_signature" => $signature['signature'],
3968 "parent_author_signature" => ""];
3974 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3976 * @param array $item The item that will be exported
3977 * @param array $owner the array of the item owner
3978 * @param array $contact Target of the communication
3979 * @param bool $public_batch Is it a public post?
3981 * @return int The result of the transmission
3983 public static function sendRelay($item, $owner, $contact, $public_batch = false)
3985 if ($item["deleted"]) {
3986 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3987 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3993 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3995 // fetch the original signature
3998 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
4003 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4009 // Old way - is used by the internal Friendica functions
4010 /// @todo Change all signatur storing functions to the new format
4011 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
4012 $message = self::messageFromSignature($item, $signature);
4014 $msg = json_decode($signature['signed_text'], true);
4017 if (is_array($msg)) {
4018 foreach ($msg as $field => $data) {
4019 if (!$item["deleted"]) {
4020 if ($field == "diaspora_handle") {
4023 if ($field == "target_type") {
4024 $field = "parent_type";
4028 $message[$field] = $data;
4031 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4035 $message["parent_author_signature"] = self::signature($owner, $message);
4037 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4039 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4043 * @brief Sends a retraction (deletion) of a message, like or comment
4045 * @param array $item The item that will be exported
4046 * @param array $owner the array of the item owner
4047 * @param array $contact Target of the communication
4048 * @param bool $public_batch Is it a public post?
4049 * @param bool $relay Is the retraction transmitted from a relay?
4051 * @return int The result of the transmission
4053 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4055 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4057 $msg_type = "retraction";
4059 if ($item['id'] == $item['parent']) {
4060 $target_type = "Post";
4061 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4062 $target_type = "Like";
4064 $target_type = "Comment";
4067 $message = ["author" => $itemaddr,
4068 "target_guid" => $item['guid'],
4069 "target_type" => $target_type];
4071 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4073 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4077 * @brief Sends a mail
4079 * @param array $item The item that will be exported
4080 * @param array $owner The owner
4081 * @param array $contact Target of the communication
4083 * @return int The result of the transmission
4085 public static function sendMail($item, $owner, $contact)
4087 $myaddr = self::myHandle($owner);
4090 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4091 intval($item["convid"]),
4092 intval($item["uid"])
4095 if (!DBM::is_result($r)) {
4096 logger("conversation not found.");
4102 "author" => $cnv["creator"],
4103 "guid" => $cnv["guid"],
4104 "subject" => $cnv["subject"],
4105 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4106 "participants" => $cnv["recips"]
4109 $body = BBCode::toMarkdown($item["body"]);
4110 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4113 "author" => $myaddr,
4114 "guid" => $item["guid"],
4115 "conversation_guid" => $cnv["guid"],
4117 "created_at" => $created,
4120 if ($item["reply"]) {
4125 "author" => $cnv["creator"],
4126 "guid" => $cnv["guid"],
4127 "subject" => $cnv["subject"],
4128 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4129 "participants" => $cnv["recips"],
4132 $type = "conversation";
4135 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4139 * @brief Split a name into first name and last name
4141 * @param string $name The name
4143 * @return array The array with "first" and "last"
4145 public static function splitName($name) {
4146 $name = trim($name);
4148 // Is the name longer than 64 characters? Then cut the rest of it.
4149 if (strlen($name) > 64) {
4150 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4151 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4153 $name = substr($name, 0, 64);
4157 // Take the first word as first name
4158 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4159 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4160 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4161 return ['first' => $first, 'last' => $last];
4164 // Take the last word as last name
4165 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4166 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4168 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4169 return ['first' => $first, 'last' => $last];
4172 // Take the first 32 characters if there is no space in the first 32 characters
4173 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4174 $first = substr($name, 0, 32);
4175 $last = substr($name, 32);
4176 return ['first' => $first, 'last' => $last];
4179 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4180 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4182 // Check if the last name is longer than 32 characters
4183 if (strlen($last) > 32) {
4184 if (strpos($last, ' ') <= 32) {
4185 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4187 $last = substr($last, 0, 32);
4191 return ['first' => $first, 'last' => $last];
4195 * @brief Create profile data
4197 * @param int $uid The user id
4199 * @return array The profile data
4201 private static function createProfileData($uid)
4204 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4206 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4207 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4208 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4217 $handle = $profile["addr"];
4219 $split_name = self::splitName($profile['name']);
4220 $first = $split_name['first'];
4221 $last = $split_name['last'];
4223 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4224 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4225 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4226 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4232 if ($searchable === 'true') {
4235 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4236 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4240 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4243 $about = $profile['about'];
4244 $about = strip_tags(BBCode::convert($about));
4246 $location = Profile::formatLocation($profile);
4248 if ($profile['pub_keywords']) {
4249 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4250 $kw = str_replace(' ', ' ', $kw);
4251 $arr = explode(' ', $profile['pub_keywords']);
4253 for ($x = 0; $x < 5; $x ++) {
4254 if (trim($arr[$x])) {
4255 $tags .= '#'. trim($arr[$x]) .' ';
4260 $tags = trim($tags);
4263 return ["author" => $handle,
4264 "first_name" => $first,
4265 "last_name" => $last,
4266 "image_url" => $large,
4267 "image_url_medium" => $medium,
4268 "image_url_small" => $small,
4270 "gender" => $profile['gender'],
4272 "location" => $location,
4273 "searchable" => $searchable,
4275 "tag_string" => $tags];
4279 * @brief Sends profile data
4281 * @param int $uid The user id
4282 * @param bool $recips optional, default false
4285 public static function sendProfile($uid, $recips = false)
4291 $owner = User::getOwnerDataById($uid);
4298 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4299 AND `uid` = %d AND `rel` != %d",
4300 dbesc(NETWORK_DIASPORA),
4302 intval(CONTACT_IS_SHARING)
4310 $message = self::createProfileData($uid);
4312 foreach ($recips as $recip) {
4313 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4314 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4319 * @brief Stores the signature for likes that are created on our system
4321 * @param array $contact The contact array of the "like"
4322 * @param int $post_id The post id of the "like"
4324 * @return bool Success
4326 public static function storeLikeSignature($contact, $post_id)
4328 // Is the contact the owner? Then fetch the private key
4329 if (!$contact['self'] || ($contact['uid'] == 0)) {
4330 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4334 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4335 if (!DBM::is_result($r)) {
4339 $contact["uprvkey"] = $r[0]['prvkey'];
4341 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4342 if (!DBM::is_result($r)) {
4346 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4350 $message = self::constructLike($r[0], $contact);
4351 if ($message === false) {
4355 $message["author_signature"] = self::signature($contact, $message);
4358 * Now store the signature more flexible to dynamically support new fields.
4359 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4361 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4363 logger('Stored diaspora like signature');
4368 * @brief Stores the signature for comments that are created on our system
4370 * @param array $item The item array of the comment
4371 * @param array $contact The contact array of the item owner
4372 * @param string $uprvkey The private key of the sender
4373 * @param int $message_id The message id of the comment
4375 * @return bool Success
4377 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4379 if ($uprvkey == "") {
4380 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4384 $contact["uprvkey"] = $uprvkey;
4386 $message = self::constructComment($item, $contact);
4387 if ($message === false) {
4391 $message["author_signature"] = self::signature($contact, $message);
4394 * Now store the signature more flexible to dynamically support new fields.
4395 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4397 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4399 logger('Stored diaspora comment signature');