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\Logger;
19 use Friendica\Core\PConfig;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\System;
22 use Friendica\Core\Worker;
23 use Friendica\Database\DBA;
24 use Friendica\Model\Contact;
25 use Friendica\Model\Conversation;
26 use Friendica\Model\GContact;
27 use Friendica\Model\Group;
28 use Friendica\Model\Item;
29 use Friendica\Model\Profile;
30 use Friendica\Model\Queue;
31 use Friendica\Model\User;
32 use Friendica\Network\Probe;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Map;
36 use Friendica\Util\Network;
37 use Friendica\Util\Strings;
38 use Friendica\Util\XML;
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
56 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
58 public static function relayList($item_id, array $contacts = [])
62 // Fetching relay servers
63 $serverdata = Config::get("system", "relay_server");
65 if (!empty($serverdata)) {
66 $servers = explode(",", $serverdata);
67 foreach ($servers as $server) {
68 $serverlist[$server] = trim($server);
72 if (Config::get("system", "relay_directly", false)) {
73 // We distribute our stuff based on the parent to ensure that the thread will be complete
74 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
75 if (!DBA::isResult($parent)) {
79 // Servers that want to get all content
80 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
81 while ($server = DBA::fetch($servers)) {
82 $serverlist[$server['url']] = $server['url'];
85 // All tags of the current post
86 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
87 $tags = DBA::select('term', ['term'], $condition);
89 while ($tag = DBA::fetch($tags)) {
90 $taglist[] = $tag['term'];
93 // All servers who wants content with this tag
95 if (!empty($taglist)) {
96 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
97 while ($server = DBA::fetch($tagserver)) {
98 $tagserverlist[] = $server['gserver-id'];
102 // All adresses with the given id
103 if (!empty($tagserverlist)) {
104 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
105 while ($server = DBA::fetch($servers)) {
106 $serverlist[$server['url']] = $server['url'];
111 // Now we are collecting all relay contacts
112 foreach ($serverlist as $server_url) {
113 // We don't send messages to ourselves
114 if (Strings::compareLink($server_url, System::baseUrl())) {
117 $contact = self::getRelayContact($server_url);
118 if (is_bool($contact)) {
123 foreach ($contacts as $entry) {
124 if ($entry['batch'] == $contact['batch']) {
130 $contacts[] = $contact;
138 * @brief Return a contact for a given server address or creates a dummy entry
140 * @param string $server_url The url of the server
141 * @return array with the contact
144 private static function getRelayContact($server_url)
146 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
148 // Fetch the relay contact
149 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
150 'contact-type' => Contact::TYPE_RELAY];
151 $contact = DBA::selectFirst('contact', $fields, $condition);
153 if (DBA::isResult($contact)) {
154 if ($contact['archive'] || $contact['blocked']) {
159 self::setRelayContact($server_url);
161 $contact = DBA::selectFirst('contact', $fields, $condition);
162 if (DBA::isResult($contact)) {
167 // It should never happen that we arrive here
172 * @brief Update or insert a relay contact
174 * @param string $server_url The url of the server
175 * @param array $network_fields Optional network specific fields
178 public static function setRelayContact($server_url, array $network_fields = [])
180 $fields = ['created' => DateTimeFormat::utcNow(),
181 'name' => 'relay', 'nick' => 'relay',
182 'url' => $server_url, 'network' => Protocol::DIASPORA,
183 'batch' => $server_url . '/receive/public',
184 'rel' => Contact::FOLLOWER, 'blocked' => false,
185 'pending' => false, 'writable' => true];
187 $fields = array_merge($fields, $network_fields);
189 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
190 'contact-type' => Contact::TYPE_RELAY];
192 if (DBA::exists('contact', $condition)) {
193 unset($fields['created']);
196 DBA::update('contact', $fields, $condition, true);
200 * @brief Return a list of participating contacts for a thread
202 * This is used for the participation feature.
203 * One of the parameters is a contact array.
204 * This is done to avoid duplicates.
206 * @param integer $thread The id of the thread
207 * @param array $contacts The previously fetched contacts
209 * @return array of relay servers
212 public static function participantsForThread($thread, array $contacts)
214 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
215 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
216 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
217 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
218 WHERE `participation`.`iid` = ?", $thread);
220 while ($contact = DBA::fetch($r)) {
221 if (!empty($contact['fnetwork'])) {
222 $contact['network'] = $contact['fnetwork'];
224 unset($contact['fnetwork']);
226 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
227 $contact['batch'] = $contact['fbatch'];
229 unset($contact['fbatch']);
232 foreach ($contacts as $entry) {
233 if ($entry['batch'] == $contact['batch']) {
239 $contacts[] = $contact;
248 * @brief repairs a signature that was double encoded
250 * The function is unused at the moment. It was copied from the old implementation.
252 * @param string $signature The signature
253 * @param string $handle The handle of the signature owner
254 * @param integer $level This value is only set inside this function to avoid endless loops
256 * @return string the repaired signature
259 private static function repairSignature($signature, $handle = "", $level = 1)
261 if ($signature == "") {
265 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
266 $signature = base64_decode($signature);
267 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
269 // Do a recursive call to be able to fix even multiple levels
271 $signature = self::repairSignature($signature, $handle, ++$level);
279 * @brief verify the envelope and return the verified data
281 * @param string $envelope The magic envelope
283 * @return string verified data
284 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
285 * @throws \ImagickException
287 private static function verifyMagicEnvelope($envelope)
289 $basedom = XML::parseString($envelope);
291 if (!is_object($basedom)) {
292 Logger::log("Envelope is no XML file");
296 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
298 if (sizeof($children) == 0) {
299 Logger::log("XML has no children");
305 $data = Strings::base64UrlDecode($children->data);
306 $type = $children->data->attributes()->type[0];
308 $encoding = $children->encoding;
310 $alg = $children->alg;
312 $sig = Strings::base64UrlDecode($children->sig);
313 $key_id = $children->sig->attributes()->key_id[0];
315 $handle = Strings::base64UrlDecode($key_id);
318 $b64url_data = Strings::base64UrlEncode($data);
319 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
321 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
324 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
328 $key = self::key($handle);
330 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
334 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
336 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
344 * @brief encrypts data via AES
346 * @param string $key The AES key
347 * @param string $iv The IV (is used for CBC encoding)
348 * @param string $data The data that is to be encrypted
350 * @return string encrypted data
352 private static function aesEncrypt($key, $iv, $data)
354 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
358 * @brief decrypts data via AES
360 * @param string $key The AES key
361 * @param string $iv The IV (is used for CBC encoding)
362 * @param string $encrypted The encrypted data
364 * @return string decrypted data
366 private static function aesDecrypt($key, $iv, $encrypted)
368 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
372 * @brief: Decodes incoming Diaspora message in the new format
374 * @param array $importer Array of the importer user
375 * @param string $raw raw post message
376 * @param boolean $no_exit Don't do an http exit on error
379 * 'message' -> decoded Diaspora XML message
380 * 'author' -> author diaspora handle
381 * 'key' -> author public key (converted to pkcs#8)
382 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
383 * @throws \ImagickException
385 public static function decodeRaw(array $importer, $raw, $no_exit = false)
387 $data = json_decode($raw);
389 // Is it a private post? Then decrypt the outer Salmon
390 if (is_object($data)) {
391 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
392 $ciphertext = base64_decode($data->encrypted_magic_envelope);
394 $outer_key_bundle = '';
395 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
396 $j_outer_key_bundle = json_decode($outer_key_bundle);
398 if (!is_object($j_outer_key_bundle)) {
399 Logger::log('Outer Salmon did not verify. Discarding.');
403 System::httpExit(400);
407 $outer_iv = base64_decode($j_outer_key_bundle->iv);
408 $outer_key = base64_decode($j_outer_key_bundle->key);
410 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
415 $basedom = XML::parseString($xml);
417 if (!is_object($basedom)) {
418 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
422 System::httpExit(400);
426 $base = $basedom->children(NAMESPACE_SALMON_ME);
428 // Not sure if this cleaning is needed
429 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
431 // Build the signed data
432 $type = $base->data[0]->attributes()->type[0];
433 $encoding = $base->encoding;
435 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
437 // This is the signature
438 $signature = Strings::base64UrlDecode($base->sig);
440 // Get the senders' public key
441 $key_id = $base->sig[0]->attributes()->key_id[0];
442 $author_addr = base64_decode($key_id);
443 if ($author_addr == '') {
444 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
448 System::httpExit(400);
452 $key = self::key($author_addr);
454 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
458 System::httpExit(400);
462 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
464 Logger::log('Message did not verify. Discarding.');
468 System::httpExit(400);
472 return ['message' => (string)Strings::base64UrlDecode($base->data),
473 'author' => XML::unescape($author_addr),
474 'key' => (string)$key];
478 * @brief: Decodes incoming Diaspora message in the deprecated format
480 * @param array $importer Array of the importer user
481 * @param string $xml urldecoded Diaspora salmon
484 * 'message' -> decoded Diaspora XML message
485 * 'author' -> author diaspora handle
486 * 'key' -> author public key (converted to pkcs#8)
487 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
488 * @throws \ImagickException
490 public static function decode(array $importer, $xml)
493 $basedom = XML::parseString($xml);
495 if (!is_object($basedom)) {
496 Logger::log("XML is not parseable.");
499 $children = $basedom->children('https://joindiaspora.com/protocol');
501 $inner_aes_key = null;
504 if ($children->header) {
506 $author_link = str_replace('acct:', '', $children->header->author_id);
508 // This happens with posts from a relais
510 Logger::log("This is no private post in the old format", Logger::DEBUG);
514 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
516 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
517 $ciphertext = base64_decode($encrypted_header->ciphertext);
519 $outer_key_bundle = '';
520 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
522 $j_outer_key_bundle = json_decode($outer_key_bundle);
524 $outer_iv = base64_decode($j_outer_key_bundle->iv);
525 $outer_key = base64_decode($j_outer_key_bundle->key);
527 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
529 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
530 $idom = XML::parseString($decrypted);
532 $inner_iv = base64_decode($idom->iv);
533 $inner_aes_key = base64_decode($idom->aes_key);
535 $author_link = str_replace('acct:', '', $idom->author_id);
538 $dom = $basedom->children(NAMESPACE_SALMON_ME);
540 // figure out where in the DOM tree our data is hiding
543 if ($dom->provenance->data) {
544 $base = $dom->provenance;
545 } elseif ($dom->env->data) {
547 } elseif ($dom->data) {
552 Logger::log('unable to locate salmon data in xml');
553 System::httpExit(400);
557 // Stash the signature away for now. We have to find their key or it won't be good for anything.
558 $signature = Strings::base64UrlDecode($base->sig);
562 // strip whitespace so our data element will return to one big base64 blob
563 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
566 // stash away some other stuff for later
568 $type = $base->data[0]->attributes()->type[0];
569 $keyhash = $base->sig[0]->attributes()->keyhash[0];
570 $encoding = $base->encoding;
574 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
578 $data = Strings::base64UrlDecode($data);
582 $inner_decrypted = $data;
584 // Decode the encrypted blob
585 $inner_encrypted = base64_decode($data);
586 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
590 Logger::log('Could not retrieve author URI.');
591 System::httpExit(400);
593 // Once we have the author URI, go to the web and try to find their public key
594 // (first this will look it up locally if it is in the fcontact cache)
595 // This will also convert diaspora public key from pkcs#1 to pkcs#8
597 Logger::log('Fetching key for '.$author_link);
598 $key = self::key($author_link);
601 Logger::log('Could not retrieve author key.');
602 System::httpExit(400);
605 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
608 Logger::log('Message did not verify. Discarding.');
609 System::httpExit(400);
612 Logger::log('Message verified.');
614 return ['message' => (string)$inner_decrypted,
615 'author' => XML::unescape($author_link),
616 'key' => (string)$key];
621 * @brief Dispatches public messages and find the fitting receivers
623 * @param array $msg The post that will be dispatched
625 * @return int The message id of the generated message, "true" or "false" if there was an error
626 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
627 * @throws \ImagickException
629 public static function dispatchPublic($msg)
631 $enabled = intval(Config::get("system", "diaspora_enabled"));
633 Logger::log("diaspora is disabled");
637 if (!($fields = self::validPosting($msg))) {
638 Logger::log("Invalid posting");
642 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
643 $success = self::dispatch($importer, $msg, $fields);
649 * @brief Dispatches the different message types to the different functions
651 * @param array $importer Array of the importer user
652 * @param array $msg The post that will be dispatched
653 * @param SimpleXMLElement $fields SimpleXML object that contains the message
655 * @return int The message id of the generated message, "true" or "false" if there was an error
656 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
657 * @throws \ImagickException
659 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
661 // The sender is the handle of the contact that sent the message.
662 // This will often be different with relayed messages (for example "like" and "comment")
663 $sender = $msg["author"];
665 // This is only needed for private postings since this is already done for public ones before
666 if (is_null($fields)) {
668 if (!($fields = self::validPosting($msg))) {
669 Logger::log("Invalid posting");
676 $type = $fields->getName();
678 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
681 case "account_migration":
683 Logger::log('Message with type ' . $type . ' is not private, quitting.');
686 return self::receiveAccountMigration($importer, $fields);
688 case "account_deletion":
689 return self::receiveAccountDeletion($fields);
692 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
696 Logger::log('Message with type ' . $type . ' is not private, quitting.');
699 return self::receiveContactRequest($importer, $fields);
703 Logger::log('Message with type ' . $type . ' is not private, quitting.');
706 return self::receiveConversation($importer, $msg, $fields);
709 return self::receiveLike($importer, $sender, $fields);
713 Logger::log('Message with type ' . $type . ' is not private, quitting.');
716 return self::receiveMessage($importer, $fields);
718 case "participation":
720 Logger::log('Message with type ' . $type . ' is not private, quitting.');
723 return self::receiveParticipation($importer, $fields);
725 case "photo": // Not implemented
726 return self::receivePhoto($importer, $fields);
728 case "poll_participation": // Not implemented
729 return self::receivePollParticipation($importer, $fields);
733 Logger::log('Message with type ' . $type . ' is not private, quitting.');
736 return self::receiveProfile($importer, $fields);
739 return self::receiveReshare($importer, $fields, $msg["message"]);
742 return self::receiveRetraction($importer, $sender, $fields);
744 case "status_message":
745 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
748 Logger::log("Unknown message type ".$type);
754 * @brief Checks if a posting is valid and fetches the data fields.
756 * This function does not only check the signature.
757 * It also does the conversion between the old and the new diaspora format.
759 * @param array $msg Array with the XML, the sender handle and the sender signature
761 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
762 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
763 * @throws \ImagickException
765 private static function validPosting($msg)
767 $data = XML::parseString($msg["message"]);
769 if (!is_object($data)) {
770 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
774 // Is this the new or the old version?
775 if ($data->getName() == "XML") {
777 foreach ($data->post->children() as $child) {
785 $type = $element->getName();
788 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
790 // All retractions are handled identically from now on.
791 // In the new version there will only be "retraction".
792 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
793 $type = "retraction";
795 if ($type == "request") {
799 $fields = new SimpleXMLElement("<".$type."/>");
802 $author_signature = null;
803 $parent_author_signature = null;
805 foreach ($element->children() as $fieldname => $entry) {
807 // Translation for the old XML structure
808 if ($fieldname == "diaspora_handle") {
809 $fieldname = "author";
811 if ($fieldname == "participant_handles") {
812 $fieldname = "participants";
814 if (in_array($type, ["like", "participation"])) {
815 if ($fieldname == "target_type") {
816 $fieldname = "parent_type";
819 if ($fieldname == "sender_handle") {
820 $fieldname = "author";
822 if ($fieldname == "recipient_handle") {
823 $fieldname = "recipient";
825 if ($fieldname == "root_diaspora_id") {
826 $fieldname = "root_author";
828 if ($type == "status_message") {
829 if ($fieldname == "raw_message") {
833 if ($type == "retraction") {
834 if ($fieldname == "post_guid") {
835 $fieldname = "target_guid";
837 if ($fieldname == "type") {
838 $fieldname = "target_type";
843 if (($fieldname == "author_signature") && ($entry != "")) {
844 $author_signature = base64_decode($entry);
845 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
846 $parent_author_signature = base64_decode($entry);
847 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
848 if ($signed_data != "") {
852 $signed_data .= $entry;
854 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
855 || ($orig_type == "relayable_retraction")
857 XML::copy($entry, $fields, $fieldname);
861 // This is something that shouldn't happen at all.
862 if (in_array($type, ["status_message", "reshare", "profile"])) {
863 if ($msg["author"] != $fields->author) {
864 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
869 // Only some message types have signatures. So we quit here for the other types.
870 if (!in_array($type, ["comment", "like"])) {
873 // No author_signature? This is a must, so we quit.
874 if (!isset($author_signature)) {
875 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
879 if (isset($parent_author_signature)) {
880 $key = self::key($msg["author"]);
882 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
886 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
887 Logger::log("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);
892 $key = self::key($fields->author);
894 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
898 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
899 Logger::log("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, Logger::DEBUG);
907 * @brief Fetches the public key for a given handle
909 * @param string $handle The handle
911 * @return string The public key
912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
913 * @throws \ImagickException
915 private static function key($handle)
917 $handle = strval($handle);
919 Logger::log("Fetching diaspora key for: ".$handle);
921 $r = self::personByHandle($handle);
930 * @brief Fetches data for a given handle
932 * @param string $handle The handle
934 * @return array the queried data
935 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
936 * @throws \ImagickException
938 public static function personByHandle($handle)
942 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
943 if (DBA::isResult($person)) {
944 Logger::log("In cache " . print_r($person, true), Logger::DEBUG);
946 // update record occasionally so it doesn't get stale
947 $d = strtotime($person["updated"]." +00:00");
948 if ($d < strtotime("now - 14 days")) {
952 if ($person["guid"] == "") {
957 if (!DBA::isResult($person) || $update) {
958 Logger::log("create or refresh", Logger::DEBUG);
959 $r = Probe::uri($handle, Protocol::DIASPORA);
961 // Note that Friendica contacts will return a "Diaspora person"
962 // if Diaspora connectivity is enabled on their server
963 if ($r && ($r["network"] === Protocol::DIASPORA)) {
964 self::updateFContact($r);
966 // Fetch the updated or added contact
967 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
968 if (!DBA::isResult($person)) {
979 * @brief Updates the fcontact table
981 * @param array $arr The fcontact data
984 private static function updateFContact($arr)
986 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
987 'request' => $arr["request"], 'nick' => $arr["nick"],
988 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
989 'batch' => $arr["batch"], 'notify' => $arr["notify"],
990 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
991 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
992 'updated' => DateTimeFormat::utcNow()];
994 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
996 DBA::update('fcontact', $fields, $condition, true);
1000 * @brief get a handle (user@domain.tld) from a given contact id
1002 * @param int $contact_id The id in the contact table
1003 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1005 * @return string the handle
1006 * @throws \Exception
1008 private static function handleFromContact($contact_id, $pcontact_id = 0)
1012 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1014 if ($pcontact_id != 0) {
1015 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1017 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1018 return strtolower($contact["addr"]);
1023 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1027 if (DBA::isResult($r)) {
1030 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1032 if ($contact['addr'] != "") {
1033 $handle = $contact['addr'];
1035 $baseurl_start = strpos($contact['url'], '://') + 3;
1036 // allows installations in a subdirectory--not sure how Diaspora will handle
1037 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1038 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1039 $handle = $contact['nick'].'@'.$baseurl;
1043 return strtolower($handle);
1047 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1050 * @param mixed $fcontact_guid Hexadecimal string guid
1052 * @return string the contact url or null
1053 * @throws \Exception
1055 public static function urlFromContactGuid($fcontact_guid)
1057 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1060 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1061 DBA::escape(Protocol::DIASPORA),
1062 DBA::escape($fcontact_guid)
1065 if (DBA::isResult($r)) {
1066 return $r[0]['url'];
1073 * @brief Get a contact id for a given handle
1075 * @todo Move to Friendica\Model\Contact
1077 * @param int $uid The user id
1078 * @param string $handle The handle in the format user@domain.tld
1080 * @return array Contact data
1081 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1082 * @throws \ImagickException
1084 private static function contactByHandle($uid, $handle)
1086 $cid = Contact::getIdForURL($handle, $uid);
1088 $handle_parts = explode("@", $handle);
1089 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1090 $cid = Contact::getIdForURL($nurl_sql, $uid);
1094 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1098 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1099 if (!DBA::isResult($contact)) {
1100 // This here shouldn't happen at all
1101 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1109 * @brief Check if posting is allowed for this contact
1111 * @param array $importer Array of the importer user
1112 * @param array $contact The contact that is checked
1113 * @param bool $is_comment Is the check for a comment?
1115 * @return bool is the contact allowed to post?
1117 private static function postAllow(array $importer, array $contact, $is_comment = false)
1120 * Perhaps we were already sharing with this person. Now they're sharing with us.
1121 * That makes us friends.
1122 * Normally this should have handled by getting a request - but this could get lost
1124 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1125 // It is not removed by now. Possibly the code is needed?
1126 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1129 // array('rel' => Contact::FRIEND, 'writable' => true),
1130 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1133 // $contact["rel"] = Contact::FRIEND;
1134 // Logger::log("defining user ".$contact["nick"]." as friend");
1137 // We don't seem to like that person
1138 if ($contact["blocked"]) {
1139 // Maybe blocked, don't accept.
1141 // We are following this person?
1142 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1143 // Yes, then it is fine.
1145 // Is it a post to a community?
1146 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1149 // Is the message a global user or a comment?
1150 } elseif (($importer["uid"] == 0) || $is_comment) {
1151 // Messages for the global users and comments are always accepted
1159 * @brief Fetches the contact id for a handle and checks if posting is allowed
1161 * @param array $importer Array of the importer user
1162 * @param string $handle The checked handle in the format user@domain.tld
1163 * @param bool $is_comment Is the check for a comment?
1165 * @return array The contact data
1166 * @throws \Exception
1168 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1170 $contact = self::contactByHandle($importer["uid"], $handle);
1172 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1173 // If a contact isn't found, we accept it anyway if it is a comment
1174 if ($is_comment && ($importer["uid"] != 0)) {
1175 return self::contactByHandle(0, $handle);
1176 } elseif ($is_comment) {
1183 if (!self::postAllow($importer, $contact, $is_comment)) {
1184 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1191 * @brief Does the message already exists on the system?
1193 * @param int $uid The user id
1194 * @param string $guid The guid of the message
1196 * @return int|bool message id if the message already was stored into the system - or false.
1197 * @throws \Exception
1199 private static function messageExists($uid, $guid)
1201 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1202 if (DBA::isResult($item)) {
1203 Logger::log("message ".$guid." already exists for user ".$uid);
1211 * @brief Checks for links to posts in a message
1213 * @param array $item The item array
1216 private static function fetchGuid(array $item)
1218 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1219 preg_replace_callback(
1221 function ($match) use ($item) {
1222 self::fetchGuidSub($match, $item);
1227 preg_replace_callback(
1228 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1229 function ($match) use ($item) {
1230 self::fetchGuidSub($match, $item);
1237 * @brief Checks for relative /people/* links in an item body to match local
1238 * contacts or prepends the remote host taken from the author link.
1240 * @param string $body The item body to replace links from
1241 * @param string $author_link The author link for missing local contact fallback
1243 * @return string the replaced string
1245 public static function replacePeopleGuid($body, $author_link)
1247 $return = preg_replace_callback(
1248 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1249 function ($match) use ($author_link) {
1251 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1252 // 1 => '0123456789abcdef'
1254 $handle = self::urlFromContactGuid($match[1]);
1257 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1259 // No local match, restoring absolute remote URL from author scheme and host
1260 $author_url = parse_url($author_link);
1261 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1273 * @brief sub function of "fetchGuid" which checks for links in messages
1275 * @param array $match array containing a link that has to be checked for a message link
1276 * @param array $item The item array
1278 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1279 * @throws \ImagickException
1281 private static function fetchGuidSub($match, $item)
1283 if (!self::storeByGuid($match[1], $item["author-link"])) {
1284 self::storeByGuid($match[1], $item["owner-link"]);
1289 * @brief Fetches an item with a given guid from a given server
1291 * @param string $guid the message guid
1292 * @param string $server The server address
1293 * @param int $uid The user id of the user
1295 * @return int the message id of the stored message or false
1296 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1297 * @throws \ImagickException
1299 private static function storeByGuid($guid, $server, $uid = 0)
1301 $serverparts = parse_url($server);
1303 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1307 $server = $serverparts["scheme"]."://".$serverparts["host"];
1309 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1311 $msg = self::message($guid, $server);
1317 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1319 // Now call the dispatcher
1320 return self::dispatchPublic($msg);
1324 * @brief Fetches a message from a server
1326 * @param string $guid message guid
1327 * @param string $server The url of the server
1328 * @param int $level Endless loop prevention
1331 * 'message' => The message XML
1332 * 'author' => The author handle
1333 * 'key' => The public key of the author
1334 * @throws \Exception
1336 private static function message($guid, $server, $level = 0)
1342 // This will work for new Diaspora servers and Friendica servers from 3.5
1343 $source_url = $server."/fetch/post/".urlencode($guid);
1345 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1347 $envelope = Network::fetchUrl($source_url);
1349 Logger::log("Envelope was fetched.", Logger::DEBUG);
1350 $x = self::verifyMagicEnvelope($envelope);
1352 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1354 Logger::log("Envelope was verified.", Logger::DEBUG);
1364 $source_xml = XML::parseString($x);
1366 if (!is_object($source_xml)) {
1370 if ($source_xml->post->reshare) {
1371 // Reshare of a reshare - old Diaspora version
1372 Logger::log("Message is a reshare", Logger::DEBUG);
1373 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1374 } elseif ($source_xml->getName() == "reshare") {
1375 // Reshare of a reshare - new Diaspora version
1376 Logger::log("Message is a new reshare", Logger::DEBUG);
1377 return self::message($source_xml->root_guid, $server, ++$level);
1382 // Fetch the author - for the old and the new Diaspora version
1383 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1384 $author = (string)$source_xml->post->status_message->diaspora_handle;
1385 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1386 $author = (string)$source_xml->author;
1389 // If this isn't a "status_message" then quit
1391 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1395 $msg = ["message" => $x, "author" => $author];
1397 $msg["key"] = self::key($msg["author"]);
1403 * @brief Fetches the item record of a given guid
1405 * @param int $uid The user id
1406 * @param string $guid message guid
1407 * @param string $author The handle of the item
1408 * @param array $contact The contact of the item owner
1410 * @return array the item record
1411 * @throws \Exception
1413 private static function parentItem($uid, $guid, $author, array $contact)
1415 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1416 'author-name', 'author-link', 'author-avatar',
1417 'owner-name', 'owner-link', 'owner-avatar'];
1418 $condition = ['uid' => $uid, 'guid' => $guid];
1419 $item = Item::selectFirst($fields, $condition);
1421 if (!DBA::isResult($item)) {
1422 $person = self::personByHandle($author);
1423 $result = self::storeByGuid($guid, $person["url"], $uid);
1425 // We don't have an url for items that arrived at the public dispatcher
1426 if (!$result && !empty($contact["url"])) {
1427 $result = self::storeByGuid($guid, $contact["url"], $uid);
1431 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1433 $item = Item::selectFirst($fields, $condition);
1437 if (!DBA::isResult($item)) {
1438 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1441 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1447 * @brief returns contact details
1449 * @param array $def_contact The default contact if the person isn't found
1450 * @param array $person The record of the person
1451 * @param int $uid The user id
1454 * 'cid' => contact id
1455 * 'network' => network type
1456 * @throws \Exception
1458 private static function authorContactByUrl($def_contact, $person, $uid)
1460 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1461 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1462 if (DBA::isResult($contact)) {
1463 $cid = $contact["id"];
1464 $network = $contact["network"];
1466 $cid = $def_contact["id"];
1467 $network = Protocol::DIASPORA;
1470 return ["cid" => $cid, "network" => $network];
1474 * @brief Is the profile a hubzilla profile?
1476 * @param string $url The profile link
1478 * @return bool is it a hubzilla server?
1480 public static function isRedmatrix($url)
1482 return(strstr($url, "/channel/"));
1486 * @brief Generate a post link with a given handle and message guid
1488 * @param string $addr The user handle
1489 * @param string $guid message guid
1490 * @param string $parent_guid optional parent guid
1492 * @return string the post link
1493 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1494 * @throws \ImagickException
1496 private static function plink($addr, $guid, $parent_guid = '')
1498 $contact = Contact::getDetailsByAddr($addr);
1502 if ($parent_guid != '') {
1503 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1505 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1509 if ($contact["network"] == Protocol::DFRN) {
1510 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1513 if (self::isRedmatrix($contact["url"])) {
1514 return $contact["url"] . "/?f=&mid=" . $guid;
1517 if ($parent_guid != '') {
1518 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1520 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1525 * @brief Receives account migration
1527 * @param array $importer Array of the importer user
1528 * @param object $data The message object
1530 * @return bool Success
1531 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1532 * @throws \ImagickException
1534 private static function receiveAccountMigration(array $importer, $data)
1536 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1537 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1538 $signature = Strings::escapeTags(XML::unescape($data->signature));
1540 $contact = self::contactByHandle($importer["uid"], $old_handle);
1542 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1546 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1549 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1550 $key = self::key($old_handle);
1551 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1552 Logger::log('No valid signature for migration.');
1556 // Update the profile
1557 self::receiveProfile($importer, $data->profile);
1559 // change the technical stuff in contact and gcontact
1560 $data = Probe::uri($new_handle);
1561 if ($data['network'] == Protocol::PHANTOM) {
1562 Logger::log('Account for '.$new_handle." couldn't be probed.");
1566 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1567 'name' => $data['name'], 'nick' => $data['nick'],
1568 'addr' => $data['addr'], 'batch' => $data['batch'],
1569 'notify' => $data['notify'], 'poll' => $data['poll'],
1570 'network' => $data['network']];
1572 DBA::update('contact', $fields, ['addr' => $old_handle]);
1574 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1575 'name' => $data['name'], 'nick' => $data['nick'],
1576 'addr' => $data['addr'], 'connect' => $data['addr'],
1577 'notify' => $data['notify'], 'photo' => $data['photo'],
1578 'server_url' => $data['baseurl'], 'network' => $data['network']];
1580 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1582 Logger::log('Contacts are updated.');
1588 * @brief Processes an account deletion
1590 * @param object $data The message object
1592 * @return bool Success
1593 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1595 private static function receiveAccountDeletion($data)
1597 $author = Strings::escapeTags(XML::unescape($data->author));
1599 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1600 while ($contact = DBA::fetch($contacts)) {
1601 Contact::remove($contact["id"]);
1604 DBA::delete('gcontact', ['addr' => $author]);
1606 Logger::log('Removed contacts for ' . $author);
1612 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1614 * @param string $author Author handle
1615 * @param string $guid Message guid
1616 * @param boolean $onlyfound Only return uri when found in the database
1618 * @return string The constructed uri or the one from our database
1619 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1620 * @throws \ImagickException
1622 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1624 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1625 if (DBA::isResult($item)) {
1626 return $item["uri"];
1627 } elseif (!$onlyfound) {
1628 $person = self::personByHandle($author);
1630 $parts = parse_url($person['url']);
1631 unset($parts['path']);
1632 $host_url = Network::unparseURL($parts);
1634 return $host_url . '/objects/' . $guid;
1641 * @brief Fetch the guid from our database with a given uri
1643 * @param string $uri Message uri
1644 * @param string $uid Author handle
1646 * @return string The post guid
1647 * @throws \Exception
1649 private static function getGuidFromUri($uri, $uid)
1651 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1652 if (DBA::isResult($item)) {
1653 return $item["guid"];
1660 * @brief Find the best importer for a comment, like, ...
1662 * @param string $guid The guid of the item
1664 * @return array|boolean the origin owner of that post - or false
1665 * @throws \Exception
1667 private static function importerForGuid($guid)
1669 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1670 if (DBA::isResult($item)) {
1671 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1672 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1673 if (DBA::isResult($contact)) {
1681 * @brief Processes an incoming comment
1683 * @param array $importer Array of the importer user
1684 * @param string $sender The sender of the message
1685 * @param object $data The message object
1686 * @param string $xml The original XML of the message
1688 * @return int The message id of the generated comment or "false" if there was an error
1689 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1690 * @throws \ImagickException
1692 private static function receiveComment(array $importer, $sender, $data, $xml)
1694 $author = Strings::escapeTags(XML::unescape($data->author));
1695 $guid = Strings::escapeTags(XML::unescape($data->guid));
1696 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1697 $text = XML::unescape($data->text);
1699 if (isset($data->created_at)) {
1700 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1702 $created_at = DateTimeFormat::utcNow();
1705 if (isset($data->thread_parent_guid)) {
1706 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1707 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1712 $contact = self::allowedContactByHandle($importer, $sender, true);
1717 $message_id = self::messageExists($importer["uid"], $guid);
1722 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1723 if (!$parent_item) {
1727 $person = self::personByHandle($author);
1728 if (!is_array($person)) {
1729 Logger::log("unable to find author details");
1733 // Fetch the contact id - if we know this contact
1734 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1738 $datarray["uid"] = $importer["uid"];
1739 $datarray["contact-id"] = $author_contact["cid"];
1740 $datarray["network"] = $author_contact["network"];
1742 $datarray["author-link"] = $person["url"];
1743 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1745 $datarray["owner-link"] = $contact["url"];
1746 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1748 $datarray["guid"] = $guid;
1749 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1751 $datarray["verb"] = ACTIVITY_POST;
1752 $datarray["gravity"] = GRAVITY_COMMENT;
1754 if ($thr_uri != "") {
1755 $datarray["parent-uri"] = $thr_uri;
1757 $datarray["parent-uri"] = $parent_item["uri"];
1760 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1762 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1763 $datarray["source"] = $xml;
1765 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1767 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1769 $body = Markdown::toBBCode($text);
1771 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1773 self::fetchGuid($datarray);
1775 // If we are the origin of the parent we store the original data.
1776 // We notify our followers during the item storage.
1777 if ($parent_item["origin"]) {
1778 $datarray['diaspora_signed_text'] = json_encode($data);
1781 $message_id = Item::insert($datarray);
1783 if ($message_id <= 0) {
1788 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1789 if ($datarray['uid'] == 0) {
1790 Item::distribute($message_id, json_encode($data));
1798 * @brief processes and stores private messages
1800 * @param array $importer Array of the importer user
1801 * @param array $contact The contact of the message
1802 * @param object $data The message object
1803 * @param array $msg Array of the processed message, author handle and key
1804 * @param object $mesg The private message
1805 * @param array $conversation The conversation record to which this message belongs
1807 * @return bool "true" if it was successful
1808 * @throws \Exception
1810 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1812 $author = Strings::escapeTags(XML::unescape($data->author));
1813 $guid = Strings::escapeTags(XML::unescape($data->guid));
1814 $subject = Strings::escapeTags(XML::unescape($data->subject));
1816 // "diaspora_handle" is the element name from the old version
1817 // "author" is the element name from the new version
1818 if ($mesg->author) {
1819 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1820 } elseif ($mesg->diaspora_handle) {
1821 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1826 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1827 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1828 $msg_text = XML::unescape($mesg->text);
1829 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1831 if ($msg_conversation_guid != $guid) {
1832 Logger::log("message conversation guid does not belong to the current conversation.");
1836 $body = Markdown::toBBCode($msg_text);
1837 $message_uri = $msg_author.":".$msg_guid;
1839 $person = self::personByHandle($msg_author);
1843 if (DBA::exists('mail', ['guid' => $msg_guid, 'uid' => $importer["uid"]])) {
1844 Logger::log("duplicate message already delivered.", Logger::DEBUG);
1848 DBA::insert('mail', [
1849 'uid' => $importer['uid'],
1850 'guid' => $msg_guid,
1851 'convid' => $conversation['id'],
1852 'from-name' => $person['name'],
1853 'from-photo' => $person['photo'],
1854 'from-url' => $person['url'],
1855 'contact-id' => $contact['id'],
1856 'title' => $subject,
1860 'uri' => $message_uri,
1861 'parent-uri' => $author . ':' . $guid,
1862 'created' => $msg_created_at
1865 $message_id = DBA::lastInsertId();
1869 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1872 "type" => NOTIFY_MAIL,
1873 "notify_flags" => $importer["notify-flags"],
1874 "language" => $importer["language"],
1875 "to_name" => $importer["username"],
1876 "to_email" => $importer["email"],
1877 "uid" => $importer["uid"],
1878 "item" => ["id" => $message_id, "title" => $subject, "subject" => $subject, "body" => $body],
1879 "parent" => $conversation["id"],
1880 "source_name" => $person["name"],
1881 "source_link" => $person["url"],
1882 "source_photo" => $person["photo"],
1883 "verb" => ACTIVITY_POST,
1891 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1893 * @param array $importer Array of the importer user
1894 * @param array $msg Array of the processed message, author handle and key
1895 * @param object $data The message object
1897 * @return bool Success
1898 * @throws \Exception
1900 private static function receiveConversation(array $importer, $msg, $data)
1902 $author = Strings::escapeTags(XML::unescape($data->author));
1903 $guid = Strings::escapeTags(XML::unescape($data->guid));
1904 $subject = Strings::escapeTags(XML::unescape($data->subject));
1905 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1906 $participants = Strings::escapeTags(XML::unescape($data->participants));
1908 $messages = $data->message;
1910 if (!count($messages)) {
1911 Logger::log("empty conversation");
1915 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1920 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1921 if (!DBA::isResult($conversation)) {
1923 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1924 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1925 intval($importer["uid"]),
1927 DBA::escape($author),
1928 DBA::escape($created_at),
1929 DBA::escape(DateTimeFormat::utcNow()),
1930 DBA::escape($subject),
1931 DBA::escape($participants)
1934 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1937 if (!$conversation) {
1938 Logger::log("unable to create conversation.");
1942 foreach ($messages as $mesg) {
1943 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1950 * @brief Processes "like" messages
1952 * @param array $importer Array of the importer user
1953 * @param string $sender The sender of the message
1954 * @param object $data The message object
1956 * @return int The message id of the generated like or "false" if there was an error
1957 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1958 * @throws \ImagickException
1960 private static function receiveLike(array $importer, $sender, $data)
1962 $author = Strings::escapeTags(XML::unescape($data->author));
1963 $guid = Strings::escapeTags(XML::unescape($data->guid));
1964 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1965 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1966 $positive = Strings::escapeTags(XML::unescape($data->positive));
1968 // likes on comments aren't supported by Diaspora - only on posts
1969 // But maybe this will be supported in the future, so we will accept it.
1970 if (!in_array($parent_type, ["Post", "Comment"])) {
1974 $contact = self::allowedContactByHandle($importer, $sender, true);
1979 $message_id = self::messageExists($importer["uid"], $guid);
1984 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1985 if (!$parent_item) {
1989 $person = self::personByHandle($author);
1990 if (!is_array($person)) {
1991 Logger::log("unable to find author details");
1995 // Fetch the contact id - if we know this contact
1996 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1998 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1999 // We would accept this anyhow.
2000 if ($positive == "true") {
2001 $verb = ACTIVITY_LIKE;
2003 $verb = ACTIVITY_DISLIKE;
2008 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2010 $datarray["uid"] = $importer["uid"];
2011 $datarray["contact-id"] = $author_contact["cid"];
2012 $datarray["network"] = $author_contact["network"];
2014 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2015 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2017 $datarray["guid"] = $guid;
2018 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2020 $datarray["verb"] = $verb;
2021 $datarray["gravity"] = GRAVITY_ACTIVITY;
2022 $datarray["parent-uri"] = $parent_item["uri"];
2024 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2026 $datarray["body"] = $verb;
2028 // Diaspora doesn't provide a date for likes
2029 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2031 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2032 if ($parent_item["id"] != $parent_item["parent"]) {
2033 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2034 $origin = $toplevel["origin"];
2036 $origin = $parent_item["origin"];
2039 // If we are the origin of the parent we store the original data.
2040 // We notify our followers during the item storage.
2042 $datarray['diaspora_signed_text'] = json_encode($data);
2045 $message_id = Item::insert($datarray);
2047 if ($message_id <= 0) {
2052 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2053 if ($datarray['uid'] == 0) {
2054 Item::distribute($message_id, json_encode($data));
2062 * @brief Processes private messages
2064 * @param array $importer Array of the importer user
2065 * @param object $data The message object
2067 * @return bool Success?
2068 * @throws \Exception
2070 private static function receiveMessage(array $importer, $data)
2072 $author = Strings::escapeTags(XML::unescape($data->author));
2073 $guid = Strings::escapeTags(XML::unescape($data->guid));
2074 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2075 $text = XML::unescape($data->text);
2076 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2078 $contact = self::allowedContactByHandle($importer, $author, true);
2083 $conversation = null;
2085 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2086 $conversation = DBA::selectFirst('conv', [], $condition);
2088 if (!DBA::isResult($conversation)) {
2089 Logger::log("conversation not available.");
2093 $message_uri = $author.":".$guid;
2095 $person = self::personByHandle($author);
2097 Logger::log("unable to find author details");
2101 $body = Markdown::toBBCode($text);
2103 $body = self::replacePeopleGuid($body, $person["url"]);
2107 if (DBA::exists('mail', ['guid' => $guid, 'uid' => $importer["uid"]])) {
2108 Logger::log("duplicate message already delivered.", Logger::DEBUG);
2112 DBA::insert('mail', [
2113 'uid' => $importer['uid'],
2115 'convid' => $conversation['id'],
2116 'from-name' => $person['name'],
2117 'from-photo' => $person['photo'],
2118 'from-url' => $person['url'],
2119 'contact-id' => $contact['id'],
2120 'title' => $conversation['subject'],
2124 'uri' => $message_uri,
2125 'parent-uri' => $author.":".$conversation['guid'],
2126 'created' => $created_at
2129 $message_id = DBA::lastInsertId();
2133 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2136 "type" => NOTIFY_MAIL,
2137 "notify_flags" => $importer["notify-flags"],
2138 "language" => $importer["language"],
2139 "to_name" => $importer["username"],
2140 "to_email" => $importer["email"],
2141 "uid" => $importer["uid"],
2142 "item" => ["id" => $message_id, "title" => $conversation["subject"], "subject" => $conversation["subject"], "body" => $body],
2143 "parent" => $conversation["id"],
2144 "source_name" => $person["name"],
2145 "source_link" => $person["url"],
2146 "source_photo" => $person["photo"],
2147 "verb" => ACTIVITY_POST,
2155 * @brief Processes participations - unsupported by now
2157 * @param array $importer Array of the importer user
2158 * @param object $data The message object
2160 * @return bool always true
2161 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2162 * @throws \ImagickException
2164 private static function receiveParticipation(array $importer, $data)
2166 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2167 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2169 $contact_id = Contact::getIdForURL($author);
2171 Logger::log('Contact not found: '.$author);
2175 $person = self::personByHandle($author);
2176 if (!is_array($person)) {
2177 Logger::log("Person not found: ".$author);
2181 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2182 if (!DBA::isResult($item)) {
2183 Logger::log('Item not found, no origin or private: '.$parent_guid);
2187 $author_parts = explode('@', $author);
2188 if (isset($author_parts[1])) {
2189 $server = $author_parts[1];
2191 // Should never happen
2195 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2197 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2198 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2201 // Send all existing comments and likes to the requesting server
2202 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2203 while ($comment = Item::fetch($comments)) {
2204 if ($comment['id'] == $comment['parent']) {
2207 if ($comment['verb'] == ACTIVITY_POST) {
2208 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2210 $cmd = $comment['self'] ? 'like' : 'comment-import';
2212 Logger::log("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, Logger::DEBUG);
2213 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2215 DBA::close($comments);
2221 * @brief Processes photos - unneeded
2223 * @param array $importer Array of the importer user
2224 * @param object $data The message object
2226 * @return bool always true
2228 private static function receivePhoto(array $importer, $data)
2230 // There doesn't seem to be a reason for this function,
2231 // since the photo data is transmitted in the status message as well
2236 * @brief Processes poll participations - unssupported
2238 * @param array $importer Array of the importer user
2239 * @param object $data The message object
2241 * @return bool always true
2243 private static function receivePollParticipation(array $importer, $data)
2245 // We don't support polls by now
2250 * @brief Processes incoming profile updates
2252 * @param array $importer Array of the importer user
2253 * @param object $data The message object
2255 * @return bool Success
2256 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2257 * @throws \ImagickException
2259 private static function receiveProfile(array $importer, $data)
2261 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2263 $contact = self::contactByHandle($importer["uid"], $author);
2268 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2269 $image_url = XML::unescape($data->image_url);
2270 $birthday = XML::unescape($data->birthday);
2271 $gender = XML::unescape($data->gender);
2272 $about = Markdown::toBBCode(XML::unescape($data->bio));
2273 $location = Markdown::toBBCode(XML::unescape($data->location));
2274 $searchable = (XML::unescape($data->searchable) == "true");
2275 $nsfw = (XML::unescape($data->nsfw) == "true");
2276 $tags = XML::unescape($data->tag_string);
2278 $tags = explode("#", $tags);
2281 foreach ($tags as $tag) {
2282 $tag = trim(strtolower($tag));
2288 $keywords = implode(", ", $keywords);
2290 $handle_parts = explode("@", $author);
2291 $nick = $handle_parts[0];
2294 $name = $handle_parts[0];
2297 if (preg_match("|^https?://|", $image_url) === 0) {
2298 $image_url = "http://".$handle_parts[1].$image_url;
2301 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2303 // Generic birthday. We don't know the timezone. The year is irrelevant.
2305 $birthday = str_replace("1000", "1901", $birthday);
2307 if ($birthday != "") {
2308 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2311 // this is to prevent multiple birthday notifications in a single year
2312 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2314 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2315 $birthday = $contact["bd"];
2318 $fields = ['name' => $name, 'location' => $location,
2319 'name-date' => DateTimeFormat::utcNow(),
2320 'about' => $about, 'gender' => $gender,
2321 'addr' => $author, 'nick' => $nick,
2322 'keywords' => $keywords];
2324 if (!empty($birthday)) {
2325 $fields['bd'] = $birthday;
2328 DBA::update('contact', $fields, ['id' => $contact['id']]);
2330 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2331 "photo" => $image_url, "name" => $name, "location" => $location,
2332 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2333 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2334 "hide" => !$searchable, "nsfw" => $nsfw];
2336 $gcid = GContact::update($gcontact);
2338 GContact::link($gcid, $importer["uid"], $contact["id"]);
2340 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2346 * @brief Processes incoming friend requests
2348 * @param array $importer Array of the importer user
2349 * @param array $contact The contact that send the request
2351 * @throws \Exception
2353 private static function receiveRequestMakeFriend(array $importer, array $contact)
2355 if ($contact["rel"] == Contact::SHARING) {
2358 ['rel' => Contact::FRIEND, 'writable' => true],
2359 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2365 * @brief Processes incoming sharing notification
2367 * @param array $importer Array of the importer user
2368 * @param object $data The message object
2370 * @return bool Success
2371 * @throws \Exception
2373 private static function receiveContactRequest(array $importer, $data)
2375 $author = XML::unescape($data->author);
2376 $recipient = XML::unescape($data->recipient);
2378 if (!$author || !$recipient) {
2382 // the current protocol version doesn't know these fields
2383 // That means that we will assume their existance
2384 if (isset($data->following)) {
2385 $following = (XML::unescape($data->following) == "true");
2390 if (isset($data->sharing)) {
2391 $sharing = (XML::unescape($data->sharing) == "true");
2396 $contact = self::contactByHandle($importer["uid"], $author);
2398 // perhaps we were already sharing with this person. Now they're sharing with us.
2399 // That makes us friends.
2402 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2403 self::receiveRequestMakeFriend($importer, $contact);
2405 // refetch the contact array
2406 $contact = self::contactByHandle($importer["uid"], $author);
2408 // If we are now friends, we are sending a share message.
2409 // Normally we needn't to do so, but the first message could have been vanished.
2410 if (in_array($contact["rel"], [Contact::FRIEND])) {
2411 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2412 if (DBA::isResult($user)) {
2413 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2414 self::sendShare($user, $contact);
2419 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2420 Contact::removeFollower($importer, $contact);
2425 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2426 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2428 } elseif (!$following && !$sharing) {
2429 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2431 } elseif (!$following && $sharing) {
2432 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2433 } elseif ($following && $sharing) {
2434 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2435 } elseif ($following && !$sharing) {
2436 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2439 $ret = self::personByHandle($author);
2441 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2442 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2446 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2449 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2450 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2451 intval($importer["uid"]),
2452 DBA::escape($ret["network"]),
2453 DBA::escape($ret["addr"]),
2454 DateTimeFormat::utcNow(),
2455 DBA::escape($ret["url"]),
2456 DBA::escape(Strings::normaliseLink($ret["url"])),
2457 DBA::escape($batch),
2458 DBA::escape($ret["name"]),
2459 DBA::escape($ret["nick"]),
2460 DBA::escape($ret["photo"]),
2461 DBA::escape($ret["pubkey"]),
2462 DBA::escape($ret["notify"]),
2463 DBA::escape($ret["poll"]),
2468 // find the contact record we just created
2470 $contact_record = self::contactByHandle($importer["uid"], $author);
2472 if (!$contact_record) {
2473 Logger::log("unable to locate newly created contact record.");
2477 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2479 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2481 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2483 if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
2484 Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2486 $hash = Strings::getRandomHex().(string)time(); // Generate a confirm_key
2489 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2490 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2491 intval($importer["uid"]),
2492 intval($contact_record["id"]),
2495 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2497 DBA::escape(DateTimeFormat::utcNow())
2500 // automatic friend approval
2502 Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2504 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2507 * technically they are sharing with us (Contact::SHARING),
2508 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2509 * we are going to change the relationship and make them a follower.
2511 if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
2512 $new_relation = Contact::FRIEND;
2513 } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
2514 $new_relation = Contact::SHARING;
2516 $new_relation = Contact::FOLLOWER;
2520 "UPDATE `contact` SET `rel` = %d,
2528 intval($new_relation),
2529 DBA::escape(DateTimeFormat::utcNow()),
2530 DBA::escape(DateTimeFormat::utcNow()),
2531 intval($contact_record["id"])
2534 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2535 if (DBA::isResult($user)) {
2536 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2537 self::sendShare($user, $contact_record);
2539 // Send the profile data, maybe it weren't transmitted before
2540 self::sendProfile($importer["uid"], [$contact_record]);
2548 * @brief Fetches a message with a given guid
2550 * @param string $guid message guid
2551 * @param string $orig_author handle of the original post
2552 * @return array The fetched item
2553 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2554 * @throws \ImagickException
2556 public static function originalItem($guid, $orig_author)
2559 Logger::log('Empty guid. Quitting.');
2563 // Do we already have this item?
2564 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2565 'author-name', 'author-link', 'author-avatar'];
2566 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2567 $item = Item::selectFirst($fields, $condition);
2569 if (DBA::isResult($item)) {
2570 Logger::log("reshared message ".$guid." already exists on system.");
2572 // Maybe it is already a reshared item?
2573 // Then refetch the content, if it is a reshare from a reshare.
2574 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2575 if (self::isReshare($item["body"], true)) {
2577 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2578 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2580 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2582 // Add OEmbed and other information to the body
2583 $item["body"] = add_page_info_to_body($item["body"], false, true);
2591 if (!DBA::isResult($item)) {
2592 if (empty($orig_author)) {
2593 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2597 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2598 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2599 $stored = self::storeByGuid($guid, $server);
2602 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2603 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2604 $stored = self::storeByGuid($guid, $server);
2608 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2609 'author-name', 'author-link', 'author-avatar'];
2610 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2611 $item = Item::selectFirst($fields, $condition);
2613 if (DBA::isResult($item)) {
2614 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2615 if (self::isReshare($item["body"], false)) {
2616 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2617 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2628 * @brief Processes a reshare message
2630 * @param array $importer Array of the importer user
2631 * @param object $data The message object
2632 * @param string $xml The original XML of the message
2634 * @return int the message id
2635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2636 * @throws \ImagickException
2638 private static function receiveReshare(array $importer, $data, $xml)
2640 $author = Strings::escapeTags(XML::unescape($data->author));
2641 $guid = Strings::escapeTags(XML::unescape($data->guid));
2642 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2643 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2644 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2645 /// @todo handle unprocessed property "provider_display_name"
2646 $public = Strings::escapeTags(XML::unescape($data->public));
2648 $contact = self::allowedContactByHandle($importer, $author, false);
2653 $message_id = self::messageExists($importer["uid"], $guid);
2658 $original_item = self::originalItem($root_guid, $root_author);
2659 if (!$original_item) {
2663 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2667 $datarray["uid"] = $importer["uid"];
2668 $datarray["contact-id"] = $contact["id"];
2669 $datarray["network"] = Protocol::DIASPORA;
2671 $datarray["author-link"] = $contact["url"];
2672 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2674 $datarray["owner-link"] = $datarray["author-link"];
2675 $datarray["owner-id"] = $datarray["author-id"];
2677 $datarray["guid"] = $guid;
2678 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2680 $datarray["verb"] = ACTIVITY_POST;
2681 $datarray["gravity"] = GRAVITY_PARENT;
2683 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2684 $datarray["source"] = $xml;
2686 $prefix = share_header(
2687 $original_item["author-name"],
2688 $original_item["author-link"],
2689 $original_item["author-avatar"],
2690 $original_item["guid"],
2691 $original_item["created"],
2694 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2696 $datarray["tag"] = $original_item["tag"];
2697 $datarray["app"] = $original_item["app"];
2699 $datarray["plink"] = self::plink($author, $guid);
2700 $datarray["private"] = (($public == "false") ? 1 : 0);
2701 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2703 $datarray["object-type"] = $original_item["object-type"];
2705 self::fetchGuid($datarray);
2706 $message_id = Item::insert($datarray);
2708 self::sendParticipation($contact, $datarray);
2711 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2712 if ($datarray['uid'] == 0) {
2713 Item::distribute($message_id);
2722 * @brief Processes retractions
2724 * @param array $importer Array of the importer user
2725 * @param array $contact The contact of the item owner
2726 * @param object $data The message object
2728 * @return bool success
2729 * @throws \Exception
2731 private static function itemRetraction(array $importer, array $contact, $data)
2733 $author = Strings::escapeTags(XML::unescape($data->author));
2734 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2735 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2737 $person = self::personByHandle($author);
2738 if (!is_array($person)) {
2739 Logger::log("unable to find author detail for ".$author);
2743 if (empty($contact["url"])) {
2744 $contact["url"] = $person["url"];
2747 // Fetch items that are about to be deleted
2748 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2750 // When we receive a public retraction, we delete every item that we find.
2751 if ($importer['uid'] == 0) {
2752 $condition = ['guid' => $target_guid, 'deleted' => false];
2754 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2757 $r = Item::select($fields, $condition);
2758 if (!DBA::isResult($r)) {
2759 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2763 while ($item = Item::fetch($r)) {
2764 if (strstr($item['file'], '[')) {
2765 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2769 // Fetch the parent item
2770 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2772 // Only delete it if the parent author really fits
2773 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2774 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2778 Item::delete(['id' => $item['id']]);
2780 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2787 * @brief Receives retraction messages
2789 * @param array $importer Array of the importer user
2790 * @param string $sender The sender of the message
2791 * @param object $data The message object
2793 * @return bool Success
2794 * @throws \Exception
2796 private static function receiveRetraction(array $importer, $sender, $data)
2798 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2800 $contact = self::contactByHandle($importer["uid"], $sender);
2801 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2802 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2810 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2812 switch ($target_type) {
2817 case "StatusMessage":
2818 return self::itemRetraction($importer, $contact, $data);
2820 case "PollParticipation":
2822 // Currently unsupported
2826 Logger::log("Unknown target type ".$target_type);
2833 * @brief Receives status messages
2835 * @param array $importer Array of the importer user
2836 * @param SimpleXMLElement $data The message object
2837 * @param string $xml The original XML of the message
2839 * @return int The message id of the newly created item
2840 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2841 * @throws \ImagickException
2843 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2845 $author = Strings::escapeTags(XML::unescape($data->author));
2846 $guid = Strings::escapeTags(XML::unescape($data->guid));
2847 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2848 $public = Strings::escapeTags(XML::unescape($data->public));
2849 $text = XML::unescape($data->text);
2850 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2852 $contact = self::allowedContactByHandle($importer, $author, false);
2857 $message_id = self::messageExists($importer["uid"], $guid);
2863 if ($data->location) {
2864 foreach ($data->location->children() as $fieldname => $data) {
2865 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2869 $body = Markdown::toBBCode($text);
2873 // Attach embedded pictures to the body
2875 foreach ($data->photo as $photo) {
2876 $body = "[img]".XML::unescape($photo->remote_photo_path).
2877 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2880 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2882 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2884 // Add OEmbed and other information to the body
2885 if (!self::isRedmatrix($contact["url"])) {
2886 $body = add_page_info_to_body($body, false, true);
2890 /// @todo enable support for polls
2891 //if ($data->poll) {
2892 // foreach ($data->poll AS $poll)
2897 /// @todo enable support for events
2899 $datarray["uid"] = $importer["uid"];
2900 $datarray["contact-id"] = $contact["id"];
2901 $datarray["network"] = Protocol::DIASPORA;
2903 $datarray["author-link"] = $contact["url"];
2904 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2906 $datarray["owner-link"] = $datarray["author-link"];
2907 $datarray["owner-id"] = $datarray["author-id"];
2909 $datarray["guid"] = $guid;
2910 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2912 $datarray["verb"] = ACTIVITY_POST;
2913 $datarray["gravity"] = GRAVITY_PARENT;
2915 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2916 $datarray["source"] = $xml;
2918 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2920 if ($provider_display_name != "") {
2921 $datarray["app"] = $provider_display_name;
2924 $datarray["plink"] = self::plink($author, $guid);
2925 $datarray["private"] = (($public == "false") ? 1 : 0);
2926 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2928 if (isset($address["address"])) {
2929 $datarray["location"] = $address["address"];
2932 if (isset($address["lat"]) && isset($address["lng"])) {
2933 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2936 self::fetchGuid($datarray);
2937 $message_id = Item::insert($datarray);
2939 self::sendParticipation($contact, $datarray);
2942 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2943 if ($datarray['uid'] == 0) {
2944 Item::distribute($message_id);
2952 /* ************************************************************************************** *
2953 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2954 * ************************************************************************************** */
2957 * @brief returnes the handle of a contact
2959 * @param array $contact contact array
2961 * @return string the handle in the format user@domain.tld
2962 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2964 private static function myHandle(array $contact)
2966 if (!empty($contact["addr"])) {
2967 return $contact["addr"];
2970 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2971 // So - just in case - we build the the address here.
2972 if ($contact["nickname"] != "") {
2973 $nick = $contact["nickname"];
2975 $nick = $contact["nick"];
2978 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2983 * @brief Creates the data for a private message in the new format
2985 * @param string $msg The message that is to be transmitted
2986 * @param array $user The record of the sender
2987 * @param array $contact Target of the communication
2988 * @param string $prvkey The private key of the sender
2989 * @param string $pubkey The public key of the receiver
2991 * @return string The encrypted data
2992 * @throws \Exception
2994 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2996 Logger::log("Message: ".$msg, Logger::DATA);
2998 // without a public key nothing will work
3000 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3004 $aes_key = openssl_random_pseudo_bytes(32);
3005 $b_aes_key = base64_encode($aes_key);
3006 $iv = openssl_random_pseudo_bytes(16);
3007 $b_iv = base64_encode($iv);
3009 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3011 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3013 $encrypted_key_bundle = "";
3014 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3016 $json_object = json_encode(
3017 ["aes_key" => base64_encode($encrypted_key_bundle),
3018 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3021 return $json_object;
3025 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3027 * @param string $msg The message that is to be transmitted
3028 * @param array $user The record of the sender
3030 * @return string The envelope
3031 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3033 public static function buildMagicEnvelope($msg, array $user)
3035 $b64url_data = Strings::base64UrlEncode($msg);
3036 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3038 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3039 $type = "application/xml";
3040 $encoding = "base64url";
3041 $alg = "RSA-SHA256";
3042 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3044 // Fallback if the private key wasn't transmitted in the expected field
3045 if ($user['uprvkey'] == "") {
3046 $user['uprvkey'] = $user['prvkey'];
3049 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3050 $sig = Strings::base64UrlEncode($signature);
3052 $xmldata = ["me:env" => ["me:data" => $data,
3053 "@attributes" => ["type" => $type],
3054 "me:encoding" => $encoding,
3057 "@attributes2" => ["key_id" => $key_id]]];
3059 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3061 return XML::fromArray($xmldata, $xml, false, $namespaces);
3065 * @brief Create the envelope for a message
3067 * @param string $msg The message that is to be transmitted
3068 * @param array $user The record of the sender
3069 * @param array $contact Target of the communication
3070 * @param string $prvkey The private key of the sender
3071 * @param string $pubkey The public key of the receiver
3072 * @param bool $public Is the message public?
3074 * @return string The message that will be transmitted to other servers
3075 * @throws \Exception
3077 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3079 // The message is put into an envelope with the sender's signature
3080 $envelope = self::buildMagicEnvelope($msg, $user);
3082 // Private messages are put into a second envelope, encrypted with the receivers public key
3084 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3091 * @brief Creates a signature for a message
3093 * @param array $owner the array of the owner of the message
3094 * @param array $message The message that is to be signed
3096 * @return string The signature
3098 private static function signature($owner, $message)
3101 unset($sigmsg["author_signature"]);
3102 unset($sigmsg["parent_author_signature"]);
3104 $signed_text = implode(";", $sigmsg);
3106 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3110 * @brief Transmit a message to a target server
3112 * @param array $owner the array of the item owner
3113 * @param array $contact Target of the communication
3114 * @param string $envelope The message that is to be transmitted
3115 * @param bool $public_batch Is it a public post?
3116 * @param bool $queue_run Is the transmission called from the queue?
3117 * @param string $guid message guid
3119 * @param bool $no_queue
3120 * @return int Result of the transmission
3121 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3122 * @throws \ImagickException
3124 public static function transmit(array $owner, array $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3126 $enabled = intval(Config::get("system", "diaspora_enabled"));
3131 $logid = Strings::getRandomHex(4);
3133 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3135 // We always try to use the data from the fcontact table.
3136 // This is important for transmitting data to Friendica servers.
3137 if (!empty($contact['addr'])) {
3138 $fcontact = self::personByHandle($contact['addr']);
3139 if (!empty($fcontact)) {
3140 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3145 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3149 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3151 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3154 if (!intval(Config::get("system", "diaspora_test"))) {
3155 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3157 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3158 $return_code = $postResult->getReturnCode();
3160 Logger::log("test_mode");
3165 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3167 if (!$return_code || (($return_code == 503) && (stristr($postResult->getHeader(), "retry-after")))) {
3168 if (!$no_queue && !empty($contact['contact-type']) && ($contact['contact-type'] != Contact::TYPE_RELAY)) {
3169 Logger::log("queue message");
3170 // queue message for redelivery
3171 Queue::add($contact["id"], Protocol::DIASPORA, $envelope, $public_batch, $guid);
3174 // The message could not be delivered. We mark the contact as "dead"
3175 Contact::markForArchival($contact);
3176 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3177 // We successfully delivered a message, the contact is alive
3178 Contact::unmarkForArchival($contact);
3181 return $return_code ? $return_code : -1;
3186 * @brief Build the post xml
3188 * @param string $type The message type
3189 * @param array $message The message data
3191 * @return string The post XML
3193 public static function buildPostXml($type, $message)
3195 $data = [$type => $message];
3197 return XML::fromArray($data, $xml);
3201 * @brief Builds and transmit messages
3203 * @param array $owner the array of the item owner
3204 * @param array $contact Target of the communication
3205 * @param string $type The message type
3206 * @param array $message The message data
3207 * @param bool $public_batch Is it a public post?
3208 * @param string $guid message guid
3209 * @param bool $spool Should the transmission be spooled or transmitted?
3211 * @return int Result of the transmission
3212 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3213 * @throws \ImagickException
3215 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3217 $msg = self::buildPostXml($type, $message);
3219 Logger::log('message: '.$msg, Logger::DATA);
3220 Logger::log('send guid '.$guid, Logger::DEBUG);
3222 // Fallback if the private key wasn't transmitted in the expected field
3223 if (empty($owner['uprvkey'])) {
3224 $owner['uprvkey'] = $owner['prvkey'];
3227 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3230 Queue::add($contact['id'], Protocol::DIASPORA, $envelope, $public_batch, $guid);
3233 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3236 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3238 return $return_code;
3242 * @brief sends a participation (Used to get all further updates)
3244 * @param array $contact Target of the communication
3245 * @param array $item Item array
3247 * @return int The result of the transmission
3248 * @throws \Exception
3250 private static function sendParticipation(array $contact, array $item)
3252 // Don't send notifications for private postings
3253 if ($item['private']) {
3257 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3259 $result = Cache::get($cachekey);
3260 if (!is_null($result)) {
3264 // Fetch some user id to have a valid handle to transmit the participation.
3265 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3266 // If the item belongs to a user, we take this user id.
3267 if ($item['uid'] == 0) {
3268 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3269 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3270 $owner = User::getOwnerDataById($first_user['uid']);
3272 $owner = User::getOwnerDataById($item['uid']);
3275 $author = self::myHandle($owner);
3277 $message = ["author" => $author,
3278 "guid" => System::createUUID(),
3279 "parent_type" => "Post",
3280 "parent_guid" => $item["guid"]];
3282 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3284 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3285 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3287 return self::buildAndTransmit($owner, $contact, "participation", $message);
3291 * @brief sends an account migration
3293 * @param array $owner the array of the item owner
3294 * @param array $contact Target of the communication
3295 * @param int $uid User ID
3297 * @return int The result of the transmission
3298 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3299 * @throws \ImagickException
3301 public static function sendAccountMigration(array $owner, array $contact, $uid)
3303 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3304 $profile = self::createProfileData($uid);
3306 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3307 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3309 $message = ["author" => $old_handle,
3310 "profile" => $profile,
3311 "signature" => $signature];
3313 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3315 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3319 * @brief Sends a "share" message
3321 * @param array $owner the array of the item owner
3322 * @param array $contact Target of the communication
3324 * @return int The result of the transmission
3325 * @throws \Exception
3327 public static function sendShare(array $owner, array $contact)
3330 * @todo support the different possible combinations of "following" and "sharing"
3331 * Currently, Diaspora only interprets the "sharing" field
3333 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3337 switch ($contact["rel"]) {
3338 case Contact::FRIEND:
3342 case Contact::SHARING:
3346 case Contact::FOLLOWER:
3352 $message = ["author" => self::myHandle($owner),
3353 "recipient" => $contact["addr"],
3354 "following" => "true",
3355 "sharing" => "true"];
3357 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3359 return self::buildAndTransmit($owner, $contact, "contact", $message);
3363 * @brief sends an "unshare"
3365 * @param array $owner the array of the item owner
3366 * @param array $contact Target of the communication
3368 * @return int The result of the transmission
3369 * @throws \Exception
3371 public static function sendUnshare(array $owner, array $contact)
3373 $message = ["author" => self::myHandle($owner),
3374 "recipient" => $contact["addr"],
3375 "following" => "false",
3376 "sharing" => "false"];
3378 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3380 return self::buildAndTransmit($owner, $contact, "contact", $message);
3384 * @brief Checks a message body if it is a reshare
3386 * @param string $body The message body that is to be check
3387 * @param bool $complete Should it be a complete check or a simple check?
3389 * @return array|bool Reshare details or "false" if no reshare
3390 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3391 * @throws \ImagickException
3393 public static function isReshare($body, $complete = true)
3395 $body = trim($body);
3397 // Skip if it isn't a pure repeated messages
3398 // Does it start with a share?
3399 if ((strpos($body, "[share") > 0) && $complete) {
3403 // Does it end with a share?
3404 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3408 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3409 // Skip if there is no shared message in there
3410 if ($body == $attributes) {
3414 // If we don't do the complete check we quit here
3417 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3418 if (!empty($matches[1])) {
3419 $guid = $matches[1];
3422 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3423 if (!empty($matches[1])) {
3424 $guid = $matches[1];
3427 if (($guid != "") && $complete) {
3428 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3429 $item = Item::selectFirst(['contact-id'], $condition);
3430 if (DBA::isResult($item)) {
3432 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3433 $ret["root_guid"] = $guid;
3435 } elseif ($complete) {
3436 // We are resharing something that isn't a DFRN or Diaspora post.
3437 // So we have to return "false" on "$complete" to not trigger a reshare.
3440 } elseif (($guid == "") && $complete) {
3444 $ret["root_guid"] = $guid;
3447 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3448 if (!empty($matches[1])) {
3449 $profile = $matches[1];
3452 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3453 if (!empty($matches[1])) {
3454 $profile = $matches[1];
3459 if ($profile != "") {
3460 if (Contact::getIdForURL($profile)) {
3461 $author = Contact::getDetailsByURL($profile);
3462 $ret["root_handle"] = $author['addr'];
3466 if (empty($ret) && !$complete) {
3474 * @brief Create an event array
3476 * @param integer $event_id The id of the event
3478 * @return array with event data
3479 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3481 private static function buildEvent($event_id)
3483 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3484 if (!DBA::isResult($r)) {
3492 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3493 if (!DBA::isResult($r)) {
3499 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3500 if (!DBA::isResult($r)) {
3506 $eventdata['author'] = self::myHandle($owner);
3508 if ($event['guid']) {
3509 $eventdata['guid'] = $event['guid'];
3512 $mask = DateTimeFormat::ATOM;
3514 /// @todo - establish "all day" events in Friendica
3515 $eventdata["all_day"] = "false";
3517 $eventdata['timezone'] = 'UTC';
3518 if (!$event['adjust'] && $user['timezone']) {
3519 $eventdata['timezone'] = $user['timezone'];
3522 if ($event['start']) {
3523 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3525 if ($event['finish'] && !$event['nofinish']) {
3526 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3528 if ($event['summary']) {
3529 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3531 if ($event['desc']) {
3532 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3534 if ($event['location']) {
3535 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3536 $coord = Map::getCoordinates($event['location']);
3539 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3540 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3541 $location["lat"] = $coord['lat'];
3542 $location["lng"] = $coord['lon'];
3544 $location["lat"] = 0;
3545 $location["lng"] = 0;
3547 $eventdata['location'] = $location;
3554 * @brief Create a post (status message or reshare)
3556 * @param array $item The item that will be exported
3557 * @param array $owner the array of the item owner
3560 * 'type' -> Message type ("status_message" or "reshare")
3561 * 'message' -> Array of XML elements of the status
3562 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3563 * @throws \ImagickException
3565 public static function buildStatus(array $item, array $owner)
3567 $cachekey = "diaspora:buildStatus:".$item['guid'];
3569 $result = Cache::get($cachekey);
3570 if (!is_null($result)) {
3574 $myaddr = self::myHandle($owner);
3576 $public = ($item["private"] ? "false" : "true");
3578 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3580 // Detect a share element and do a reshare
3581 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3582 $message = ["author" => $myaddr,
3583 "guid" => $item["guid"],
3584 "created_at" => $created,
3585 "root_author" => $ret["root_handle"],
3586 "root_guid" => $ret["root_guid"],
3587 "provider_display_name" => $item["app"],
3588 "public" => $public];
3592 $title = $item["title"];
3593 $body = $item["body"];
3595 if ($item['author-link'] != $item['owner-link']) {
3596 require_once 'mod/share.php';
3597 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3598 "", $item['created'], $item['plink']) . $body . '[/share]';
3601 // convert to markdown
3602 $body = html_entity_decode(BBCode::toMarkdown($body));
3605 if (strlen($title)) {
3606 $body = "## ".html_entity_decode($title)."\n\n".$body;
3609 if ($item["attach"]) {
3610 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3612 $body .= "\n".L10n::t("Attachments:")."\n";
3613 foreach ($matches as $mtch) {
3614 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3621 if ($item["location"] != "")
3622 $location["address"] = $item["location"];
3624 if ($item["coord"] != "") {
3625 $coord = explode(" ", $item["coord"]);
3626 $location["lat"] = $coord[0];
3627 $location["lng"] = $coord[1];
3630 $message = ["author" => $myaddr,
3631 "guid" => $item["guid"],
3632 "created_at" => $created,
3633 "public" => $public,
3635 "provider_display_name" => $item["app"],
3636 "location" => $location];
3638 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3639 if (!isset($location["lat"]) || !isset($location["lng"])) {
3640 unset($message["location"]);
3643 if ($item['event-id'] > 0) {
3644 $event = self::buildEvent($item['event-id']);
3645 if (count($event)) {
3646 $message['event'] = $event;
3648 if (!empty($event['location']['address']) &&
3649 !empty($event['location']['lat']) &&
3650 !empty($event['location']['lng'])) {
3651 $message['location'] = $event['location'];
3654 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3655 // $message['text'] = '';
3659 $type = "status_message";
3662 $msg = ["type" => $type, "message" => $message];
3664 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3670 * @brief Sends a post
3672 * @param array $item The item that will be exported
3673 * @param array $owner the array of the item owner
3674 * @param array $contact Target of the communication
3675 * @param bool $public_batch Is it a public post?
3677 * @return int The result of the transmission
3678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3679 * @throws \ImagickException
3681 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3683 $status = self::buildStatus($item, $owner);
3685 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3689 * @brief Creates a "like" object
3691 * @param array $item The item that will be exported
3692 * @param array $owner the array of the item owner
3694 * @return array The data for a "like"
3695 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3697 private static function constructLike(array $item, array $owner)
3699 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3700 if (!DBA::isResult($parent)) {
3704 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3706 if ($item['verb'] === ACTIVITY_LIKE) {
3708 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3709 $positive = "false";
3712 return(["author" => self::myHandle($owner),
3713 "guid" => $item["guid"],
3714 "parent_guid" => $parent["guid"],
3715 "parent_type" => $target_type,
3716 "positive" => $positive,
3717 "author_signature" => ""]);
3721 * @brief Creates an "EventParticipation" object
3723 * @param array $item The item that will be exported
3724 * @param array $owner the array of the item owner
3726 * @return array The data for an "EventParticipation"
3727 * @throws \Exception
3729 private static function constructAttend(array $item, array $owner)
3731 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3732 if (!DBA::isResult($parent)) {
3736 switch ($item['verb']) {
3737 case ACTIVITY_ATTEND:
3738 $attend_answer = 'accepted';
3740 case ACTIVITY_ATTENDNO:
3741 $attend_answer = 'declined';
3743 case ACTIVITY_ATTENDMAYBE:
3744 $attend_answer = 'tentative';
3747 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3751 return(["author" => self::myHandle($owner),
3752 "guid" => $item["guid"],
3753 "parent_guid" => $parent["guid"],
3754 "status" => $attend_answer,
3755 "author_signature" => ""]);
3759 * @brief Creates the object for a comment
3761 * @param array $item The item that will be exported
3762 * @param array $owner the array of the item owner
3764 * @return array The data for a comment
3765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3767 private static function constructComment(array $item, array $owner)
3769 $cachekey = "diaspora:constructComment:".$item['guid'];
3771 $result = Cache::get($cachekey);
3772 if (!is_null($result)) {
3776 $parent = Item::selectFirst(['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3777 if (!DBA::isResult($parent)) {
3781 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3782 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3784 $comment = ["author" => self::myHandle($owner),
3785 "guid" => $item["guid"],
3786 "created_at" => $created,
3787 "parent_guid" => $parent["guid"],
3789 "author_signature" => ""];
3791 // Send the thread parent guid only if it is a threaded comment
3792 if ($item['thr-parent'] != $item['parent-uri']) {
3793 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3796 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3802 * @brief Send a like or a comment
3804 * @param array $item The item that will be exported
3805 * @param array $owner the array of the item owner
3806 * @param array $contact Target of the communication
3807 * @param bool $public_batch Is it a public post?
3809 * @return int The result of the transmission
3810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3811 * @throws \ImagickException
3813 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3815 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3816 $message = self::constructAttend($item, $owner);
3817 $type = "event_participation";
3818 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3819 $message = self::constructLike($item, $owner);
3821 } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW])) {
3822 $message = self::constructComment($item, $owner);
3826 if (empty($message)) {
3830 $message["author_signature"] = self::signature($owner, $message);
3832 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3836 * @brief Creates a message from a signature record entry
3838 * @param array $item The item that will be exported
3839 * @return array The message
3841 private static function messageFromSignature(array $item)
3843 // Split the signed text
3844 $signed_parts = explode(";", $item['signed_text']);
3846 if ($item["deleted"]) {
3847 $message = ["author" => $item['signer'],
3848 "target_guid" => $signed_parts[0],
3849 "target_type" => $signed_parts[1]];
3850 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3851 $message = ["author" => $signed_parts[4],
3852 "guid" => $signed_parts[1],
3853 "parent_guid" => $signed_parts[3],
3854 "parent_type" => $signed_parts[2],
3855 "positive" => $signed_parts[0],
3856 "author_signature" => $item['signature'],
3857 "parent_author_signature" => ""];
3859 // Remove the comment guid
3860 $guid = array_shift($signed_parts);
3862 // Remove the parent guid
3863 $parent_guid = array_shift($signed_parts);
3865 // Remove the handle
3866 $handle = array_pop($signed_parts);
3869 "author" => $handle,
3871 "parent_guid" => $parent_guid,
3872 "text" => implode(";", $signed_parts),
3873 "author_signature" => $item['signature'],
3874 "parent_author_signature" => ""
3881 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3883 * @param array $item The item that will be exported
3884 * @param array $owner the array of the item owner
3885 * @param array $contact Target of the communication
3886 * @param bool $public_batch Is it a public post?
3888 * @return int The result of the transmission
3889 * @throws \Exception
3891 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3893 if ($item["deleted"]) {
3894 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3895 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3901 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3903 // Old way - is used by the internal Friendica functions
3904 /// @todo Change all signatur storing functions to the new format
3905 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
3906 $message = self::messageFromSignature($item);
3908 $msg = json_decode($item['signed_text'], true);
3911 if (is_array($msg)) {
3912 foreach ($msg as $field => $data) {
3913 if (!$item["deleted"]) {
3914 if ($field == "diaspora_handle") {
3917 if ($field == "target_type") {
3918 $field = "parent_type";
3922 $message[$field] = $data;
3925 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3929 $message["parent_author_signature"] = self::signature($owner, $message);
3931 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
3933 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3937 * @brief Sends a retraction (deletion) of a message, like or comment
3939 * @param array $item The item that will be exported
3940 * @param array $owner the array of the item owner
3941 * @param array $contact Target of the communication
3942 * @param bool $public_batch Is it a public post?
3943 * @param bool $relay Is the retraction transmitted from a relay?
3945 * @return int The result of the transmission
3946 * @throws \Exception
3948 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3950 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3952 $msg_type = "retraction";
3954 if ($item['id'] == $item['parent']) {
3955 $target_type = "Post";
3956 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3957 $target_type = "Like";
3959 $target_type = "Comment";
3962 $message = ["author" => $itemaddr,
3963 "target_guid" => $item['guid'],
3964 "target_type" => $target_type];
3966 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
3968 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3972 * @brief Sends a mail
3974 * @param array $item The item that will be exported
3975 * @param array $owner The owner
3976 * @param array $contact Target of the communication
3978 * @return int The result of the transmission
3979 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3980 * @throws \ImagickException
3982 public static function sendMail(array $item, array $owner, array $contact)
3984 $myaddr = self::myHandle($owner);
3986 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3987 if (!DBA::isResult($cnv)) {
3988 Logger::log("conversation not found.");
3992 $body = BBCode::toMarkdown($item["body"]);
3993 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3996 "author" => $myaddr,
3997 "guid" => $item["guid"],
3998 "conversation_guid" => $cnv["guid"],
4000 "created_at" => $created,
4003 if ($item["reply"]) {
4008 "author" => $cnv["creator"],
4009 "guid" => $cnv["guid"],
4010 "subject" => $cnv["subject"],
4011 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4012 "participants" => $cnv["recips"],
4016 $type = "conversation";
4019 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4023 * @brief Split a name into first name and last name
4025 * @param string $name The name
4027 * @return array The array with "first" and "last"
4029 public static function splitName($name) {
4030 $name = trim($name);
4032 // Is the name longer than 64 characters? Then cut the rest of it.
4033 if (strlen($name) > 64) {
4034 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4035 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4037 $name = substr($name, 0, 64);
4041 // Take the first word as first name
4042 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4043 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4044 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4045 return ['first' => $first, 'last' => $last];
4048 // Take the last word as last name
4049 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4050 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4052 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4053 return ['first' => $first, 'last' => $last];
4056 // Take the first 32 characters if there is no space in the first 32 characters
4057 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4058 $first = substr($name, 0, 32);
4059 $last = substr($name, 32);
4060 return ['first' => $first, 'last' => $last];
4063 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4064 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4066 // Check if the last name is longer than 32 characters
4067 if (strlen($last) > 32) {
4068 if (strpos($last, ' ') <= 32) {
4069 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4071 $last = substr($last, 0, 32);
4075 return ['first' => $first, 'last' => $last];
4079 * @brief Create profile data
4081 * @param int $uid The user id
4083 * @return array The profile data
4084 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4086 private static function createProfileData($uid)
4089 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4091 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4092 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4093 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4102 $handle = $profile["addr"];
4104 $split_name = self::splitName($profile['name']);
4105 $first = $split_name['first'];
4106 $last = $split_name['last'];
4108 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4109 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4110 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4111 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4117 if ($searchable === 'true') {
4120 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4121 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4125 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4128 $about = $profile['about'];
4129 $about = strip_tags(BBCode::convert($about));
4131 $location = Profile::formatLocation($profile);
4133 if ($profile['pub_keywords']) {
4134 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4135 $kw = str_replace(' ', ' ', $kw);
4136 $arr = explode(' ', $kw);
4138 for ($x = 0; $x < 5; $x ++) {
4139 if (!empty($arr[$x])) {
4140 $tags .= '#'. trim($arr[$x]) .' ';
4145 $tags = trim($tags);
4148 return ["author" => $handle,
4149 "first_name" => $first,
4150 "last_name" => $last,
4151 "image_url" => $large,
4152 "image_url_medium" => $medium,
4153 "image_url_small" => $small,
4155 "gender" => $profile['gender'],
4157 "location" => $location,
4158 "searchable" => $searchable,
4160 "tag_string" => $tags];
4164 * @brief Sends profile data
4166 * @param int $uid The user id
4167 * @param bool $recips optional, default false
4169 * @throws \Exception
4171 public static function sendProfile($uid, $recips = false)
4177 $owner = User::getOwnerDataById($uid);
4184 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4185 AND `uid` = %d AND `rel` != %d",
4186 DBA::escape(Protocol::DIASPORA),
4188 intval(Contact::SHARING)
4196 $message = self::createProfileData($uid);
4198 foreach ($recips as $recip) {
4199 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4200 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4205 * @brief Creates the signature for likes that are created on our system
4207 * @param integer $uid The user of that comment
4208 * @param array $item Item array
4210 * @return array Signed content
4211 * @throws \Exception
4213 public static function createLikeSignature($uid, array $item)
4215 $owner = User::getOwnerDataById($uid);
4216 if (empty($owner)) {
4217 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4221 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4225 $message = self::constructLike($item, $owner);
4226 if ($message === false) {
4230 $message["author_signature"] = self::signature($owner, $message);
4236 * @brief Creates the signature for Comments that are created on our system
4238 * @param integer $uid The user of that comment
4239 * @param array $item Item array
4241 * @return array Signed content
4242 * @throws \Exception
4244 public static function createCommentSignature($uid, array $item)
4246 $owner = User::getOwnerDataById($uid);
4247 if (empty($owner)) {
4248 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4252 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4253 $item['thr-parent'] = $item['parent-uri'];
4255 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4256 if (!DBA::isResult($parent)) {
4260 $item['parent-uri'] = $parent['parent-uri'];
4262 $message = self::constructComment($item, $owner);
4263 if ($message === false) {
4267 $message["author_signature"] = self::signature($owner, $message);