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 * The list contains not only the official relays but also servers that we serve directly
52 * @param integer $item_id The id of the item that is sent
53 * @param array $contacts The previously fetched contacts
55 * @return array of relay servers
57 public static function relayList($item_id, $contacts = [])
61 // Fetching relay servers
62 $serverdata = Config::get("system", "relay_server");
63 if ($serverdata != "") {
64 $servers = explode(",", $serverdata);
65 foreach ($servers as $server) {
66 $serverlist[$server] = trim($server);
70 if (Config::get("system", "relay_directly", false)) {
71 // Servers that want to get all content
72 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
73 while ($server = dba::fetch($servers)) {
74 $serverlist[$server['url']] = $server['url'];
77 // All tags of the current post
78 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $item_id];
79 $tags = dba::select('term', ['term'], $condition);
81 while ($tag = dba::fetch($tags)) {
82 $taglist[] = $tag['term'];
85 // All servers who wants content with this tag
87 if (!empty($taglist)) {
88 $tagserver = dba::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
89 while ($server = dba::fetch($tagserver)) {
90 $tagserverlist[] = $server['gserver-id'];
94 // All adresses with the given id
95 if (!empty($tagserverlist)) {
96 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
97 while ($server = dba::fetch($servers)) {
98 $serverlist[$server['url']] = $server['url'];
103 // Now we are collecting all relay contacts
104 foreach ($serverlist as $server_url) {
105 // We don't send messages to ourselves
106 if (link_compare($server_url, System::baseUrl())) {
109 $contact = self::getRelayContact($server_url);
110 if (is_bool($contact)) {
115 foreach ($contacts as $entry) {
116 if ($entry['batch'] == $contact['batch']) {
122 $contacts[] = $contact;
130 * @brief Return a contact for a given server address or creates a dummy entry
132 * @param string $server_url The url of the server
133 * @return array with the contact
135 private static function getRelayContact($server_url)
137 $batch = $server_url . '/receive/public';
139 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
141 // Fetch the relay contact
142 $condition = ['uid' => 0, 'network' => NETWORK_DIASPORA, 'batch' => $batch,
143 'contact-type' => ACCOUNT_TYPE_RELAY];
144 $contact = dba::selectFirst('contact', $fields, $condition);
146 // If there is nothing found, we check if there is some unmarked relay
147 // This code segment can be removed before the release 2018-05
148 if (!DBM::is_result($contact)) {
149 $condition = ['uid' => 0, 'network' => NETWORK_DIASPORA, 'batch' => $batch,
150 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url];
151 $contact = dba::selectFirst('contact', $fields, $condition);
153 if (DBM::is_result($contact)) {
154 // Mark the relay account as a relay account
155 $fields = ['contact-type' => ACCOUNT_TYPE_RELAY];
156 dba::update('contact', $fields, ['id' => $contact['id']]);
159 if (DBM::is_result($contact)) {
160 if ($contact['archive'] || $contact['blocked']) {
165 $fields = ['uid' => 0, 'created' => DateTimeFormat::utcNow(),
166 'name' => 'relay', 'nick' => 'relay',
167 'url' => $server_url, 'nurl' => normalise_link($server_url),
168 'batch' => $batch, 'network' => NETWORK_DIASPORA,
169 'rel' => CONTACT_IS_FOLLOWER, 'blocked' => false,
170 'contact-type' => ACCOUNT_TYPE_RELAY,
171 'pending' => false, 'writable' => true];
172 dba::insert('contact', $fields);
174 $fields = ['batch', 'id', 'name', 'network'];
175 $contact = dba::selectFirst('contact', $fields, $condition);
176 if (DBM::is_result($contact)) {
182 // It should never happen that we arrive here
187 * @brief Return a list of participating contacts for a thread
189 * This is used for the participation feature.
190 * One of the parameters is a contact array.
191 * This is done to avoid duplicates.
193 * @param integer $thread The id of the thread
194 * @param array $contacts The previously fetched contacts
196 * @return array of relay servers
198 public static function participantsForThread($thread, $contacts)
200 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
201 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
202 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
203 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
204 WHERE `participation`.`iid` = ?", $thread);
206 while ($contact = dba::fetch($r)) {
207 if (!empty($contact['fnetwork'])) {
208 $contact['network'] = $contact['fnetwork'];
210 unset($contact['fnetwork']);
212 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
213 $contact['batch'] = $contact['fbatch'];
215 unset($contact['fbatch']);
218 foreach ($contacts as $entry) {
219 if ($entry['batch'] == $contact['batch']) {
225 $contacts[] = $contact;
234 * @brief repairs a signature that was double encoded
236 * The function is unused at the moment. It was copied from the old implementation.
238 * @param string $signature The signature
239 * @param string $handle The handle of the signature owner
240 * @param integer $level This value is only set inside this function to avoid endless loops
242 * @return string the repaired signature
244 private static function repairSignature($signature, $handle = "", $level = 1)
246 if ($signature == "") {
250 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
251 $signature = base64_decode($signature);
252 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
254 // Do a recursive call to be able to fix even multiple levels
256 $signature = self::repairSignature($signature, $handle, ++$level);
264 * @brief verify the envelope and return the verified data
266 * @param string $envelope The magic envelope
268 * @return string verified data
270 private static function verifyMagicEnvelope($envelope)
272 $basedom = XML::parseString($envelope);
274 if (!is_object($basedom)) {
275 logger("Envelope is no XML file");
279 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
281 if (sizeof($children) == 0) {
282 logger("XML has no children");
288 $data = base64url_decode($children->data);
289 $type = $children->data->attributes()->type[0];
291 $encoding = $children->encoding;
293 $alg = $children->alg;
295 $sig = base64url_decode($children->sig);
296 $key_id = $children->sig->attributes()->key_id[0];
298 $handle = base64url_decode($key_id);
301 $b64url_data = base64url_encode($data);
302 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
304 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
307 logger('No author could be decoded. Discarding. Message: ' . $envelope);
311 $key = self::key($handle);
313 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
317 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
319 logger('Message from ' . $handle . ' did not verify. Discarding.');
327 * @brief encrypts data via AES
329 * @param string $key The AES key
330 * @param string $iv The IV (is used for CBC encoding)
331 * @param string $data The data that is to be encrypted
333 * @return string encrypted data
335 private static function aesEncrypt($key, $iv, $data)
337 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
341 * @brief decrypts data via AES
343 * @param string $key The AES key
344 * @param string $iv The IV (is used for CBC encoding)
345 * @param string $encrypted The encrypted data
347 * @return string decrypted data
349 private static function aesDecrypt($key, $iv, $encrypted)
351 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
355 * @brief: Decodes incoming Diaspora message in the new format
357 * @param array $importer Array of the importer user
358 * @param string $raw raw post message
361 * 'message' -> decoded Diaspora XML message
362 * 'author' -> author diaspora handle
363 * 'key' -> author public key (converted to pkcs#8)
365 public static function decodeRaw($importer, $raw)
367 $data = json_decode($raw);
369 // Is it a private post? Then decrypt the outer Salmon
370 if (is_object($data)) {
371 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
372 $ciphertext = base64_decode($data->encrypted_magic_envelope);
374 $outer_key_bundle = '';
375 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
376 $j_outer_key_bundle = json_decode($outer_key_bundle);
378 if (!is_object($j_outer_key_bundle)) {
379 logger('Outer Salmon did not verify. Discarding.');
380 System::httpExit(400);
383 $outer_iv = base64_decode($j_outer_key_bundle->iv);
384 $outer_key = base64_decode($j_outer_key_bundle->key);
386 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
391 $basedom = XML::parseString($xml);
393 if (!is_object($basedom)) {
394 logger('Received data does not seem to be an XML. Discarding. '.$xml);
395 System::httpExit(400);
398 $base = $basedom->children(NAMESPACE_SALMON_ME);
400 // Not sure if this cleaning is needed
401 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
403 // Build the signed data
404 $type = $base->data[0]->attributes()->type[0];
405 $encoding = $base->encoding;
407 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
409 // This is the signature
410 $signature = base64url_decode($base->sig);
412 // Get the senders' public key
413 $key_id = $base->sig[0]->attributes()->key_id[0];
414 $author_addr = base64_decode($key_id);
415 if ($author_addr == '') {
416 logger('No author could be decoded. Discarding. Message: ' . $xml);
417 System::httpExit(400);
420 $key = self::key($author_addr);
422 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
423 System::httpExit(400);
426 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
428 logger('Message did not verify. Discarding.');
429 System::httpExit(400);
432 return ['message' => (string)base64url_decode($base->data),
433 'author' => unxmlify($author_addr),
434 'key' => (string)$key];
438 * @brief: Decodes incoming Diaspora message in the deprecated format
440 * @param array $importer Array of the importer user
441 * @param string $xml urldecoded Diaspora salmon
444 * 'message' -> decoded Diaspora XML message
445 * 'author' -> author diaspora handle
446 * 'key' -> author public key (converted to pkcs#8)
448 public static function decode($importer, $xml)
451 $basedom = XML::parseString($xml);
453 if (!is_object($basedom)) {
454 logger("XML is not parseable.");
457 $children = $basedom->children('https://joindiaspora.com/protocol');
459 $inner_aes_key = null;
462 if ($children->header) {
464 $author_link = str_replace('acct:', '', $children->header->author_id);
466 // This happens with posts from a relais
468 logger("This is no private post in the old format", LOGGER_DEBUG);
472 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
474 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
475 $ciphertext = base64_decode($encrypted_header->ciphertext);
477 $outer_key_bundle = '';
478 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
480 $j_outer_key_bundle = json_decode($outer_key_bundle);
482 $outer_iv = base64_decode($j_outer_key_bundle->iv);
483 $outer_key = base64_decode($j_outer_key_bundle->key);
485 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
487 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
488 $idom = XML::parseString($decrypted);
490 $inner_iv = base64_decode($idom->iv);
491 $inner_aes_key = base64_decode($idom->aes_key);
493 $author_link = str_replace('acct:', '', $idom->author_id);
496 $dom = $basedom->children(NAMESPACE_SALMON_ME);
498 // figure out where in the DOM tree our data is hiding
501 if ($dom->provenance->data) {
502 $base = $dom->provenance;
503 } elseif ($dom->env->data) {
505 } elseif ($dom->data) {
510 logger('unable to locate salmon data in xml');
511 System::httpExit(400);
515 // Stash the signature away for now. We have to find their key or it won't be good for anything.
516 $signature = base64url_decode($base->sig);
520 // strip whitespace so our data element will return to one big base64 blob
521 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
524 // stash away some other stuff for later
526 $type = $base->data[0]->attributes()->type[0];
527 $keyhash = $base->sig[0]->attributes()->keyhash[0];
528 $encoding = $base->encoding;
532 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
536 $data = base64url_decode($data);
540 $inner_decrypted = $data;
542 // Decode the encrypted blob
543 $inner_encrypted = base64_decode($data);
544 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
548 logger('Could not retrieve author URI.');
549 System::httpExit(400);
551 // Once we have the author URI, go to the web and try to find their public key
552 // (first this will look it up locally if it is in the fcontact cache)
553 // This will also convert diaspora public key from pkcs#1 to pkcs#8
555 logger('Fetching key for '.$author_link);
556 $key = self::key($author_link);
559 logger('Could not retrieve author key.');
560 System::httpExit(400);
563 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
566 logger('Message did not verify. Discarding.');
567 System::httpExit(400);
570 logger('Message verified.');
572 return ['message' => (string)$inner_decrypted,
573 'author' => unxmlify($author_link),
574 'key' => (string)$key];
579 * @brief Dispatches public messages and find the fitting receivers
581 * @param array $msg The post that will be dispatched
583 * @return int The message id of the generated message, "true" or "false" if there was an error
585 public static function dispatchPublic($msg)
587 $enabled = intval(Config::get("system", "diaspora_enabled"));
589 logger("diaspora is disabled");
593 if (!($fields = self::validPosting($msg))) {
594 logger("Invalid posting");
598 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
599 $message_id = self::dispatch($importer, $msg, $fields);
605 * @brief Dispatches the different message types to the different functions
607 * @param array $importer Array of the importer user
608 * @param array $msg The post that will be dispatched
609 * @param object $fields SimpleXML object that contains the message
611 * @return int The message id of the generated message, "true" or "false" if there was an error
613 public static function dispatch($importer, $msg, $fields = null)
615 // The sender is the handle of the contact that sent the message.
616 // This will often be different with relayed messages (for example "like" and "comment")
617 $sender = $msg["author"];
619 // This is only needed for private postings since this is already done for public ones before
620 if (is_null($fields)) {
621 if (!($fields = self::validPosting($msg))) {
622 logger("Invalid posting");
627 $type = $fields->getName();
629 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
632 case "account_migration":
633 return self::receiveAccountMigration($importer, $fields);
635 case "account_deletion":
636 return self::receiveAccountDeletion($importer, $fields);
639 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
642 return self::receiveContactRequest($importer, $fields);
645 return self::receiveConversation($importer, $msg, $fields);
648 return self::receiveLike($importer, $sender, $fields);
651 return self::receiveMessage($importer, $fields);
653 case "participation":
654 return self::receiveParticipation($importer, $fields);
656 case "photo": // Not implemented
657 return self::receivePhoto($importer, $fields);
659 case "poll_participation": // Not implemented
660 return self::receivePollParticipation($importer, $fields);
663 return self::receiveProfile($importer, $fields);
666 return self::receiveReshare($importer, $fields, $msg["message"]);
669 return self::receiveRetraction($importer, $sender, $fields);
671 case "status_message":
672 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
675 logger("Unknown message type ".$type);
683 * @brief Checks if a posting is valid and fetches the data fields.
685 * This function does not only check the signature.
686 * It also does the conversion between the old and the new diaspora format.
688 * @param array $msg Array with the XML, the sender handle and the sender signature
690 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
692 private static function validPosting($msg)
694 $data = XML::parseString($msg["message"]);
696 if (!is_object($data)) {
697 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
701 // Is this the new or the old version?
702 if ($data->getName() == "XML") {
704 foreach ($data->post->children() as $child) {
712 $type = $element->getName();
715 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
717 // All retractions are handled identically from now on.
718 // In the new version there will only be "retraction".
719 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
720 $type = "retraction";
722 if ($type == "request") {
726 $fields = new SimpleXMLElement("<".$type."/>");
729 $author_signature = null;
730 $parent_author_signature = null;
732 foreach ($element->children() as $fieldname => $entry) {
734 // Translation for the old XML structure
735 if ($fieldname == "diaspora_handle") {
736 $fieldname = "author";
738 if ($fieldname == "participant_handles") {
739 $fieldname = "participants";
741 if (in_array($type, ["like", "participation"])) {
742 if ($fieldname == "target_type") {
743 $fieldname = "parent_type";
746 if ($fieldname == "sender_handle") {
747 $fieldname = "author";
749 if ($fieldname == "recipient_handle") {
750 $fieldname = "recipient";
752 if ($fieldname == "root_diaspora_id") {
753 $fieldname = "root_author";
755 if ($type == "status_message") {
756 if ($fieldname == "raw_message") {
760 if ($type == "retraction") {
761 if ($fieldname == "post_guid") {
762 $fieldname = "target_guid";
764 if ($fieldname == "type") {
765 $fieldname = "target_type";
770 if (($fieldname == "author_signature") && ($entry != "")) {
771 $author_signature = base64_decode($entry);
772 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
773 $parent_author_signature = base64_decode($entry);
774 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
775 if ($signed_data != "") {
779 $signed_data .= $entry;
781 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
782 || ($orig_type == "relayable_retraction")
784 XML::copy($entry, $fields, $fieldname);
788 // This is something that shouldn't happen at all.
789 if (in_array($type, ["status_message", "reshare", "profile"])) {
790 if ($msg["author"] != $fields->author) {
791 logger("Message handle is not the same as envelope sender. Quitting this message.");
796 // Only some message types have signatures. So we quit here for the other types.
797 if (!in_array($type, ["comment", "like"])) {
800 // No author_signature? This is a must, so we quit.
801 if (!isset($author_signature)) {
802 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
806 if (isset($parent_author_signature)) {
807 $key = self::key($msg["author"]);
809 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
810 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);
815 $key = self::key($fields->author);
817 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
818 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
826 * @brief Fetches the public key for a given handle
828 * @param string $handle The handle
830 * @return string The public key
832 private static function key($handle)
834 $handle = strval($handle);
836 logger("Fetching diaspora key for: ".$handle);
838 $r = self::personByHandle($handle);
847 * @brief Fetches data for a given handle
849 * @param string $handle The handle
851 * @return array the queried data
853 public static function personByHandle($handle)
857 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
858 if (DBM::is_result($person)) {
859 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
861 // update record occasionally so it doesn't get stale
862 $d = strtotime($person["updated"]." +00:00");
863 if ($d < strtotime("now - 14 days")) {
867 if ($person["guid"] == "") {
872 if (!DBM::is_result($person) || $update) {
873 logger("create or refresh", LOGGER_DEBUG);
874 $r = Probe::uri($handle, NETWORK_DIASPORA);
876 // Note that Friendica contacts will return a "Diaspora person"
877 // if Diaspora connectivity is enabled on their server
878 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
879 self::addFContact($r, $update);
881 // Fetch the updated or added contact
882 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
883 if (!DBM::is_result($person)) {
893 * @brief Updates the fcontact table
895 * @param array $arr The fcontact data
896 * @param bool $update Update or insert?
898 * @return string The id of the fcontact entry
900 private static function addFContact($arr, $update = false)
904 "UPDATE `fcontact` SET
918 WHERE `url` = '%s' AND `network` = '%s'",
920 dbesc($arr["photo"]),
921 dbesc($arr["request"]),
923 dbesc(strtolower($arr["addr"])),
925 dbesc($arr["batch"]),
926 dbesc($arr["notify"]),
928 dbesc($arr["confirm"]),
929 dbesc($arr["alias"]),
930 dbesc($arr["pubkey"]),
931 dbesc(DateTimeFormat::utcNow()),
933 dbesc($arr["network"])
937 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
938 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
939 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
942 dbesc($arr["photo"]),
943 dbesc($arr["request"]),
947 dbesc($arr["batch"]),
948 dbesc($arr["notify"]),
950 dbesc($arr["confirm"]),
951 dbesc($arr["network"]),
952 dbesc($arr["alias"]),
953 dbesc($arr["pubkey"]),
954 dbesc(DateTimeFormat::utcNow())
962 * @brief get a handle (user@domain.tld) from a given contact id
964 * @param int $contact_id The id in the contact table
965 * @param int $pcontact_id The id in the contact table (Used for the public contact)
967 * @return string the handle
969 private static function handleFromContact($contact_id, $pcontact_id = 0)
973 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
975 if ($pcontact_id != 0) {
977 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
981 if (DBM::is_result($r)) {
982 return strtolower($r[0]["addr"]);
987 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
991 if (DBM::is_result($r)) {
994 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
996 if ($contact['addr'] != "") {
997 $handle = $contact['addr'];
999 $baseurl_start = strpos($contact['url'], '://') + 3;
1000 // allows installations in a subdirectory--not sure how Diaspora will handle
1001 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1002 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1003 $handle = $contact['nick'].'@'.$baseurl;
1007 return strtolower($handle);
1011 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1014 * @param mixed $fcontact_guid Hexadecimal string guid
1016 * @return string the contact url or null
1018 public static function urlFromContactGuid($fcontact_guid)
1020 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
1023 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1024 dbesc(NETWORK_DIASPORA),
1025 dbesc($fcontact_guid)
1028 if (DBM::is_result($r)) {
1029 return $r[0]['url'];
1036 * @brief Get a contact id for a given handle
1038 * @todo Move to Friendica\Model\Contact
1040 * @param int $uid The user id
1041 * @param string $handle The handle in the format user@domain.tld
1043 * @return int Contact id
1045 private static function contactByHandle($uid, $handle)
1047 // First do a direct search on the contact table
1049 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1054 if (DBM::is_result($r)) {
1058 * We haven't found it?
1059 * We use another function for it that will possibly create a contact entry.
1061 $cid = Contact::getIdForURL($handle, $uid);
1064 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1065 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1067 if (DBM::is_result($r)) {
1073 $handle_parts = explode("@", $handle);
1074 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1076 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1077 dbesc(NETWORK_DFRN),
1081 if (DBM::is_result($r)) {
1085 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1090 * @brief Check if posting is allowed for this contact
1092 * @param array $importer Array of the importer user
1093 * @param array $contact The contact that is checked
1094 * @param bool $is_comment Is the check for a comment?
1096 * @return bool is the contact allowed to post?
1098 private static function postAllow($importer, $contact, $is_comment = false)
1101 * Perhaps we were already sharing with this person. Now they're sharing with us.
1102 * That makes us friends.
1103 * Normally this should have handled by getting a request - but this could get lost
1105 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1106 // It is not removed by now. Possibly the code is needed?
1107 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1110 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1111 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1114 // $contact["rel"] = CONTACT_IS_FRIEND;
1115 // logger("defining user ".$contact["nick"]." as friend");
1118 // We don't seem to like that person
1119 if ($contact["blocked"] || $contact["readonly"]) {
1120 // Maybe blocked, don't accept.
1122 // We are following this person?
1123 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1124 // Yes, then it is fine.
1126 // Is it a post to a community?
1127 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && in_array($importer["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
1130 // Is the message a global user or a comment?
1131 } elseif (($importer["uid"] == 0) || $is_comment) {
1132 // Messages for the global users and comments are always accepted
1140 * @brief Fetches the contact id for a handle and checks if posting is allowed
1142 * @param array $importer Array of the importer user
1143 * @param string $handle The checked handle in the format user@domain.tld
1144 * @param bool $is_comment Is the check for a comment?
1146 * @return array The contact data
1148 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1150 $contact = self::contactByHandle($importer["uid"], $handle);
1152 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1153 // If a contact isn't found, we accept it anyway if it is a comment
1161 if (!self::postAllow($importer, $contact, $is_comment)) {
1162 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1169 * @brief Does the message already exists on the system?
1171 * @param int $uid The user id
1172 * @param string $guid The guid of the message
1174 * @return int|bool message id if the message already was stored into the system - or false.
1176 private static function messageExists($uid, $guid)
1179 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1184 if (DBM::is_result($r)) {
1185 logger("message ".$guid." already exists for user ".$uid);
1193 * @brief Checks for links to posts in a message
1195 * @param array $item The item array
1198 private static function fetchGuid($item)
1200 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1201 preg_replace_callback(
1203 function ($match) use ($item) {
1204 self::fetchGuidSub($match, $item);
1209 preg_replace_callback(
1210 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1211 function ($match) use ($item) {
1212 self::fetchGuidSub($match, $item);
1219 * @brief Checks for relative /people/* links in an item body to match local
1220 * contacts or prepends the remote host taken from the author link.
1222 * @param string $body The item body to replace links from
1223 * @param string $author_link The author link for missing local contact fallback
1225 * @return string the replaced string
1227 public static function replacePeopleGuid($body, $author_link)
1229 $return = preg_replace_callback(
1230 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1231 function ($match) use ($author_link) {
1233 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1234 // 1 => '0123456789abcdef'
1236 $handle = self::urlFromContactGuid($match[1]);
1239 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1241 // No local match, restoring absolute remote URL from author scheme and host
1242 $author_url = parse_url($author_link);
1243 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1255 * @brief sub function of "fetchGuid" which checks for links in messages
1257 * @param array $match array containing a link that has to be checked for a message link
1258 * @param array $item The item array
1261 private static function fetchGuidSub($match, $item)
1263 if (!self::storeByGuid($match[1], $item["author-link"])) {
1264 self::storeByGuid($match[1], $item["owner-link"]);
1269 * @brief Fetches an item with a given guid from a given server
1271 * @param string $guid the message guid
1272 * @param string $server The server address
1273 * @param int $uid The user id of the user
1275 * @return int the message id of the stored message or false
1277 private static function storeByGuid($guid, $server, $uid = 0)
1279 $serverparts = parse_url($server);
1280 $server = $serverparts["scheme"]."://".$serverparts["host"];
1282 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1284 $msg = self::message($guid, $server);
1290 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1292 // Now call the dispatcher
1293 return self::dispatchPublic($msg);
1297 * @brief Fetches a message from a server
1299 * @param string $guid message guid
1300 * @param string $server The url of the server
1301 * @param int $level Endless loop prevention
1304 * 'message' => The message XML
1305 * 'author' => The author handle
1306 * 'key' => The public key of the author
1308 private static function message($guid, $server, $level = 0)
1314 // This will work for new Diaspora servers and Friendica servers from 3.5
1315 $source_url = $server."/fetch/post/".urlencode($guid);
1317 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1319 $envelope = Network::fetchUrl($source_url);
1321 logger("Envelope was fetched.", LOGGER_DEBUG);
1322 $x = self::verifyMagicEnvelope($envelope);
1324 logger("Envelope could not be verified.", LOGGER_DEBUG);
1326 logger("Envelope was verified.", LOGGER_DEBUG);
1332 // This will work for older Diaspora and Friendica servers
1334 $source_url = $server."/p/".urlencode($guid).".xml";
1335 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1337 $x = Network::fetchUrl($source_url);
1343 $source_xml = XML::parseString($x);
1345 if (!is_object($source_xml)) {
1349 if ($source_xml->post->reshare) {
1350 // Reshare of a reshare - old Diaspora version
1351 logger("Message is a reshare", LOGGER_DEBUG);
1352 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1353 } elseif ($source_xml->getName() == "reshare") {
1354 // Reshare of a reshare - new Diaspora version
1355 logger("Message is a new reshare", LOGGER_DEBUG);
1356 return self::message($source_xml->root_guid, $server, ++$level);
1361 // Fetch the author - for the old and the new Diaspora version
1362 if ($source_xml->post->status_message->diaspora_handle) {
1363 $author = (string)$source_xml->post->status_message->diaspora_handle;
1364 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1365 $author = (string)$source_xml->author;
1368 // If this isn't a "status_message" then quit
1370 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1374 $msg = ["message" => $x, "author" => $author];
1376 $msg["key"] = self::key($msg["author"]);
1382 * @brief Fetches the item record of a given guid
1384 * @param int $uid The user id
1385 * @param string $guid message guid
1386 * @param string $author The handle of the item
1387 * @param array $contact The contact of the item owner
1389 * @return array the item record
1391 private static function parentItem($uid, $guid, $author, $contact)
1394 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1395 `author-name`, `author-link`, `author-avatar`,
1396 `owner-name`, `owner-link`, `owner-avatar`
1397 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1403 $result = self::storeByGuid($guid, $contact["url"], $uid);
1406 $person = self::personByHandle($author);
1407 $result = self::storeByGuid($guid, $person["url"], $uid);
1411 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1414 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1415 `author-name`, `author-link`, `author-avatar`,
1416 `owner-name`, `owner-link`, `owner-avatar`
1417 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1425 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1428 logger("parent item found: parent: ".$guid." - user: ".$uid);
1434 * @brief returns contact details
1436 * @param array $def_contact The default contact if the person isn't found
1437 * @param array $person The record of the person
1438 * @param int $uid The user id
1441 * 'cid' => contact id
1442 * 'network' => network type
1444 private static function authorContactByUrl($def_contact, $person, $uid)
1446 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1447 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1448 if (DBM::is_result($contact)) {
1449 $cid = $contact["id"];
1450 $network = $contact["network"];
1452 $cid = $def_contact["id"];
1453 $network = NETWORK_DIASPORA;
1456 return ["cid" => $cid, "network" => $network];
1460 * @brief Is the profile a hubzilla profile?
1462 * @param string $url The profile link
1464 * @return bool is it a hubzilla server?
1466 public static function isRedmatrix($url)
1468 return(strstr($url, "/channel/"));
1472 * @brief Generate a post link with a given handle and message guid
1474 * @param string $addr The user handle
1475 * @param string $guid message guid
1476 * @param string $parent_guid optional parent guid
1478 * @return string the post link
1480 private static function plink($addr, $guid, $parent_guid = '')
1482 $contact = Contact::getDetailsByAddr($addr);
1486 if ($parent_guid != '') {
1487 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1489 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1493 if ($contact["network"] == NETWORK_DFRN) {
1494 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1497 if (self::isRedmatrix($contact["url"])) {
1498 return $contact["url"] . "/?f=&mid=" . $guid;
1501 if ($parent_guid != '') {
1502 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1504 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1509 * @brief Receives account migration
1511 * @param array $importer Array of the importer user
1512 * @param object $data The message object
1514 * @return bool Success
1516 private static function receiveAccountMigration($importer, $data)
1518 $old_handle = notags(unxmlify($data->author));
1519 $new_handle = notags(unxmlify($data->profile->author));
1520 $signature = notags(unxmlify($data->signature));
1522 $contact = self::contactByHandle($importer["uid"], $old_handle);
1524 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1528 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1531 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1532 $key = self::key($old_handle);
1533 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1534 logger('No valid signature for migration.');
1538 // Update the profile
1539 self::receiveProfile($importer, $data->profile);
1541 // change the technical stuff in contact and gcontact
1542 $data = Probe::uri($new_handle);
1543 if ($data['network'] == NETWORK_PHANTOM) {
1544 logger('Account for '.$new_handle." couldn't be probed.");
1548 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1549 'name' => $data['name'], 'nick' => $data['nick'],
1550 'addr' => $data['addr'], 'batch' => $data['batch'],
1551 'notify' => $data['notify'], 'poll' => $data['poll'],
1552 'network' => $data['network']];
1554 dba::update('contact', $fields, ['addr' => $old_handle]);
1556 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1557 'name' => $data['name'], 'nick' => $data['nick'],
1558 'addr' => $data['addr'], 'connect' => $data['addr'],
1559 'notify' => $data['notify'], 'photo' => $data['photo'],
1560 'server_url' => $data['baseurl'], 'network' => $data['network']];
1562 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1564 logger('Contacts are updated.');
1567 /// @todo This is an extreme performance killer
1569 'owner-link' => [$contact["url"], $data["url"]],
1570 'author-link' => [$contact["url"], $data["url"]],
1572 foreach ($fields as $n => $f) {
1574 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1577 intval($importer["uid"])
1580 if (DBM::is_result($r)) {
1582 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1587 intval($importer["uid"])
1596 logger('Items are updated.');
1602 * @brief Processes an account deletion
1604 * @param array $importer Array of the importer user
1605 * @param object $data The message object
1607 * @return bool Success
1609 private static function receiveAccountDeletion($importer, $data)
1611 /// @todo Account deletion should remove the contact from the global contacts as well
1613 $author = notags(unxmlify($data->author));
1615 $contact = self::contactByHandle($importer["uid"], $author);
1617 logger("cannot find contact for author: ".$author);
1621 // We now remove the contact
1622 Contact::remove($contact["id"]);
1627 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1629 * @param string $author Author handle
1630 * @param string $guid Message guid
1631 * @param boolean $onlyfound Only return uri when found in the database
1633 * @return string The constructed uri or the one from our database
1635 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1637 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1638 if (DBM::is_result($r)) {
1639 return $r[0]["uri"];
1640 } elseif (!$onlyfound) {
1641 return $author.":".$guid;
1648 * @brief Fetch the guid from our database with a given uri
1650 * @param string $uri Message uri
1651 * @param string $uid Author handle
1653 * @return string The post guid
1655 private static function getGuidFromUri($uri, $uid)
1657 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1658 if (DBM::is_result($r)) {
1659 return $r[0]["guid"];
1666 * @brief Find the best importer for a comment, like, ...
1668 * @param string $guid The guid of the item
1670 * @return array|boolean the origin owner of that post - or false
1672 private static function importerForGuid($guid)
1674 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1676 if (DBM::is_result($item)) {
1677 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1678 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1679 if (DBM::is_result($contact)) {
1687 * @brief Processes an incoming comment
1689 * @param array $importer Array of the importer user
1690 * @param string $sender The sender of the message
1691 * @param object $data The message object
1692 * @param string $xml The original XML of the message
1694 * @return int The message id of the generated comment or "false" if there was an error
1696 private static function receiveComment($importer, $sender, $data, $xml)
1698 $author = notags(unxmlify($data->author));
1699 $guid = notags(unxmlify($data->guid));
1700 $parent_guid = notags(unxmlify($data->parent_guid));
1701 $text = unxmlify($data->text);
1703 if (isset($data->created_at)) {
1704 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1706 $created_at = DateTimeFormat::utcNow();
1709 if (isset($data->thread_parent_guid)) {
1710 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1711 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1716 $contact = self::allowedContactByHandle($importer, $sender, true);
1721 $message_id = self::messageExists($importer["uid"], $guid);
1726 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1727 if (!$parent_item) {
1731 $person = self::personByHandle($author);
1732 if (!is_array($person)) {
1733 logger("unable to find author details");
1737 // Fetch the contact id - if we know this contact
1738 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1742 $datarray["uid"] = $importer["uid"];
1743 $datarray["contact-id"] = $author_contact["cid"];
1744 $datarray["network"] = $author_contact["network"];
1746 $datarray["author-name"] = $person["name"];
1747 $datarray["author-link"] = $person["url"];
1748 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1750 $datarray["owner-name"] = $contact["name"];
1751 $datarray["owner-link"] = $contact["url"];
1752 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1754 $datarray["guid"] = $guid;
1755 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1757 $datarray["type"] = "remote-comment";
1758 $datarray["verb"] = ACTIVITY_POST;
1759 $datarray["gravity"] = GRAVITY_COMMENT;
1761 if ($thr_uri != "") {
1762 $datarray["parent-uri"] = $thr_uri;
1764 $datarray["parent-uri"] = $parent_item["uri"];
1767 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1769 $datarray["protocol"] = PROTOCOL_DIASPORA;
1770 $datarray["source"] = $xml;
1772 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1774 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1776 $body = Markdown::toBBCode($text);
1778 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1780 self::fetchGuid($datarray);
1782 $message_id = Item::insert($datarray);
1784 if ($message_id <= 0) {
1789 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1790 if ($datarray['uid'] == 0) {
1791 Item::distribute($message_id);
1795 // If we are the origin of the parent we store the original data and notify our followers
1796 if ($message_id && $parent_item["origin"]) {
1797 // Formerly we stored the signed text, the signature and the author in different fields.
1798 // We now store the raw data so that we are more flexible.
1799 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1802 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1809 * @brief processes and stores private messages
1811 * @param array $importer Array of the importer user
1812 * @param array $contact The contact of the message
1813 * @param object $data The message object
1814 * @param array $msg Array of the processed message, author handle and key
1815 * @param object $mesg The private message
1816 * @param array $conversation The conversation record to which this message belongs
1818 * @return bool "true" if it was successful
1820 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1822 $author = notags(unxmlify($data->author));
1823 $guid = notags(unxmlify($data->guid));
1824 $subject = notags(unxmlify($data->subject));
1826 // "diaspora_handle" is the element name from the old version
1827 // "author" is the element name from the new version
1828 if ($mesg->author) {
1829 $msg_author = notags(unxmlify($mesg->author));
1830 } elseif ($mesg->diaspora_handle) {
1831 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1836 $msg_guid = notags(unxmlify($mesg->guid));
1837 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1838 $msg_text = unxmlify($mesg->text);
1839 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1841 if ($msg_conversation_guid != $guid) {
1842 logger("message conversation guid does not belong to the current conversation.");
1846 $body = Markdown::toBBCode($msg_text);
1847 $message_uri = $msg_author.":".$msg_guid;
1849 $person = self::personByHandle($msg_author);
1854 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1856 intval($importer["uid"])
1858 if (DBM::is_result($r)) {
1859 logger("duplicate message already delivered.", LOGGER_DEBUG);
1864 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1865 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1866 intval($importer["uid"]),
1868 intval($conversation["id"]),
1869 dbesc($person["name"]),
1870 dbesc($person["photo"]),
1871 dbesc($person["url"]),
1872 intval($contact["id"]),
1877 dbesc($message_uri),
1878 dbesc($author.":".$guid),
1879 dbesc($msg_created_at)
1884 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1888 "type" => NOTIFY_MAIL,
1889 "notify_flags" => $importer["notify-flags"],
1890 "language" => $importer["language"],
1891 "to_name" => $importer["username"],
1892 "to_email" => $importer["email"],
1893 "uid" =>$importer["uid"],
1894 "item" => ["subject" => $subject, "body" => $body],
1895 "source_name" => $person["name"],
1896 "source_link" => $person["url"],
1897 "source_photo" => $person["thumb"],
1898 "verb" => ACTIVITY_POST,
1905 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1907 * @param array $importer Array of the importer user
1908 * @param array $msg Array of the processed message, author handle and key
1909 * @param object $data The message object
1911 * @return bool Success
1913 private static function receiveConversation($importer, $msg, $data)
1915 $author = notags(unxmlify($data->author));
1916 $guid = notags(unxmlify($data->guid));
1917 $subject = notags(unxmlify($data->subject));
1918 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1919 $participants = notags(unxmlify($data->participants));
1921 $messages = $data->message;
1923 if (!count($messages)) {
1924 logger("empty conversation");
1928 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1933 $conversation = null;
1936 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1937 intval($importer["uid"]),
1941 $conversation = $c[0];
1944 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1945 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1946 intval($importer["uid"]),
1950 dbesc(DateTimeFormat::utcNow()),
1952 dbesc($participants)
1956 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1957 intval($importer["uid"]),
1963 $conversation = $c[0];
1966 if (!$conversation) {
1967 logger("unable to create conversation.");
1971 foreach ($messages as $mesg) {
1972 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1979 * @brief Creates the body for a "like" message
1981 * @param array $contact The contact that send us the "like"
1982 * @param array $parent_item The item array of the parent item
1983 * @param string $guid message guid
1985 * @return string the body
1987 private static function constructLikeBody($contact, $parent_item, $guid)
1989 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1991 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1992 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1993 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
1995 return sprintf($bodyverb, $ulink, $alink, $plink);
1999 * @brief Creates a XML object for a "like"
2001 * @param array $importer Array of the importer user
2002 * @param array $parent_item The item array of the parent item
2004 * @return string The XML
2006 private static function constructLikeObject($importer, $parent_item)
2008 $objtype = ACTIVITY_OBJ_NOTE;
2009 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
2010 $parent_body = $parent_item["body"];
2012 $xmldata = ["object" => ["type" => $objtype,
2014 "id" => $parent_item["uri"],
2017 "content" => $parent_body]];
2019 return XML::fromArray($xmldata, $xml, true);
2023 * @brief Processes "like" messages
2025 * @param array $importer Array of the importer user
2026 * @param string $sender The sender of the message
2027 * @param object $data The message object
2029 * @return int The message id of the generated like or "false" if there was an error
2031 private static function receiveLike($importer, $sender, $data)
2033 $author = notags(unxmlify($data->author));
2034 $guid = notags(unxmlify($data->guid));
2035 $parent_guid = notags(unxmlify($data->parent_guid));
2036 $parent_type = notags(unxmlify($data->parent_type));
2037 $positive = notags(unxmlify($data->positive));
2039 // likes on comments aren't supported by Diaspora - only on posts
2040 // But maybe this will be supported in the future, so we will accept it.
2041 if (!in_array($parent_type, ["Post", "Comment"])) {
2045 $contact = self::allowedContactByHandle($importer, $sender, true);
2050 $message_id = self::messageExists($importer["uid"], $guid);
2055 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2056 if (!$parent_item) {
2060 $person = self::personByHandle($author);
2061 if (!is_array($person)) {
2062 logger("unable to find author details");
2066 // Fetch the contact id - if we know this contact
2067 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2069 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2070 // We would accept this anyhow.
2071 if ($positive == "true") {
2072 $verb = ACTIVITY_LIKE;
2074 $verb = ACTIVITY_DISLIKE;
2079 $datarray["protocol"] = PROTOCOL_DIASPORA;
2081 $datarray["uid"] = $importer["uid"];
2082 $datarray["contact-id"] = $author_contact["cid"];
2083 $datarray["network"] = $author_contact["network"];
2085 $datarray["author-name"] = $person["name"];
2086 $datarray["author-link"] = $person["url"];
2087 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2089 $datarray["owner-name"] = $contact["name"];
2090 $datarray["owner-link"] = $contact["url"];
2091 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2093 $datarray["guid"] = $guid;
2094 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2096 $datarray["type"] = "activity";
2097 $datarray["verb"] = $verb;
2098 $datarray["gravity"] = GRAVITY_LIKE;
2099 $datarray["parent-uri"] = $parent_item["uri"];
2101 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2102 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2104 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2106 $message_id = Item::insert($datarray);
2108 if ($message_id <= 0) {
2113 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2114 if ($datarray['uid'] == 0) {
2115 Item::distribute($message_id);
2119 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2120 if ($parent_item["id"] != $parent_item["parent"]) {
2121 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2122 $origin = $toplevel["origin"];
2124 $origin = $parent_item["origin"];
2127 // If we are the origin of the parent we store the original data and notify our followers
2128 if ($message_id && $origin) {
2129 // Formerly we stored the signed text, the signature and the author in different fields.
2130 // We now store the raw data so that we are more flexible.
2131 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2134 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2141 * @brief Processes private messages
2143 * @param array $importer Array of the importer user
2144 * @param object $data The message object
2146 * @return bool Success?
2148 private static function receiveMessage($importer, $data)
2150 $author = notags(unxmlify($data->author));
2151 $guid = notags(unxmlify($data->guid));
2152 $conversation_guid = notags(unxmlify($data->conversation_guid));
2153 $text = unxmlify($data->text);
2154 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2156 $contact = self::allowedContactByHandle($importer, $author, true);
2161 $conversation = null;
2164 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2165 intval($importer["uid"]),
2166 dbesc($conversation_guid)
2169 $conversation = $c[0];
2171 logger("conversation not available.");
2175 $message_uri = $author.":".$guid;
2177 $person = self::personByHandle($author);
2179 logger("unable to find author details");
2183 $body = Markdown::toBBCode($text);
2185 $body = self::replacePeopleGuid($body, $person["url"]);
2190 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2192 intval($importer["uid"])
2194 if (DBM::is_result($r)) {
2195 logger("duplicate message already delivered.", LOGGER_DEBUG);
2200 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2201 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2202 intval($importer["uid"]),
2204 intval($conversation["id"]),
2205 dbesc($person["name"]),
2206 dbesc($person["photo"]),
2207 dbesc($person["url"]),
2208 intval($contact["id"]),
2209 dbesc($conversation["subject"]),
2213 dbesc($message_uri),
2214 dbesc($author.":".$conversation["guid"]),
2220 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2225 * @brief Processes participations - unsupported by now
2227 * @param array $importer Array of the importer user
2228 * @param object $data The message object
2230 * @return bool always true
2232 private static function receiveParticipation($importer, $data)
2234 $author = strtolower(notags(unxmlify($data->author)));
2235 $parent_guid = notags(unxmlify($data->parent_guid));
2237 $contact_id = Contact::getIdForURL($author);
2239 logger('Contact not found: '.$author);
2243 $person = self::personByHandle($author);
2244 if (!is_array($person)) {
2245 logger("Person not found: ".$author);
2249 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2250 if (!DBM::is_result($item)) {
2251 logger('Item not found, no origin or private: '.$parent_guid);
2255 $author_parts = explode('@', $author);
2256 if (isset($author_parts[1])) {
2257 $server = $author_parts[1];
2259 // Should never happen
2263 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2265 if (!dba::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2266 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2269 // Send all existing comments and likes to the requesting server
2270 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2272 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2273 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2274 while ($comment = dba::fetch($comments)) {
2275 if ($comment['verb'] == ACTIVITY_POST) {
2276 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2278 $cmd = $comment['self'] ? 'like' : 'comment-import';
2280 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2281 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2283 dba::close($comments);
2289 * @brief Processes photos - unneeded
2291 * @param array $importer Array of the importer user
2292 * @param object $data The message object
2294 * @return bool always true
2296 private static function receivePhoto($importer, $data)
2298 // There doesn't seem to be a reason for this function,
2299 // since the photo data is transmitted in the status message as well
2304 * @brief Processes poll participations - unssupported
2306 * @param array $importer Array of the importer user
2307 * @param object $data The message object
2309 * @return bool always true
2311 private static function receivePollParticipation($importer, $data)
2313 // We don't support polls by now
2318 * @brief Processes incoming profile updates
2320 * @param array $importer Array of the importer user
2321 * @param object $data The message object
2323 * @return bool Success
2325 private static function receiveProfile($importer, $data)
2327 $author = strtolower(notags(unxmlify($data->author)));
2329 $contact = self::contactByHandle($importer["uid"], $author);
2334 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2335 $image_url = unxmlify($data->image_url);
2336 $birthday = unxmlify($data->birthday);
2337 $gender = unxmlify($data->gender);
2338 $about = Markdown::toBBCode(unxmlify($data->bio));
2339 $location = Markdown::toBBCode(unxmlify($data->location));
2340 $searchable = (unxmlify($data->searchable) == "true");
2341 $nsfw = (unxmlify($data->nsfw) == "true");
2342 $tags = unxmlify($data->tag_string);
2344 $tags = explode("#", $tags);
2347 foreach ($tags as $tag) {
2348 $tag = trim(strtolower($tag));
2354 $keywords = implode(", ", $keywords);
2356 $handle_parts = explode("@", $author);
2357 $nick = $handle_parts[0];
2360 $name = $handle_parts[0];
2363 if (preg_match("|^https?://|", $image_url) === 0) {
2364 $image_url = "http://".$handle_parts[1].$image_url;
2367 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2369 // Generic birthday. We don't know the timezone. The year is irrelevant.
2371 $birthday = str_replace("1000", "1901", $birthday);
2373 if ($birthday != "") {
2374 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2377 // this is to prevent multiple birthday notifications in a single year
2378 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2380 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2381 $birthday = $contact["bd"];
2385 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2386 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2390 dbesc(DateTimeFormat::utcNow()),
2396 intval($contact["id"]),
2397 intval($importer["uid"])
2400 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2401 "photo" => $image_url, "name" => $name, "location" => $location,
2402 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2403 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2404 "hide" => !$searchable, "nsfw" => $nsfw];
2406 $gcid = GContact::update($gcontact);
2408 GContact::link($gcid, $importer["uid"], $contact["id"]);
2410 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2416 * @brief Processes incoming friend requests
2418 * @param array $importer Array of the importer user
2419 * @param array $contact The contact that send the request
2422 private static function receiveRequestMakeFriend($importer, $contact)
2426 if ($contact["rel"] == CONTACT_IS_SHARING) {
2429 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2430 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2433 // send notification
2436 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2437 intval($importer["uid"])
2440 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2442 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2443 intval($importer["uid"])
2446 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2448 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2450 $arr["protocol"] = PROTOCOL_DIASPORA;
2451 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2452 $arr["uid"] = $importer["uid"];
2453 $arr["contact-id"] = $self[0]["id"];
2455 $arr["type"] = 'wall';
2456 $arr["gravity"] = 0;
2458 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2459 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2460 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2461 $arr["verb"] = ACTIVITY_FRIEND;
2462 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2464 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2465 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2466 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2467 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2469 $arr["object"] = self::constructNewFriendObject($contact);
2471 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2473 $arr["allow_cid"] = $user["allow_cid"];
2474 $arr["allow_gid"] = $user["allow_gid"];
2475 $arr["deny_cid"] = $user["deny_cid"];
2476 $arr["deny_gid"] = $user["deny_gid"];
2478 $i = Item::insert($arr);
2480 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2487 * @brief Creates a XML object for a "new friend" message
2489 * @param array $contact Array of the contact
2491 * @return string The XML
2493 private static function constructNewFriendObject($contact)
2495 $objtype = ACTIVITY_OBJ_PERSON;
2496 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2497 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2499 $xmldata = ["object" => ["type" => $objtype,
2500 "title" => $contact["name"],
2501 "id" => $contact["url"]."/".$contact["name"],
2504 return XML::fromArray($xmldata, $xml, true);
2508 * @brief Processes incoming sharing notification
2510 * @param array $importer Array of the importer user
2511 * @param object $data The message object
2513 * @return bool Success
2515 private static function receiveContactRequest($importer, $data)
2517 $author = unxmlify($data->author);
2518 $recipient = unxmlify($data->recipient);
2520 if (!$author || !$recipient) {
2524 // the current protocol version doesn't know these fields
2525 // That means that we will assume their existance
2526 if (isset($data->following)) {
2527 $following = (unxmlify($data->following) == "true");
2532 if (isset($data->sharing)) {
2533 $sharing = (unxmlify($data->sharing) == "true");
2538 $contact = self::contactByHandle($importer["uid"], $author);
2540 // perhaps we were already sharing with this person. Now they're sharing with us.
2541 // That makes us friends.
2544 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2545 self::receiveRequestMakeFriend($importer, $contact);
2547 // refetch the contact array
2548 $contact = self::contactByHandle($importer["uid"], $author);
2550 // If we are now friends, we are sending a share message.
2551 // Normally we needn't to do so, but the first message could have been vanished.
2552 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2553 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2555 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2556 $ret = self::sendShare($u[0], $contact);
2561 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2562 Contact::removeFollower($importer, $contact);
2567 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2568 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2570 } elseif (!$following && !$sharing) {
2571 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2573 } elseif (!$following && $sharing) {
2574 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2575 } elseif ($following && $sharing) {
2576 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2577 } elseif ($following && !$sharing) {
2578 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2581 $ret = self::personByHandle($author);
2583 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2584 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2588 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2591 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2592 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2593 intval($importer["uid"]),
2594 dbesc($ret["network"]),
2595 dbesc($ret["addr"]),
2596 DateTimeFormat::utcNow(),
2598 dbesc(normalise_link($ret["url"])),
2600 dbesc($ret["name"]),
2601 dbesc($ret["nick"]),
2602 dbesc($ret["photo"]),
2603 dbesc($ret["pubkey"]),
2604 dbesc($ret["notify"]),
2605 dbesc($ret["poll"]),
2610 // find the contact record we just created
2612 $contact_record = self::contactByHandle($importer["uid"], $author);
2614 if (!$contact_record) {
2615 logger("unable to locate newly created contact record.");
2619 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2621 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2623 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2625 if (in_array($importer["page-flags"], [PAGE_NORMAL, PAGE_PRVGROUP])) {
2626 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2628 $hash = random_string().(string)time(); // Generate a confirm_key
2631 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2632 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2633 intval($importer["uid"]),
2634 intval($contact_record["id"]),
2637 dbesc(L10n::t("Sharing notification from Diaspora network")),
2639 dbesc(DateTimeFormat::utcNow())
2642 // automatic friend approval
2644 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2646 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2648 // technically they are sharing with us (CONTACT_IS_SHARING),
2649 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2650 // we are going to change the relationship and make them a follower.
2652 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2653 $new_relation = CONTACT_IS_FRIEND;
2654 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2655 $new_relation = CONTACT_IS_SHARING;
2657 $new_relation = CONTACT_IS_FOLLOWER;
2661 "UPDATE `contact` SET `rel` = %d,
2669 intval($new_relation),
2670 dbesc(DateTimeFormat::utcNow()),
2671 dbesc(DateTimeFormat::utcNow()),
2672 intval($contact_record["id"])
2675 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2677 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2678 $ret = self::sendShare($u[0], $contact_record);
2680 // Send the profile data, maybe it weren't transmitted before
2681 self::sendProfile($importer["uid"], [$contact_record]);
2689 * @brief Fetches a message with a given guid
2691 * @param string $guid message guid
2692 * @param string $orig_author handle of the original post
2693 * @param string $author handle of the sharer
2695 * @return array The fetched item
2697 public static function originalItem($guid, $orig_author)
2699 // Do we already have this item?
2700 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2701 'author-name', 'author-link', 'author-avatar'];
2702 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false];
2703 $item = dba::selectfirst('item', $fields, $condition);
2705 if (DBM::is_result($item)) {
2706 logger("reshared message ".$guid." already exists on system.");
2708 // Maybe it is already a reshared item?
2709 // Then refetch the content, if it is a reshare from a reshare.
2710 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2711 if (self::isReshare($item["body"], true)) {
2713 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2714 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2716 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2718 // Add OEmbed and other information to the body
2719 $item["body"] = add_page_info_to_body($item["body"], false, true);
2727 if (!DBM::is_result($r)) {
2728 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2729 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2730 $item_id = self::storeByGuid($guid, $server);
2733 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2734 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2735 $item_id = self::storeByGuid($guid, $server);
2739 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2740 'author-name', 'author-link', 'author-avatar'];
2741 $condition = ['id' => $item_id, 'visible' => true, 'deleted' => false];
2742 $item = dba::selectfirst('item', $fields, $condition);
2744 if (DBM::is_result($item)) {
2745 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2746 if (self::isReshare($item["body"], false)) {
2747 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2748 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2759 * @brief Processes a reshare message
2761 * @param array $importer Array of the importer user
2762 * @param object $data The message object
2763 * @param string $xml The original XML of the message
2765 * @return int the message id
2767 private static function receiveReshare($importer, $data, $xml)
2769 $author = notags(unxmlify($data->author));
2770 $guid = notags(unxmlify($data->guid));
2771 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2772 $root_author = notags(unxmlify($data->root_author));
2773 $root_guid = notags(unxmlify($data->root_guid));
2774 /// @todo handle unprocessed property "provider_display_name"
2775 $public = notags(unxmlify($data->public));
2777 $contact = self::allowedContactByHandle($importer, $author, false);
2782 $message_id = self::messageExists($importer["uid"], $guid);
2787 $original_item = self::originalItem($root_guid, $root_author);
2788 if (!$original_item) {
2792 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2796 $datarray["uid"] = $importer["uid"];
2797 $datarray["contact-id"] = $contact["id"];
2798 $datarray["network"] = NETWORK_DIASPORA;
2800 $datarray["author-name"] = $contact["name"];
2801 $datarray["author-link"] = $contact["url"];
2802 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2804 $datarray["owner-name"] = $datarray["author-name"];
2805 $datarray["owner-link"] = $datarray["author-link"];
2806 $datarray["owner-avatar"] = $datarray["author-avatar"];
2808 $datarray["guid"] = $guid;
2809 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2811 $datarray["verb"] = ACTIVITY_POST;
2812 $datarray["gravity"] = GRAVITY_PARENT;
2814 $datarray["protocol"] = PROTOCOL_DIASPORA;
2815 $datarray["source"] = $xml;
2817 $prefix = share_header(
2818 $original_item["author-name"],
2819 $original_item["author-link"],
2820 $original_item["author-avatar"],
2821 $original_item["guid"],
2822 $original_item["created"],
2825 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2827 $datarray["tag"] = $original_item["tag"];
2828 $datarray["app"] = $original_item["app"];
2830 $datarray["plink"] = self::plink($author, $guid);
2831 $datarray["private"] = (($public == "false") ? 1 : 0);
2832 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2834 $datarray["object-type"] = $original_item["object-type"];
2836 self::fetchGuid($datarray);
2837 $message_id = Item::insert($datarray);
2839 self::sendParticipation($contact, $datarray);
2842 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2843 if ($datarray['uid'] == 0) {
2844 Item::distribute($message_id);
2853 * @brief Processes retractions
2855 * @param array $importer Array of the importer user
2856 * @param array $contact The contact of the item owner
2857 * @param object $data The message object
2859 * @return bool success
2861 private static function itemRetraction($importer, $contact, $data)
2863 $author = notags(unxmlify($data->author));
2864 $target_guid = notags(unxmlify($data->target_guid));
2865 $target_type = notags(unxmlify($data->target_type));
2867 $person = self::personByHandle($author);
2868 if (!is_array($person)) {
2869 logger("unable to find author detail for ".$author);
2873 if (empty($contact["url"])) {
2874 $contact["url"] = $person["url"];
2877 // Fetch items that are about to be deleted
2878 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2880 // When we receive a public retraction, we delete every item that we find.
2881 if ($importer['uid'] == 0) {
2882 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2884 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2886 $r = dba::select('item', $fields, $condition);
2887 if (!DBM::is_result($r)) {
2888 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2892 while ($item = dba::fetch($r)) {
2893 // Fetch the parent item
2894 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2896 // Only delete it if the parent author really fits
2897 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2898 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2902 Item::deleteById($item["id"]);
2904 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2906 // Now check if the retraction needs to be relayed by us
2907 if ($parent["origin"]) {
2909 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2917 * @brief Receives retraction messages
2919 * @param array $importer Array of the importer user
2920 * @param string $sender The sender of the message
2921 * @param object $data The message object
2923 * @return bool Success
2925 private static function receiveRetraction($importer, $sender, $data)
2927 $target_type = notags(unxmlify($data->target_type));
2929 $contact = self::contactByHandle($importer["uid"], $sender);
2930 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2931 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2935 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2937 switch ($target_type) {
2942 case "StatusMessage":
2943 return self::itemRetraction($importer, $contact, $data);
2947 /// @todo What should we do with an "unshare"?
2948 // Removing the contact isn't correct since we still can read the public items
2949 Contact::remove($contact["id"]);
2953 logger("Unknown target type ".$target_type);
2960 * @brief Receives status messages
2962 * @param array $importer Array of the importer user
2963 * @param object $data The message object
2964 * @param string $xml The original XML of the message
2966 * @return int The message id of the newly created item
2968 private static function receiveStatusMessage($importer, $data, $xml)
2970 $author = notags(unxmlify($data->author));
2971 $guid = notags(unxmlify($data->guid));
2972 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2973 $public = notags(unxmlify($data->public));
2974 $text = unxmlify($data->text);
2975 $provider_display_name = notags(unxmlify($data->provider_display_name));
2977 $contact = self::allowedContactByHandle($importer, $author, false);
2982 $message_id = self::messageExists($importer["uid"], $guid);
2988 if ($data->location) {
2989 foreach ($data->location->children() as $fieldname => $data) {
2990 $address[$fieldname] = notags(unxmlify($data));
2994 $body = Markdown::toBBCode($text);
2998 // Attach embedded pictures to the body
3000 foreach ($data->photo as $photo) {
3001 $body = "[img]".unxmlify($photo->remote_photo_path).
3002 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
3005 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
3007 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
3009 // Add OEmbed and other information to the body
3010 if (!self::isRedmatrix($contact["url"])) {
3011 $body = add_page_info_to_body($body, false, true);
3015 /// @todo enable support for polls
3016 //if ($data->poll) {
3017 // foreach ($data->poll AS $poll)
3022 /// @todo enable support for events
3024 $datarray["uid"] = $importer["uid"];
3025 $datarray["contact-id"] = $contact["id"];
3026 $datarray["network"] = NETWORK_DIASPORA;
3028 $datarray["author-name"] = $contact["name"];
3029 $datarray["author-link"] = $contact["url"];
3030 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
3032 $datarray["owner-name"] = $datarray["author-name"];
3033 $datarray["owner-link"] = $datarray["author-link"];
3034 $datarray["owner-avatar"] = $datarray["author-avatar"];
3036 $datarray["guid"] = $guid;
3037 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3039 $datarray["verb"] = ACTIVITY_POST;
3040 $datarray["gravity"] = GRAVITY_PARENT;
3042 $datarray["protocol"] = PROTOCOL_DIASPORA;
3043 $datarray["source"] = $xml;
3045 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3047 if ($provider_display_name != "") {
3048 $datarray["app"] = $provider_display_name;
3051 $datarray["plink"] = self::plink($author, $guid);
3052 $datarray["private"] = (($public == "false") ? 1 : 0);
3053 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3055 if (isset($address["address"])) {
3056 $datarray["location"] = $address["address"];
3059 if (isset($address["lat"]) && isset($address["lng"])) {
3060 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3063 self::fetchGuid($datarray);
3064 $message_id = Item::insert($datarray);
3066 self::sendParticipation($contact, $datarray);
3069 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3070 if ($datarray['uid'] == 0) {
3071 Item::distribute($message_id);
3079 /* ************************************************************************************** *
3080 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3081 * ************************************************************************************** */
3084 * @brief returnes the handle of a contact
3086 * @param array $contact contact array
3088 * @return string the handle in the format user@domain.tld
3090 private static function myHandle($contact)
3092 if ($contact["addr"] != "") {
3093 return $contact["addr"];
3096 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3097 // So - just in case - we build the the address here.
3098 if ($contact["nickname"] != "") {
3099 $nick = $contact["nickname"];
3101 $nick = $contact["nick"];
3104 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3109 * @brief Creates the data for a private message in the new format
3111 * @param string $msg The message that is to be transmitted
3112 * @param array $user The record of the sender
3113 * @param array $contact Target of the communication
3114 * @param string $prvkey The private key of the sender
3115 * @param string $pubkey The public key of the receiver
3117 * @return string The encrypted data
3119 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3121 logger("Message: ".$msg, LOGGER_DATA);
3123 // without a public key nothing will work
3125 logger("pubkey missing: contact id: ".$contact["id"]);
3129 $aes_key = openssl_random_pseudo_bytes(32);
3130 $b_aes_key = base64_encode($aes_key);
3131 $iv = openssl_random_pseudo_bytes(16);
3132 $b_iv = base64_encode($iv);
3134 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3136 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3138 $encrypted_key_bundle = "";
3139 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3141 $json_object = json_encode(
3142 ["aes_key" => base64_encode($encrypted_key_bundle),
3143 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3146 return $json_object;
3150 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3152 * @param string $msg The message that is to be transmitted
3153 * @param array $user The record of the sender
3155 * @return string The envelope
3157 public static function buildMagicEnvelope($msg, $user)
3159 $b64url_data = base64url_encode($msg);
3160 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3162 $key_id = base64url_encode(self::myHandle($user));
3163 $type = "application/xml";
3164 $encoding = "base64url";
3165 $alg = "RSA-SHA256";
3166 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3168 // Fallback if the private key wasn't transmitted in the expected field
3169 if ($user['uprvkey'] == "") {
3170 $user['uprvkey'] = $user['prvkey'];
3173 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3174 $sig = base64url_encode($signature);
3176 $xmldata = ["me:env" => ["me:data" => $data,
3177 "@attributes" => ["type" => $type],
3178 "me:encoding" => $encoding,
3181 "@attributes2" => ["key_id" => $key_id]]];
3183 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3185 return XML::fromArray($xmldata, $xml, false, $namespaces);
3189 * @brief Create the envelope for a message
3191 * @param string $msg The message that is to be transmitted
3192 * @param array $user The record of the sender
3193 * @param array $contact Target of the communication
3194 * @param string $prvkey The private key of the sender
3195 * @param string $pubkey The public key of the receiver
3196 * @param bool $public Is the message public?
3198 * @return string The message that will be transmitted to other servers
3200 public static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3202 // The message is put into an envelope with the sender's signature
3203 $envelope = self::buildMagicEnvelope($msg, $user);
3205 // Private messages are put into a second envelope, encrypted with the receivers public key
3207 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3214 * @brief Creates a signature for a message
3216 * @param array $owner the array of the owner of the message
3217 * @param array $message The message that is to be signed
3219 * @return string The signature
3221 private static function signature($owner, $message)
3224 unset($sigmsg["author_signature"]);
3225 unset($sigmsg["parent_author_signature"]);
3227 $signed_text = implode(";", $sigmsg);
3229 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3233 * @brief Transmit a message to a target server
3235 * @param array $owner the array of the item owner
3236 * @param array $contact Target of the communication
3237 * @param string $envelope The message that is to be transmitted
3238 * @param bool $public_batch Is it a public post?
3239 * @param bool $queue_run Is the transmission called from the queue?
3240 * @param string $guid message guid
3242 * @return int Result of the transmission
3244 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3248 $enabled = intval(Config::get("system", "diaspora_enabled"));
3253 $logid = random_string(4);
3255 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3257 // We always try to use the data from the fcontact table.
3258 // This is important for transmitting data to Friendica servers.
3259 if (!empty($contact['addr'])) {
3260 $fcontact = self::personByHandle($contact['addr']);
3261 if (!empty($fcontact)) {
3262 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3267 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3271 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3273 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3276 if (!intval(Config::get("system", "diaspora_test"))) {
3277 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3279 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3280 $return_code = $a->get_curl_code();
3282 logger("test_mode");
3287 logger("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3289 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3290 if (!$no_queue && ($contact['contact-type'] != ACCOUNT_TYPE_RELAY)) {
3291 logger("queue message");
3292 // queue message for redelivery
3293 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3296 // The message could not be delivered. We mark the contact as "dead"
3297 Contact::markForArchival($contact);
3298 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3299 // We successfully delivered a message, the contact is alive
3300 Contact::unmarkForArchival($contact);
3303 return $return_code ? $return_code : -1;
3308 * @brief Build the post xml
3310 * @param string $type The message type
3311 * @param array $message The message data
3313 * @return string The post XML
3315 public static function buildPostXml($type, $message)
3317 $data = [$type => $message];
3319 return XML::fromArray($data, $xml);
3323 * @brief Builds and transmit messages
3325 * @param array $owner the array of the item owner
3326 * @param array $contact Target of the communication
3327 * @param string $type The message type
3328 * @param array $message The message data
3329 * @param bool $public_batch Is it a public post?
3330 * @param string $guid message guid
3331 * @param bool $spool Should the transmission be spooled or transmitted?
3333 * @return int Result of the transmission
3335 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3337 $msg = self::buildPostXml($type, $message);
3339 logger('message: '.$msg, LOGGER_DATA);
3340 logger('send guid '.$guid, LOGGER_DEBUG);
3342 // Fallback if the private key wasn't transmitted in the expected field
3343 if ($owner['uprvkey'] == "") {
3344 $owner['uprvkey'] = $owner['prvkey'];
3347 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3350 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3353 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3356 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3358 return $return_code;
3362 * @brief sends a participation (Used to get all further updates)
3364 * @param array $contact Target of the communication
3365 * @param array $item Item array
3367 * @return int The result of the transmission
3369 private static function sendParticipation($contact, $item)
3371 // Don't send notifications for private postings
3372 if ($item['private']) {
3376 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3378 $result = Cache::get($cachekey);
3379 if (!is_null($result)) {
3383 // Fetch some user id to have a valid handle to transmit the participation.
3384 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3385 // If the item belongs to a user, we take this user id.
3386 if ($item['uid'] == 0) {
3387 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3388 $first_user = dba::selectFirst('user', ['uid'], $condition);
3389 $owner = User::getOwnerDataById($first_user['uid']);
3391 $owner = User::getOwnerDataById($item['uid']);
3394 $author = self::myHandle($owner);
3396 $message = ["author" => $author,
3397 "guid" => get_guid(32),
3398 "parent_type" => "Post",
3399 "parent_guid" => $item["guid"]];
3401 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3403 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3404 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3406 return self::buildAndTransmit($owner, $contact, "participation", $message);
3410 * @brief sends an account migration
3412 * @param array $owner the array of the item owner
3413 * @param array $contact Target of the communication
3414 * @param int $uid User ID
3416 * @return int The result of the transmission
3418 public static function sendAccountMigration($owner, $contact, $uid)
3420 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3421 $profile = self::createProfileData($uid);
3423 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3424 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3426 $message = ["author" => $old_handle,
3427 "profile" => $profile,
3428 "signature" => $signature];
3430 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3432 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3436 * @brief Sends a "share" message
3438 * @param array $owner the array of the item owner
3439 * @param array $contact Target of the communication
3441 * @return int The result of the transmission
3443 public static function sendShare($owner, $contact)
3446 * @todo support the different possible combinations of "following" and "sharing"
3447 * Currently, Diaspora only interprets the "sharing" field
3449 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3453 switch ($contact["rel"]) {
3454 case CONTACT_IS_FRIEND:
3457 case CONTACT_IS_SHARING:
3460 case CONTACT_IS_FOLLOWER:
3466 $message = ["author" => self::myHandle($owner),
3467 "recipient" => $contact["addr"],
3468 "following" => "true",
3469 "sharing" => "true"];
3471 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3473 return self::buildAndTransmit($owner, $contact, "contact", $message);
3477 * @brief sends an "unshare"
3479 * @param array $owner the array of the item owner
3480 * @param array $contact Target of the communication
3482 * @return int The result of the transmission
3484 public static function sendUnshare($owner, $contact)
3486 $message = ["author" => self::myHandle($owner),
3487 "recipient" => $contact["addr"],
3488 "following" => "false",
3489 "sharing" => "false"];
3491 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3493 return self::buildAndTransmit($owner, $contact, "contact", $message);
3497 * @brief Checks a message body if it is a reshare
3499 * @param string $body The message body that is to be check
3500 * @param bool $complete Should it be a complete check or a simple check?
3502 * @return array|bool Reshare details or "false" if no reshare
3504 public static function isReshare($body, $complete = true)
3506 $body = trim($body);
3508 // Skip if it isn't a pure repeated messages
3509 // Does it start with a share?
3510 if ((strpos($body, "[share") > 0) && $complete) {
3514 // Does it end with a share?
3515 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3519 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3520 // Skip if there is no shared message in there
3521 if ($body == $attributes) {
3525 // If we don't do the complete check we quit here
3528 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3529 if ($matches[1] != "") {
3530 $guid = $matches[1];
3533 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3534 if ($matches[1] != "") {
3535 $guid = $matches[1];
3538 if (($guid != "") && $complete) {
3539 $condition = ['guid' => $guid, 'network' => [NETWORK_DFRN, NETWORK_DIASPORA]];
3540 $item = dba::selectFirst('item', ['contact-id'], $condition);
3541 if (DBM::is_result($item)) {
3543 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3544 $ret["root_guid"] = $guid;
3550 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3551 if ($matches[1] != "") {
3552 $profile = $matches[1];
3555 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3556 if ($matches[1] != "") {
3557 $profile = $matches[1];
3562 if ($profile != "") {
3563 if (Contact::getIdForURL($profile)) {
3564 $author = Contact::getDetailsByURL($profile);
3565 $ret["root_handle"] = $author['addr'];
3569 if (!empty($guid)) {
3570 $ret["root_guid"] = $guid;
3573 if (empty($ret) && !$complete) {
3581 * @brief Create an event array
3583 * @param integer $event_id The id of the event
3585 * @return array with event data
3587 private static function buildEvent($event_id)
3589 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3590 if (!DBM::is_result($r)) {
3598 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3599 if (!DBM::is_result($r)) {
3605 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3606 if (!DBM::is_result($r)) {
3612 $eventdata['author'] = self::myHandle($owner);
3614 if ($event['guid']) {
3615 $eventdata['guid'] = $event['guid'];
3618 $mask = DateTimeFormat::ATOM;
3620 /// @todo - establish "all day" events in Friendica
3621 $eventdata["all_day"] = "false";
3623 if (!$event['adjust']) {
3624 $eventdata['timezone'] = $user['timezone'];
3626 if ($eventdata['timezone'] == "") {
3627 $eventdata['timezone'] = 'UTC';
3631 if ($event['start']) {
3632 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3634 if ($event['finish'] && !$event['nofinish']) {
3635 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3637 if ($event['summary']) {
3638 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3640 if ($event['desc']) {
3641 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3643 if ($event['location']) {
3644 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3645 $coord = Map::getCoordinates($event['location']);
3648 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3649 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3650 $location["lat"] = $coord['lat'];
3651 $location["lng"] = $coord['lon'];
3653 $location["lat"] = 0;
3654 $location["lng"] = 0;
3656 $eventdata['location'] = $location;
3663 * @brief Create a post (status message or reshare)
3665 * @param array $item The item that will be exported
3666 * @param array $owner the array of the item owner
3669 * 'type' -> Message type ("status_message" or "reshare")
3670 * 'message' -> Array of XML elements of the status
3672 public static function buildStatus($item, $owner)
3674 $cachekey = "diaspora:buildStatus:".$item['guid'];
3676 $result = Cache::get($cachekey);
3677 if (!is_null($result)) {
3681 $myaddr = self::myHandle($owner);
3683 $public = (($item["private"]) ? "false" : "true");
3685 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3687 // Detect a share element and do a reshare
3688 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3689 $message = ["author" => $myaddr,
3690 "guid" => $item["guid"],
3691 "created_at" => $created,
3692 "root_author" => $ret["root_handle"],
3693 "root_guid" => $ret["root_guid"],
3694 "provider_display_name" => $item["app"],
3695 "public" => $public];
3699 $title = $item["title"];
3700 $body = $item["body"];
3702 if ($item['author-link'] != $item['owner-link']) {
3703 require_once 'mod/share.php';
3704 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3705 "", $item['created'], $item['plink']) . $body . '[/share]';
3708 // convert to markdown
3709 $body = html_entity_decode(BBCode::toMarkdown($body));
3712 if (strlen($title)) {
3713 $body = "## ".html_entity_decode($title)."\n\n".$body;
3716 if ($item["attach"]) {
3717 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3719 $body .= "\n".L10n::t("Attachments:")."\n";
3720 foreach ($matches as $mtch) {
3721 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3728 if ($item["location"] != "")
3729 $location["address"] = $item["location"];
3731 if ($item["coord"] != "") {
3732 $coord = explode(" ", $item["coord"]);
3733 $location["lat"] = $coord[0];
3734 $location["lng"] = $coord[1];
3737 $message = ["author" => $myaddr,
3738 "guid" => $item["guid"],
3739 "created_at" => $created,
3740 "public" => $public,
3742 "provider_display_name" => $item["app"],
3743 "location" => $location];
3745 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3746 if (!isset($location["lat"]) || !isset($location["lng"])) {
3747 unset($message["location"]);
3750 if ($item['event-id'] > 0) {
3751 $event = self::buildEvent($item['event-id']);
3752 if (count($event)) {
3753 $message['event'] = $event;
3755 if (!empty($event['location']['address']) &&
3756 !empty($event['location']['lat']) &&
3757 !empty($event['location']['lng'])) {
3758 $message['location'] = $event['location'];
3761 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3762 // $message['text'] = '';
3766 $type = "status_message";
3769 $msg = ["type" => $type, "message" => $message];
3771 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3777 * @brief Sends a post
3779 * @param array $item The item that will be exported
3780 * @param array $owner the array of the item owner
3781 * @param array $contact Target of the communication
3782 * @param bool $public_batch Is it a public post?
3784 * @return int The result of the transmission
3786 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3788 $status = self::buildStatus($item, $owner);
3790 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3794 * @brief Creates a "like" object
3796 * @param array $item The item that will be exported
3797 * @param array $owner the array of the item owner
3799 * @return array The data for a "like"
3801 private static function constructLike($item, $owner)
3804 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3805 dbesc($item["thr-parent"])
3807 if (!DBM::is_result($p)) {
3813 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3815 if ($item['verb'] === ACTIVITY_LIKE) {
3817 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3818 $positive = "false";
3821 return(["author" => self::myHandle($owner),
3822 "guid" => $item["guid"],
3823 "parent_guid" => $parent["guid"],
3824 "parent_type" => $target_type,
3825 "positive" => $positive,
3826 "author_signature" => ""]);
3830 * @brief Creates an "EventParticipation" object
3832 * @param array $item The item that will be exported
3833 * @param array $owner the array of the item owner
3835 * @return array The data for an "EventParticipation"
3837 private static function constructAttend($item, $owner)
3840 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3841 dbesc($item["thr-parent"])
3843 if (!DBM::is_result($p)) {
3849 switch ($item['verb']) {
3850 case ACTIVITY_ATTEND:
3851 $attend_answer = 'accepted';
3853 case ACTIVITY_ATTENDNO:
3854 $attend_answer = 'declined';
3856 case ACTIVITY_ATTENDMAYBE:
3857 $attend_answer = 'tentative';
3860 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3864 return(["author" => self::myHandle($owner),
3865 "guid" => $item["guid"],
3866 "parent_guid" => $parent["guid"],
3867 "status" => $attend_answer,
3868 "author_signature" => ""]);
3872 * @brief Creates the object for a comment
3874 * @param array $item The item that will be exported
3875 * @param array $owner the array of the item owner
3877 * @return array The data for a comment
3879 private static function constructComment($item, $owner)
3881 $cachekey = "diaspora:constructComment:".$item['guid'];
3883 $result = Cache::get($cachekey);
3884 if (!is_null($result)) {
3889 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3890 intval($item["parent"]),
3891 intval($item["parent"])
3894 if (!DBM::is_result($p)) {
3900 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3901 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3903 $comment = ["author" => self::myHandle($owner),
3904 "guid" => $item["guid"],
3905 "created_at" => $created,
3906 "parent_guid" => $parent["guid"],
3908 "author_signature" => ""];
3910 // Send the thread parent guid only if it is a threaded comment
3911 if ($item['thr-parent'] != $item['parent-uri']) {
3912 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3915 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3921 * @brief Send a like or a comment
3923 * @param array $item The item that will be exported
3924 * @param array $owner the array of the item owner
3925 * @param array $contact Target of the communication
3926 * @param bool $public_batch Is it a public post?
3928 * @return int The result of the transmission
3930 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3932 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3933 $message = self::constructAttend($item, $owner);
3934 $type = "event_participation";
3935 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3936 $message = self::constructLike($item, $owner);
3939 $message = self::constructComment($item, $owner);
3947 $message["author_signature"] = self::signature($owner, $message);
3949 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3953 * @brief Creates a message from a signature record entry
3955 * @param array $item The item that will be exported
3956 * @param array $signature The entry of the "sign" record
3958 * @return string The message
3960 private static function messageFromSignature($item, $signature)
3962 // Split the signed text
3963 $signed_parts = explode(";", $signature['signed_text']);
3965 if ($item["deleted"]) {
3966 $message = ["author" => $signature['signer'],
3967 "target_guid" => $signed_parts[0],
3968 "target_type" => $signed_parts[1]];
3969 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3970 $message = ["author" => $signed_parts[4],
3971 "guid" => $signed_parts[1],
3972 "parent_guid" => $signed_parts[3],
3973 "parent_type" => $signed_parts[2],
3974 "positive" => $signed_parts[0],
3975 "author_signature" => $signature['signature'],
3976 "parent_author_signature" => ""];
3978 // Remove the comment guid
3979 $guid = array_shift($signed_parts);
3981 // Remove the parent guid
3982 $parent_guid = array_shift($signed_parts);
3984 // Remove the handle
3985 $handle = array_pop($signed_parts);
3987 // Glue the parts together
3988 $text = implode(";", $signed_parts);
3990 $message = ["author" => $handle,
3992 "parent_guid" => $parent_guid,
3993 "text" => implode(";", $signed_parts),
3994 "author_signature" => $signature['signature'],
3995 "parent_author_signature" => ""];
4001 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
4003 * @param array $item The item that will be exported
4004 * @param array $owner the array of the item owner
4005 * @param array $contact Target of the communication
4006 * @param bool $public_batch Is it a public post?
4008 * @return int The result of the transmission
4010 public static function sendRelay($item, $owner, $contact, $public_batch = false)
4012 if ($item["deleted"]) {
4013 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
4014 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4020 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4022 // fetch the original signature
4025 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
4030 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4036 // Old way - is used by the internal Friendica functions
4037 /// @todo Change all signatur storing functions to the new format
4038 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
4039 $message = self::messageFromSignature($item, $signature);
4041 $msg = json_decode($signature['signed_text'], true);
4044 if (is_array($msg)) {
4045 foreach ($msg as $field => $data) {
4046 if (!$item["deleted"]) {
4047 if ($field == "diaspora_handle") {
4050 if ($field == "target_type") {
4051 $field = "parent_type";
4055 $message[$field] = $data;
4058 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4062 $message["parent_author_signature"] = self::signature($owner, $message);
4064 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4066 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4070 * @brief Sends a retraction (deletion) of a message, like or comment
4072 * @param array $item The item that will be exported
4073 * @param array $owner the array of the item owner
4074 * @param array $contact Target of the communication
4075 * @param bool $public_batch Is it a public post?
4076 * @param bool $relay Is the retraction transmitted from a relay?
4078 * @return int The result of the transmission
4080 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4082 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4084 $msg_type = "retraction";
4086 if ($item['id'] == $item['parent']) {
4087 $target_type = "Post";
4088 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4089 $target_type = "Like";
4091 $target_type = "Comment";
4094 $message = ["author" => $itemaddr,
4095 "target_guid" => $item['guid'],
4096 "target_type" => $target_type];
4098 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4100 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4104 * @brief Sends a mail
4106 * @param array $item The item that will be exported
4107 * @param array $owner The owner
4108 * @param array $contact Target of the communication
4110 * @return int The result of the transmission
4112 public static function sendMail($item, $owner, $contact)
4114 $myaddr = self::myHandle($owner);
4117 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4118 intval($item["convid"]),
4119 intval($item["uid"])
4122 if (!DBM::is_result($r)) {
4123 logger("conversation not found.");
4129 "author" => $cnv["creator"],
4130 "guid" => $cnv["guid"],
4131 "subject" => $cnv["subject"],
4132 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4133 "participants" => $cnv["recips"]
4136 $body = BBCode::toMarkdown($item["body"]);
4137 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4140 "author" => $myaddr,
4141 "guid" => $item["guid"],
4142 "conversation_guid" => $cnv["guid"],
4144 "created_at" => $created,
4147 if ($item["reply"]) {
4152 "author" => $cnv["creator"],
4153 "guid" => $cnv["guid"],
4154 "subject" => $cnv["subject"],
4155 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4156 "participants" => $cnv["recips"],
4159 $type = "conversation";
4162 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4166 * @brief Split a name into first name and last name
4168 * @param string $name The name
4170 * @return array The array with "first" and "last"
4172 public static function splitName($name) {
4173 $name = trim($name);
4175 // Is the name longer than 64 characters? Then cut the rest of it.
4176 if (strlen($name) > 64) {
4177 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4178 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4180 $name = substr($name, 0, 64);
4184 // Take the first word as first name
4185 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4186 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4187 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4188 return ['first' => $first, 'last' => $last];
4191 // Take the last word as last name
4192 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4193 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4195 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4196 return ['first' => $first, 'last' => $last];
4199 // Take the first 32 characters if there is no space in the first 32 characters
4200 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4201 $first = substr($name, 0, 32);
4202 $last = substr($name, 32);
4203 return ['first' => $first, 'last' => $last];
4206 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4207 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4209 // Check if the last name is longer than 32 characters
4210 if (strlen($last) > 32) {
4211 if (strpos($last, ' ') <= 32) {
4212 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4214 $last = substr($last, 0, 32);
4218 return ['first' => $first, 'last' => $last];
4222 * @brief Create profile data
4224 * @param int $uid The user id
4226 * @return array The profile data
4228 private static function createProfileData($uid)
4231 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4233 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4234 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4235 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4244 $handle = $profile["addr"];
4246 $split_name = self::splitName($profile['name']);
4247 $first = $split_name['first'];
4248 $last = $split_name['last'];
4250 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4251 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4252 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4253 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4259 if ($searchable === 'true') {
4262 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4263 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4267 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4270 $about = $profile['about'];
4271 $about = strip_tags(BBCode::convert($about));
4273 $location = Profile::formatLocation($profile);
4275 if ($profile['pub_keywords']) {
4276 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4277 $kw = str_replace(' ', ' ', $kw);
4278 $arr = explode(' ', $profile['pub_keywords']);
4280 for ($x = 0; $x < 5; $x ++) {
4281 if (trim($arr[$x])) {
4282 $tags .= '#'. trim($arr[$x]) .' ';
4287 $tags = trim($tags);
4290 return ["author" => $handle,
4291 "first_name" => $first,
4292 "last_name" => $last,
4293 "image_url" => $large,
4294 "image_url_medium" => $medium,
4295 "image_url_small" => $small,
4297 "gender" => $profile['gender'],
4299 "location" => $location,
4300 "searchable" => $searchable,
4302 "tag_string" => $tags];
4306 * @brief Sends profile data
4308 * @param int $uid The user id
4309 * @param bool $recips optional, default false
4312 public static function sendProfile($uid, $recips = false)
4318 $owner = User::getOwnerDataById($uid);
4325 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4326 AND `uid` = %d AND `rel` != %d",
4327 dbesc(NETWORK_DIASPORA),
4329 intval(CONTACT_IS_SHARING)
4337 $message = self::createProfileData($uid);
4339 foreach ($recips as $recip) {
4340 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4341 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4346 * @brief Stores the signature for likes that are created on our system
4348 * @param array $contact The contact array of the "like"
4349 * @param int $post_id The post id of the "like"
4351 * @return bool Success
4353 public static function storeLikeSignature($contact, $post_id)
4355 // Is the contact the owner? Then fetch the private key
4356 if (!$contact['self'] || ($contact['uid'] == 0)) {
4357 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4361 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4362 if (!DBM::is_result($r)) {
4366 $contact["uprvkey"] = $r[0]['prvkey'];
4368 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4369 if (!DBM::is_result($r)) {
4373 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4377 $message = self::constructLike($r[0], $contact);
4378 if ($message === false) {
4382 $message["author_signature"] = self::signature($contact, $message);
4385 * Now store the signature more flexible to dynamically support new fields.
4386 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4388 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4390 logger('Stored diaspora like signature');
4395 * @brief Stores the signature for comments that are created on our system
4397 * @param array $item The item array of the comment
4398 * @param array $contact The contact array of the item owner
4399 * @param string $uprvkey The private key of the sender
4400 * @param int $message_id The message id of the comment
4402 * @return bool Success
4404 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4406 if ($uprvkey == "") {
4407 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4411 $contact["uprvkey"] = $uprvkey;
4413 $message = self::constructComment($item, $contact);
4414 if ($message === false) {
4418 $message["author_signature"] = self::signature($contact, $message);
4421 * Now store the signature more flexible to dynamically support new fields.
4422 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4424 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4426 logger('Stored diaspora comment signature');