3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GContact;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\Probe;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Map;
47 use Friendica\Util\Network;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
50 use Friendica\Worker\Delivery;
54 * This class contain functions to create and send Diaspora XML files
59 * Mark the relay contact of the given contact for archival
60 * This is called whenever there is a communication issue with the server.
61 * It avoids sending stuff to servers who don't exist anymore.
62 * The relay contact is a technical contact entry that exists once per server.
64 * @param array $contact of the relay contact
66 public static function markRelayForArchival(array $contact)
68 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
69 // This is already the relay contact, we don't need to fetch it
70 $relay_contact = $contact;
71 } elseif (empty($contact['baseurl'])) {
72 if (!empty($contact['batch'])) {
73 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
74 $relay_contact = DBA::selectFirst('contact', [], $condition);
79 $relay_contact = self::getRelayContact($contact['baseurl'], []);
82 if (!empty($relay_contact)) {
83 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
84 Contact::markForArchival($relay_contact);
89 * Return a list of relay servers
91 * The list contains not only the official relays but also servers that we serve directly
93 * @param integer $item_id The id of the item that is sent
94 * @param array $contacts The previously fetched contacts
96 * @return array of relay servers
97 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
99 public static function relayList($item_id, array $contacts = [])
103 // Fetching relay servers
104 $serverdata = DI::config()->get("system", "relay_server");
106 if (!empty($serverdata)) {
107 $servers = explode(",", $serverdata);
108 foreach ($servers as $server) {
109 $serverlist[$server] = trim($server);
113 if (DI::config()->get("system", "relay_directly", false)) {
114 // We distribute our stuff based on the parent to ensure that the thread will be complete
115 $parent = Item::selectFirst(['uri-id'], ['id' => $item_id]);
116 if (!DBA::isResult($parent)) {
120 // Servers that want to get all content
121 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
122 while ($server = DBA::fetch($servers)) {
123 $serverlist[$server['url']] = $server['url'];
125 DBA::close($servers);
127 // All tags of the current post
128 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
130 while ($tag = DBA::fetch($tags)) {
131 $taglist[] = $tag['name'];
135 // All servers who wants content with this tag
137 if (!empty($taglist)) {
138 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
139 while ($server = DBA::fetch($tagserver)) {
140 $tagserverlist[] = $server['gserver-id'];
142 DBA::close($tagserver);
145 // All adresses with the given id
146 if (!empty($tagserverlist)) {
147 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
148 while ($server = DBA::fetch($servers)) {
149 $serverlist[$server['url']] = $server['url'];
151 DBA::close($servers);
155 // Now we are collecting all relay contacts
156 foreach ($serverlist as $server_url) {
157 // We don't send messages to ourselves
158 if (Strings::compareLink($server_url, DI::baseUrl())) {
161 $contact = self::getRelayContact($server_url);
162 if (is_bool($contact)) {
167 foreach ($contacts as $entry) {
168 if ($entry['batch'] == $contact['batch']) {
174 $contacts[] = $contact;
182 * Return a contact for a given server address or creates a dummy entry
184 * @param string $server_url The url of the server
185 * @param array $fields Fieldlist
186 * @return array with the contact
189 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
191 // Fetch the relay contact
192 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
193 'contact-type' => Contact::TYPE_RELAY];
194 $contact = DBA::selectFirst('contact', $fields, $condition);
196 if (DBA::isResult($contact)) {
197 if ($contact['archive'] || $contact['blocked']) {
202 self::setRelayContact($server_url);
204 $contact = DBA::selectFirst('contact', $fields, $condition);
205 if (DBA::isResult($contact)) {
210 // It should never happen that we arrive here
215 * Update or insert a relay contact
217 * @param string $server_url The url of the server
218 * @param array $network_fields Optional network specific fields
221 public static function setRelayContact($server_url, array $network_fields = [])
223 $fields = ['created' => DateTimeFormat::utcNow(),
224 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
225 'nurl' => Strings::normaliseLink($server_url),
226 'network' => Protocol::DIASPORA, 'uid' => 0,
227 'batch' => $server_url . '/receive/public',
228 'rel' => Contact::FOLLOWER, 'blocked' => false,
229 'pending' => false, 'writable' => true,
230 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
232 $fields = array_merge($fields, $network_fields);
234 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
235 $old = DBA::selectFirst('contact', [], $condition);
236 if (DBA::isResult($old)) {
237 unset($fields['created']);
238 $condition = ['id' => $old['id']];
240 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
241 DBA::update('contact', $fields, $condition, $old);
243 Logger::info('Create relay contact', ['fields' => $fields]);
244 Contact::insert($fields);
249 * Return a list of participating contacts for a thread
251 * This is used for the participation feature.
252 * One of the parameters is a contact array.
253 * This is done to avoid duplicates.
255 * @param array $item Item that is about to be delivered
256 * @param array $contacts The previously fetched contacts
258 * @return array of relay servers
261 public static function participantsForThread(array $item, array $contacts)
263 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
264 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
268 $items = Item::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
269 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
270 while ($item = DBA::fetch($items)) {
271 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
272 ['id' => $item['author-id']]);
273 if (!DBA::isResult($contact) || empty($contact['batch']) ||
274 ($contact['network'] != Protocol::DIASPORA) ||
275 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
280 foreach ($contacts as $entry) {
281 if ($entry['batch'] == $contact['batch']) {
287 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
288 $contacts[] = $contact;
297 * repairs a signature that was double encoded
299 * The function is unused at the moment. It was copied from the old implementation.
301 * @param string $signature The signature
302 * @param string $handle The handle of the signature owner
303 * @param integer $level This value is only set inside this function to avoid endless loops
305 * @return string the repaired signature
308 private static function repairSignature($signature, $handle = "", $level = 1)
310 if ($signature == "") {
314 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
315 $signature = base64_decode($signature);
316 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
318 // Do a recursive call to be able to fix even multiple levels
320 $signature = self::repairSignature($signature, $handle, ++$level);
328 * verify the envelope and return the verified data
330 * @param string $envelope The magic envelope
332 * @return string verified data
333 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
334 * @throws \ImagickException
336 private static function verifyMagicEnvelope($envelope)
338 $basedom = XML::parseString($envelope, true);
340 if (!is_object($basedom)) {
341 Logger::log("Envelope is no XML file");
345 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
347 if (sizeof($children) == 0) {
348 Logger::log("XML has no children");
354 $data = Strings::base64UrlDecode($children->data);
355 $type = $children->data->attributes()->type[0];
357 $encoding = $children->encoding;
359 $alg = $children->alg;
361 $sig = Strings::base64UrlDecode($children->sig);
362 $key_id = $children->sig->attributes()->key_id[0];
364 $handle = Strings::base64UrlDecode($key_id);
367 $b64url_data = Strings::base64UrlEncode($data);
368 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
370 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
373 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
377 $key = self::key($handle);
379 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
383 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
385 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
393 * encrypts data via AES
395 * @param string $key The AES key
396 * @param string $iv The IV (is used for CBC encoding)
397 * @param string $data The data that is to be encrypted
399 * @return string encrypted data
401 private static function aesEncrypt($key, $iv, $data)
403 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
407 * decrypts data via AES
409 * @param string $key The AES key
410 * @param string $iv The IV (is used for CBC encoding)
411 * @param string $encrypted The encrypted data
413 * @return string decrypted data
415 private static function aesDecrypt($key, $iv, $encrypted)
417 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
421 * Decodes incoming Diaspora message in the new format
423 * @param string $raw raw post message
424 * @param string $privKey The private key of the importer
425 * @param boolean $no_exit Don't do an http exit on error
428 * 'message' -> decoded Diaspora XML message
429 * 'author' -> author diaspora handle
430 * 'key' -> author public key (converted to pkcs#8)
431 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
432 * @throws \ImagickException
434 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
436 $data = json_decode($raw);
438 // Is it a private post? Then decrypt the outer Salmon
439 if (is_object($data)) {
440 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
441 $ciphertext = base64_decode($data->encrypted_magic_envelope);
443 $outer_key_bundle = '';
444 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
445 $j_outer_key_bundle = json_decode($outer_key_bundle);
447 if (!is_object($j_outer_key_bundle)) {
448 Logger::log('Outer Salmon did not verify. Discarding.');
452 throw new \Friendica\Network\HTTPException\BadRequestException();
456 $outer_iv = base64_decode($j_outer_key_bundle->iv);
457 $outer_key = base64_decode($j_outer_key_bundle->key);
459 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
464 $basedom = XML::parseString($xml, true);
466 if (!is_object($basedom)) {
467 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
471 throw new \Friendica\Network\HTTPException\BadRequestException();
475 $base = $basedom->children(ActivityNamespace::SALMON_ME);
477 // Not sure if this cleaning is needed
478 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
480 // Build the signed data
481 $type = $base->data[0]->attributes()->type[0];
482 $encoding = $base->encoding;
484 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
486 // This is the signature
487 $signature = Strings::base64UrlDecode($base->sig);
489 // Get the senders' public key
490 $key_id = $base->sig[0]->attributes()->key_id[0];
491 $author_addr = base64_decode($key_id);
492 if ($author_addr == '') {
493 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
497 throw new \Friendica\Network\HTTPException\BadRequestException();
501 $key = self::key($author_addr);
503 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
507 throw new \Friendica\Network\HTTPException\BadRequestException();
511 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
513 Logger::log('Message did not verify. Discarding.');
517 throw new \Friendica\Network\HTTPException\BadRequestException();
521 return ['message' => (string)Strings::base64UrlDecode($base->data),
522 'author' => XML::unescape($author_addr),
523 'key' => (string)$key];
527 * Decodes incoming Diaspora message in the deprecated format
529 * @param string $xml urldecoded Diaspora salmon
530 * @param string $privKey The private key of the importer
533 * 'message' -> decoded Diaspora XML message
534 * 'author' -> author diaspora handle
535 * 'key' -> author public key (converted to pkcs#8)
536 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
537 * @throws \ImagickException
539 public static function decode(string $xml, string $privKey = '')
542 $basedom = XML::parseString($xml);
544 if (!is_object($basedom)) {
545 Logger::log("XML is not parseable.");
548 $children = $basedom->children('https://joindiaspora.com/protocol');
550 $inner_aes_key = null;
553 if ($children->header) {
555 $author_link = str_replace('acct:', '', $children->header->author_id);
557 // This happens with posts from a relais
558 if (empty($privKey)) {
559 Logger::log("This is no private post in the old format", Logger::DEBUG);
563 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
565 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
566 $ciphertext = base64_decode($encrypted_header->ciphertext);
568 $outer_key_bundle = '';
569 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
571 $j_outer_key_bundle = json_decode($outer_key_bundle);
573 $outer_iv = base64_decode($j_outer_key_bundle->iv);
574 $outer_key = base64_decode($j_outer_key_bundle->key);
576 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
578 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
579 $idom = XML::parseString($decrypted);
581 $inner_iv = base64_decode($idom->iv);
582 $inner_aes_key = base64_decode($idom->aes_key);
584 $author_link = str_replace('acct:', '', $idom->author_id);
587 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
589 // figure out where in the DOM tree our data is hiding
592 if ($dom->provenance->data) {
593 $base = $dom->provenance;
594 } elseif ($dom->env->data) {
596 } elseif ($dom->data) {
601 Logger::log('unable to locate salmon data in xml');
602 throw new \Friendica\Network\HTTPException\BadRequestException();
606 // Stash the signature away for now. We have to find their key or it won't be good for anything.
607 $signature = Strings::base64UrlDecode($base->sig);
611 // strip whitespace so our data element will return to one big base64 blob
612 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
615 // stash away some other stuff for later
617 $type = $base->data[0]->attributes()->type[0];
618 $keyhash = $base->sig[0]->attributes()->keyhash[0];
619 $encoding = $base->encoding;
623 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
627 $data = Strings::base64UrlDecode($data);
631 $inner_decrypted = $data;
633 // Decode the encrypted blob
634 $inner_encrypted = base64_decode($data);
635 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
639 Logger::log('Could not retrieve author URI.');
640 throw new \Friendica\Network\HTTPException\BadRequestException();
642 // Once we have the author URI, go to the web and try to find their public key
643 // (first this will look it up locally if it is in the fcontact cache)
644 // This will also convert diaspora public key from pkcs#1 to pkcs#8
646 Logger::log('Fetching key for '.$author_link);
647 $key = self::key($author_link);
650 Logger::log('Could not retrieve author key.');
651 throw new \Friendica\Network\HTTPException\BadRequestException();
654 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
657 Logger::log('Message did not verify. Discarding.');
658 throw new \Friendica\Network\HTTPException\BadRequestException();
661 Logger::log('Message verified.');
663 return ['message' => (string)$inner_decrypted,
664 'author' => XML::unescape($author_link),
665 'key' => (string)$key];
670 * Dispatches public messages and find the fitting receivers
672 * @param array $msg The post that will be dispatched
674 * @return int The message id of the generated message, "true" or "false" if there was an error
675 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
676 * @throws \ImagickException
678 public static function dispatchPublic($msg)
680 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
682 Logger::log("diaspora is disabled");
686 if (!($fields = self::validPosting($msg))) {
687 Logger::log("Invalid posting");
691 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
692 $success = self::dispatch($importer, $msg, $fields);
698 * Dispatches the different message types to the different functions
700 * @param array $importer Array of the importer user
701 * @param array $msg The post that will be dispatched
702 * @param SimpleXMLElement $fields SimpleXML object that contains the message
704 * @return int The message id of the generated message, "true" or "false" if there was an error
705 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
706 * @throws \ImagickException
708 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
710 // The sender is the handle of the contact that sent the message.
711 // This will often be different with relayed messages (for example "like" and "comment")
712 $sender = $msg["author"];
714 // This is only needed for private postings since this is already done for public ones before
715 if (is_null($fields)) {
717 if (!($fields = self::validPosting($msg))) {
718 Logger::log("Invalid posting");
725 $type = $fields->getName();
727 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
730 case "account_migration":
732 Logger::log('Message with type ' . $type . ' is not private, quitting.');
735 return self::receiveAccountMigration($importer, $fields);
737 case "account_deletion":
738 return self::receiveAccountDeletion($fields);
741 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
745 Logger::log('Message with type ' . $type . ' is not private, quitting.');
748 return self::receiveContactRequest($importer, $fields);
752 Logger::log('Message with type ' . $type . ' is not private, quitting.');
755 return self::receiveConversation($importer, $msg, $fields);
758 return self::receiveLike($importer, $sender, $fields);
762 Logger::log('Message with type ' . $type . ' is not private, quitting.');
765 return self::receiveMessage($importer, $fields);
767 case "participation":
769 Logger::log('Message with type ' . $type . ' is not private, quitting.');
772 return self::receiveParticipation($importer, $fields);
774 case "photo": // Not implemented
775 return self::receivePhoto($importer, $fields);
777 case "poll_participation": // Not implemented
778 return self::receivePollParticipation($importer, $fields);
782 Logger::log('Message with type ' . $type . ' is not private, quitting.');
785 return self::receiveProfile($importer, $fields);
788 return self::receiveReshare($importer, $fields, $msg["message"]);
791 return self::receiveRetraction($importer, $sender, $fields);
793 case "status_message":
794 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
797 Logger::log("Unknown message type ".$type);
803 * Checks if a posting is valid and fetches the data fields.
805 * This function does not only check the signature.
806 * It also does the conversion between the old and the new diaspora format.
808 * @param array $msg Array with the XML, the sender handle and the sender signature
810 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
812 * @throws \ImagickException
814 private static function validPosting($msg)
816 $data = XML::parseString($msg["message"]);
818 if (!is_object($data)) {
819 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
823 // Is this the new or the old version?
824 if ($data->getName() == "XML") {
826 foreach ($data->post->children() as $child) {
834 $type = $element->getName();
837 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
839 // All retractions are handled identically from now on.
840 // In the new version there will only be "retraction".
841 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
842 $type = "retraction";
844 if ($type == "request") {
848 $fields = new SimpleXMLElement("<".$type."/>");
851 $author_signature = null;
852 $parent_author_signature = null;
854 foreach ($element->children() as $fieldname => $entry) {
856 // Translation for the old XML structure
857 if ($fieldname == "diaspora_handle") {
858 $fieldname = "author";
860 if ($fieldname == "participant_handles") {
861 $fieldname = "participants";
863 if (in_array($type, ["like", "participation"])) {
864 if ($fieldname == "target_type") {
865 $fieldname = "parent_type";
868 if ($fieldname == "sender_handle") {
869 $fieldname = "author";
871 if ($fieldname == "recipient_handle") {
872 $fieldname = "recipient";
874 if ($fieldname == "root_diaspora_id") {
875 $fieldname = "root_author";
877 if ($type == "status_message") {
878 if ($fieldname == "raw_message") {
882 if ($type == "retraction") {
883 if ($fieldname == "post_guid") {
884 $fieldname = "target_guid";
886 if ($fieldname == "type") {
887 $fieldname = "target_type";
892 if (($fieldname == "author_signature") && ($entry != "")) {
893 $author_signature = base64_decode($entry);
894 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
895 $parent_author_signature = base64_decode($entry);
896 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
897 if ($signed_data != "") {
901 $signed_data .= $entry;
903 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
904 || ($orig_type == "relayable_retraction")
906 XML::copy($entry, $fields, $fieldname);
910 // This is something that shouldn't happen at all.
911 if (in_array($type, ["status_message", "reshare", "profile"])) {
912 if ($msg["author"] != $fields->author) {
913 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
918 // Only some message types have signatures. So we quit here for the other types.
919 if (!in_array($type, ["comment", "like"])) {
922 // No author_signature? This is a must, so we quit.
923 if (!isset($author_signature)) {
924 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
928 if (isset($parent_author_signature)) {
929 $key = self::key($msg["author"]);
931 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
935 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
936 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);
941 $key = self::key($fields->author);
943 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
947 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
948 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);
956 * Fetches the public key for a given handle
958 * @param string $handle The handle
960 * @return string The public key
961 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
962 * @throws \ImagickException
964 private static function key($handle)
966 $handle = strval($handle);
968 Logger::log("Fetching diaspora key for: ".$handle);
970 $r = self::personByHandle($handle);
979 * Fetches data for a given handle
981 * @param string $handle The handle
982 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
984 * @return array the queried data
985 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
986 * @throws \ImagickException
988 public static function personByHandle($handle, $update = null)
990 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
991 if (!DBA::isResult($person)) {
992 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
993 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
996 if (DBA::isResult($person)) {
997 Logger::debug("In cache " . print_r($person, true));
999 if (is_null($update)) {
1000 // update record occasionally so it doesn't get stale
1001 $d = strtotime($person["updated"]." +00:00");
1002 if ($d < strtotime("now - 14 days")) {
1006 if ($person["guid"] == "") {
1010 } elseif (is_null($update)) {
1011 $update = !DBA::isResult($person);
1017 Logger::log("create or refresh", Logger::DEBUG);
1018 $r = Probe::uri($handle, Protocol::DIASPORA);
1020 // Note that Friendica contacts will return a "Diaspora person"
1021 // if Diaspora connectivity is enabled on their server
1022 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1023 self::updateFContact($r);
1025 $person = self::personByHandle($handle, false);
1033 * Updates the fcontact table
1035 * @param array $arr The fcontact data
1036 * @throws \Exception
1038 private static function updateFContact($arr)
1040 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1041 'request' => $arr["request"], 'nick' => $arr["nick"],
1042 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1043 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1044 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1045 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1046 'updated' => DateTimeFormat::utcNow()];
1048 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1050 DBA::update('fcontact', $fields, $condition, true);
1054 * get a handle (user@domain.tld) from a given contact id
1056 * @param int $contact_id The id in the contact table
1057 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1059 * @return string the handle
1060 * @throws \Exception
1062 private static function handleFromContact($contact_id, $pcontact_id = 0)
1066 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1068 if ($pcontact_id != 0) {
1069 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1071 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1072 return strtolower($contact["addr"]);
1077 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1081 if (DBA::isResult($r)) {
1084 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1086 if ($contact['addr'] != "") {
1087 $handle = $contact['addr'];
1089 $baseurl_start = strpos($contact['url'], '://') + 3;
1090 // allows installations in a subdirectory--not sure how Diaspora will handle
1091 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1092 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1093 $handle = $contact['nick'].'@'.$baseurl;
1097 return strtolower($handle);
1101 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1104 * @param mixed $fcontact_guid Hexadecimal string guid
1106 * @return string the contact url or null
1107 * @throws \Exception
1109 public static function urlFromContactGuid($fcontact_guid)
1111 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1114 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1115 DBA::escape(Protocol::DIASPORA),
1116 DBA::escape($fcontact_guid)
1119 if (DBA::isResult($r)) {
1120 return $r[0]['url'];
1127 * Get a contact id for a given handle
1129 * @todo Move to Friendica\Model\Contact
1131 * @param int $uid The user id
1132 * @param string $handle The handle in the format user@domain.tld
1134 * @return array Contact data
1135 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1136 * @throws \ImagickException
1138 private static function contactByHandle($uid, $handle)
1140 $cid = Contact::getIdForURL($handle, $uid);
1142 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1146 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1147 if (!DBA::isResult($contact)) {
1148 // This here shouldn't happen at all
1149 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1157 * Checks if the given contact url does support ActivityPub
1159 * @param string $url profile url
1160 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1162 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1163 * @throws \ImagickException
1165 public static function isSupportedByContactUrl($url, $update = null)
1167 return !empty(self::personByHandle($url, $update));
1171 * Check if posting is allowed for this contact
1173 * @param array $importer Array of the importer user
1174 * @param array $contact The contact that is checked
1175 * @param bool $is_comment Is the check for a comment?
1177 * @return bool is the contact allowed to post?
1179 private static function postAllow(array $importer, array $contact, $is_comment = false)
1182 * Perhaps we were already sharing with this person. Now they're sharing with us.
1183 * That makes us friends.
1184 * Normally this should have handled by getting a request - but this could get lost
1186 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1187 // It is not removed by now. Possibly the code is needed?
1188 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1191 // array('rel' => Contact::FRIEND, 'writable' => true),
1192 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1195 // $contact["rel"] = Contact::FRIEND;
1196 // Logger::log("defining user ".$contact["nick"]." as friend");
1199 // Contact server is blocked
1200 if (Network::isUrlBlocked($contact['url'])) {
1202 // We don't seem to like that person
1203 } elseif ($contact["blocked"]) {
1204 // Maybe blocked, don't accept.
1206 // We are following this person?
1207 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1208 // Yes, then it is fine.
1210 // Is it a post to a community?
1211 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1214 // Is the message a global user or a comment?
1215 } elseif (($importer["uid"] == 0) || $is_comment) {
1216 // Messages for the global users and comments are always accepted
1224 * Fetches the contact id for a handle and checks if posting is allowed
1226 * @param array $importer Array of the importer user
1227 * @param string $handle The checked handle in the format user@domain.tld
1228 * @param bool $is_comment Is the check for a comment?
1230 * @return array The contact data
1231 * @throws \Exception
1233 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1235 $contact = self::contactByHandle($importer["uid"], $handle);
1237 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1238 // If a contact isn't found, we accept it anyway if it is a comment
1239 if ($is_comment && ($importer["uid"] != 0)) {
1240 return self::contactByHandle(0, $handle);
1241 } elseif ($is_comment) {
1248 if (!self::postAllow($importer, $contact, $is_comment)) {
1249 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1256 * Does the message already exists on the system?
1258 * @param int $uid The user id
1259 * @param string $guid The guid of the message
1261 * @return int|bool message id if the message already was stored into the system - or false.
1262 * @throws \Exception
1264 private static function messageExists($uid, $guid)
1266 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1267 if (DBA::isResult($item)) {
1268 Logger::log("message ".$guid." already exists for user ".$uid);
1276 * Checks for links to posts in a message
1278 * @param array $item The item array
1281 private static function fetchGuid(array $item)
1283 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1284 preg_replace_callback(
1286 function ($match) use ($item) {
1287 self::fetchGuidSub($match, $item);
1292 preg_replace_callback(
1293 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1294 function ($match) use ($item) {
1295 self::fetchGuidSub($match, $item);
1302 * Checks for relative /people/* links in an item body to match local
1303 * contacts or prepends the remote host taken from the author link.
1305 * @param string $body The item body to replace links from
1306 * @param string $author_link The author link for missing local contact fallback
1308 * @return string the replaced string
1310 public static function replacePeopleGuid($body, $author_link)
1312 $return = preg_replace_callback(
1313 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1314 function ($match) use ($author_link) {
1316 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1317 // 1 => '0123456789abcdef'
1319 $handle = self::urlFromContactGuid($match[1]);
1322 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1324 // No local match, restoring absolute remote URL from author scheme and host
1325 $author_url = parse_url($author_link);
1326 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1338 * sub function of "fetchGuid" which checks for links in messages
1340 * @param array $match array containing a link that has to be checked for a message link
1341 * @param array $item The item array
1343 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1344 * @throws \ImagickException
1346 private static function fetchGuidSub($match, $item)
1348 if (!self::storeByGuid($match[1], $item["author-link"])) {
1349 self::storeByGuid($match[1], $item["owner-link"]);
1354 * Fetches an item with a given guid from a given server
1356 * @param string $guid the message guid
1357 * @param string $server The server address
1358 * @param int $uid The user id of the user
1360 * @return int the message id of the stored message or false
1361 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1362 * @throws \ImagickException
1364 private static function storeByGuid($guid, $server, $uid = 0)
1366 $serverparts = parse_url($server);
1368 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1372 $server = $serverparts["scheme"]."://".$serverparts["host"];
1374 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1376 $msg = self::message($guid, $server);
1382 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1384 // Now call the dispatcher
1385 return self::dispatchPublic($msg);
1389 * Fetches a message from a server
1391 * @param string $guid message guid
1392 * @param string $server The url of the server
1393 * @param int $level Endless loop prevention
1396 * 'message' => The message XML
1397 * 'author' => The author handle
1398 * 'key' => The public key of the author
1399 * @throws \Exception
1401 private static function message($guid, $server, $level = 0)
1407 // This will work for new Diaspora servers and Friendica servers from 3.5
1408 $source_url = $server."/fetch/post/".urlencode($guid);
1410 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1412 $envelope = Network::fetchUrl($source_url);
1414 Logger::log("Envelope was fetched.", Logger::DEBUG);
1415 $x = self::verifyMagicEnvelope($envelope);
1417 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1419 Logger::log("Envelope was verified.", Logger::DEBUG);
1429 $source_xml = XML::parseString($x);
1431 if (!is_object($source_xml)) {
1435 if ($source_xml->post->reshare) {
1436 // Reshare of a reshare - old Diaspora version
1437 Logger::log("Message is a reshare", Logger::DEBUG);
1438 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1439 } elseif ($source_xml->getName() == "reshare") {
1440 // Reshare of a reshare - new Diaspora version
1441 Logger::log("Message is a new reshare", Logger::DEBUG);
1442 return self::message($source_xml->root_guid, $server, ++$level);
1447 // Fetch the author - for the old and the new Diaspora version
1448 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1449 $author = (string)$source_xml->post->status_message->diaspora_handle;
1450 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1451 $author = (string)$source_xml->author;
1454 // If this isn't a "status_message" then quit
1456 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1460 $msg = ["message" => $x, "author" => $author];
1462 $msg["key"] = self::key($msg["author"]);
1468 * Fetches an item with a given URL
1470 * @param string $url the message url
1472 * @return int the message id of the stored message or false
1473 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1474 * @throws \ImagickException
1476 public static function fetchByURL($url, $uid = 0)
1478 // Check for Diaspora (and Friendica) typical paths
1479 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1480 Logger::info('Invalid url', ['url' => $url]);
1484 $guid = urldecode($matches[2]);
1486 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1487 if (DBA::isResult($item)) {
1488 Logger::info('Found', ['id' => $item['id']]);
1492 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1493 $ret = self::storeByGuid($guid, $matches[1], $uid);
1494 Logger::info('Result', ['ret' => $ret]);
1496 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1497 if (DBA::isResult($item)) {
1498 Logger::info('Found', ['id' => $item['id']]);
1501 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1507 * Fetches the item record of a given guid
1509 * @param int $uid The user id
1510 * @param string $guid message guid
1511 * @param string $author The handle of the item
1512 * @param array $contact The contact of the item owner
1514 * @return array the item record
1515 * @throws \Exception
1517 private static function parentItem($uid, $guid, $author, array $contact)
1519 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1520 'author-name', 'author-link', 'author-avatar', 'gravity',
1521 'owner-name', 'owner-link', 'owner-avatar'];
1522 $condition = ['uid' => $uid, 'guid' => $guid];
1523 $item = Item::selectFirst($fields, $condition);
1525 if (!DBA::isResult($item)) {
1526 $person = self::personByHandle($author);
1527 $result = self::storeByGuid($guid, $person["url"], $uid);
1529 // We don't have an url for items that arrived at the public dispatcher
1530 if (!$result && !empty($contact["url"])) {
1531 $result = self::storeByGuid($guid, $contact["url"], $uid);
1535 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1537 $item = Item::selectFirst($fields, $condition);
1541 if (!DBA::isResult($item)) {
1542 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1545 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1551 * returns contact details
1553 * @param array $def_contact The default contact if the person isn't found
1554 * @param array $person The record of the person
1555 * @param int $uid The user id
1558 * 'cid' => contact id
1559 * 'network' => network type
1560 * @throws \Exception
1562 private static function authorContactByUrl($def_contact, $person, $uid)
1564 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1565 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1566 if (DBA::isResult($contact)) {
1567 $cid = $contact["id"];
1568 $network = $contact["network"];
1570 $cid = $def_contact["id"];
1571 $network = Protocol::DIASPORA;
1574 return ["cid" => $cid, "network" => $network];
1578 * Is the profile a hubzilla profile?
1580 * @param string $url The profile link
1582 * @return bool is it a hubzilla server?
1584 private static function isHubzilla($url)
1586 return(strstr($url, '/channel/'));
1590 * Generate a post link with a given handle and message guid
1592 * @param string $addr The user handle
1593 * @param string $guid message guid
1594 * @param string $parent_guid optional parent guid
1596 * @return string the post link
1597 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1598 * @throws \ImagickException
1600 private static function plink($addr, $guid, $parent_guid = '')
1602 $contact = Contact::getDetailsByAddr($addr);
1603 if (empty($contact)) {
1604 Logger::info('No contact data for address', ['addr' => $addr]);
1608 if (empty($contact['baseurl'])) {
1609 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1610 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1614 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1615 if (!empty($gserver['platform'])) {
1616 $platform = strtolower($gserver['platform']);
1617 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1620 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1621 if (self::isHubzilla($contact['url'])) {
1622 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1623 $platform = 'hubzilla';
1624 } elseif ($contact['network'] == Protocol::DFRN) {
1625 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1626 $platform = 'friendica';
1630 if ($platform == 'friendica') {
1631 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1634 if ($platform == 'hubzilla') {
1635 return $contact['baseurl'] . '/item/' . $guid;
1638 if ($platform == 'socialhome') {
1639 return $contact['baseurl'] . '/content/' . $guid;
1642 if ($platform != 'diaspora') {
1643 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1647 if ($parent_guid != '') {
1648 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1650 return $contact['baseurl'] . '/posts/' . $guid;
1655 * Receives account migration
1657 * @param array $importer Array of the importer user
1658 * @param object $data The message object
1660 * @return bool Success
1661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1662 * @throws \ImagickException
1664 private static function receiveAccountMigration(array $importer, $data)
1666 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1667 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1668 $signature = Strings::escapeTags(XML::unescape($data->signature));
1670 $contact = self::contactByHandle($importer["uid"], $old_handle);
1672 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1676 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1679 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1680 $key = self::key($old_handle);
1681 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1682 Logger::log('No valid signature for migration.');
1686 // Update the profile
1687 self::receiveProfile($importer, $data->profile);
1689 // change the technical stuff in contact and gcontact
1690 $data = Probe::uri($new_handle);
1691 if ($data['network'] == Protocol::PHANTOM) {
1692 Logger::log('Account for '.$new_handle." couldn't be probed.");
1696 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1697 'name' => $data['name'], 'nick' => $data['nick'],
1698 'addr' => $data['addr'], 'batch' => $data['batch'],
1699 'notify' => $data['notify'], 'poll' => $data['poll'],
1700 'network' => $data['network']];
1702 DBA::update('contact', $fields, ['addr' => $old_handle]);
1704 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1705 'name' => $data['name'], 'nick' => $data['nick'],
1706 'addr' => $data['addr'], 'connect' => $data['addr'],
1707 'notify' => $data['notify'], 'photo' => $data['photo'],
1708 'server_url' => $data['baseurl'], 'network' => $data['network']];
1710 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1712 Logger::log('Contacts are updated.');
1718 * Processes an account deletion
1720 * @param object $data The message object
1722 * @return bool Success
1723 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1725 private static function receiveAccountDeletion($data)
1727 $author = Strings::escapeTags(XML::unescape($data->author));
1729 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1730 while ($contact = DBA::fetch($contacts)) {
1731 Contact::remove($contact["id"]);
1733 DBA::close($contacts);
1735 DBA::delete('gcontact', ['addr' => $author]);
1737 Logger::log('Removed contacts for ' . $author);
1743 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1745 * @param string $author Author handle
1746 * @param string $guid Message guid
1747 * @param boolean $onlyfound Only return uri when found in the database
1749 * @return string The constructed uri or the one from our database
1750 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1751 * @throws \ImagickException
1753 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1755 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1756 if (DBA::isResult($item)) {
1757 return $item["uri"];
1758 } elseif (!$onlyfound) {
1759 $person = self::personByHandle($author);
1761 $parts = parse_url($person['url']);
1762 unset($parts['path']);
1763 $host_url = Network::unparseURL($parts);
1765 return $host_url . '/objects/' . $guid;
1772 * Fetch the guid from our database with a given uri
1774 * @param string $uri Message uri
1775 * @param string $uid Author handle
1777 * @return string The post guid
1778 * @throws \Exception
1780 private static function getGuidFromUri($uri, $uid)
1782 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1783 if (DBA::isResult($item)) {
1784 return $item["guid"];
1791 * Find the best importer for a comment, like, ...
1793 * @param string $guid The guid of the item
1795 * @return array|boolean the origin owner of that post - or false
1796 * @throws \Exception
1798 private static function importerForGuid($guid)
1800 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1801 if (DBA::isResult($item)) {
1802 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1803 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1804 if (DBA::isResult($contact)) {
1812 * Store the mentions in the tag table
1814 * @param integer $uriid
1815 * @param string $text
1817 private static function storeMentions(int $uriid, string $text)
1819 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1820 if (empty($matches)) {
1825 * Matching values for the preg match
1826 * [1] = mention type (@ or !)
1827 * [2] = name (optional)
1831 foreach ($matches as $match) {
1832 if (empty($match)) {
1836 $person = self::personByHandle($match[3]);
1837 if (empty($person)) {
1841 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1846 * Processes an incoming comment
1848 * @param array $importer Array of the importer user
1849 * @param string $sender The sender of the message
1850 * @param object $data The message object
1851 * @param string $xml The original XML of the message
1853 * @return int The message id of the generated comment or "false" if there was an error
1854 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1855 * @throws \ImagickException
1857 private static function receiveComment(array $importer, $sender, $data, $xml)
1859 $author = Strings::escapeTags(XML::unescape($data->author));
1860 $guid = Strings::escapeTags(XML::unescape($data->guid));
1861 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1862 $text = XML::unescape($data->text);
1864 if (isset($data->created_at)) {
1865 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1867 $created_at = DateTimeFormat::utcNow();
1870 if (isset($data->thread_parent_guid)) {
1871 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1872 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1877 $contact = self::allowedContactByHandle($importer, $sender, true);
1882 $message_id = self::messageExists($importer["uid"], $guid);
1887 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1888 if (!$parent_item) {
1892 $person = self::personByHandle($author);
1893 if (!is_array($person)) {
1894 Logger::log("unable to find author details");
1898 // Fetch the contact id - if we know this contact
1899 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1903 $datarray["uid"] = $importer["uid"];
1904 $datarray["contact-id"] = $author_contact["cid"];
1905 $datarray["network"] = $author_contact["network"];
1907 $datarray["author-link"] = $person["url"];
1908 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1910 $datarray["owner-link"] = $contact["url"];
1911 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1913 $datarray["guid"] = $guid;
1914 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1915 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1917 $datarray["verb"] = Activity::POST;
1918 $datarray["gravity"] = GRAVITY_COMMENT;
1920 if ($thr_uri != "") {
1921 $datarray["parent-uri"] = $thr_uri;
1923 $datarray["parent-uri"] = $parent_item["uri"];
1926 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1928 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1929 $datarray["source"] = $xml;
1931 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1933 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1934 $body = Markdown::toBBCode($text);
1936 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1938 self::storeMentions($datarray['uri-id'], $text);
1939 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1941 self::fetchGuid($datarray);
1943 // If we are the origin of the parent we store the original data.
1944 // We notify our followers during the item storage.
1945 if ($parent_item["origin"]) {
1946 $datarray['diaspora_signed_text'] = json_encode($data);
1949 $message_id = Item::insert($datarray);
1951 if ($message_id <= 0) {
1956 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1957 if ($datarray['uid'] == 0) {
1958 Item::distribute($message_id, json_encode($data));
1966 * processes and stores private messages
1968 * @param array $importer Array of the importer user
1969 * @param array $contact The contact of the message
1970 * @param object $data The message object
1971 * @param array $msg Array of the processed message, author handle and key
1972 * @param object $mesg The private message
1973 * @param array $conversation The conversation record to which this message belongs
1975 * @return bool "true" if it was successful
1976 * @throws \Exception
1978 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1980 $author = Strings::escapeTags(XML::unescape($data->author));
1981 $guid = Strings::escapeTags(XML::unescape($data->guid));
1982 $subject = Strings::escapeTags(XML::unescape($data->subject));
1984 // "diaspora_handle" is the element name from the old version
1985 // "author" is the element name from the new version
1986 if ($mesg->author) {
1987 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1988 } elseif ($mesg->diaspora_handle) {
1989 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1994 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1995 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1996 $msg_text = XML::unescape($mesg->text);
1997 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1999 if ($msg_conversation_guid != $guid) {
2000 Logger::log("message conversation guid does not belong to the current conversation.");
2004 $body = Markdown::toBBCode($msg_text);
2005 $message_uri = $msg_author.":".$msg_guid;
2007 $person = self::personByHandle($msg_author);
2009 return Mail::insert([
2010 'uid' => $importer['uid'],
2011 'guid' => $msg_guid,
2012 'convid' => $conversation['id'],
2013 'from-name' => $person['name'],
2014 'from-photo' => $person['photo'],
2015 'from-url' => $person['url'],
2016 'contact-id' => $contact['id'],
2017 'title' => $subject,
2019 'uri' => $message_uri,
2020 'parent-uri' => $author . ':' . $guid,
2021 'created' => $msg_created_at
2026 * Processes new private messages (answers to private messages are processed elsewhere)
2028 * @param array $importer Array of the importer user
2029 * @param array $msg Array of the processed message, author handle and key
2030 * @param object $data The message object
2032 * @return bool Success
2033 * @throws \Exception
2035 private static function receiveConversation(array $importer, $msg, $data)
2037 $author = Strings::escapeTags(XML::unescape($data->author));
2038 $guid = Strings::escapeTags(XML::unescape($data->guid));
2039 $subject = Strings::escapeTags(XML::unescape($data->subject));
2040 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2041 $participants = Strings::escapeTags(XML::unescape($data->participants));
2043 $messages = $data->message;
2045 if (!count($messages)) {
2046 Logger::log("empty conversation");
2050 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2055 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2056 if (!DBA::isResult($conversation)) {
2058 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2059 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2060 intval($importer["uid"]),
2062 DBA::escape($author),
2063 DBA::escape($created_at),
2064 DBA::escape(DateTimeFormat::utcNow()),
2065 DBA::escape($subject),
2066 DBA::escape($participants)
2069 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2072 if (!$conversation) {
2073 Logger::log("unable to create conversation.");
2077 foreach ($messages as $mesg) {
2078 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2085 * Processes "like" messages
2087 * @param array $importer Array of the importer user
2088 * @param string $sender The sender of the message
2089 * @param object $data The message object
2091 * @return int The message id of the generated like or "false" if there was an error
2092 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2093 * @throws \ImagickException
2095 private static function receiveLike(array $importer, $sender, $data)
2097 $author = Strings::escapeTags(XML::unescape($data->author));
2098 $guid = Strings::escapeTags(XML::unescape($data->guid));
2099 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2100 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2101 $positive = Strings::escapeTags(XML::unescape($data->positive));
2103 // likes on comments aren't supported by Diaspora - only on posts
2104 // But maybe this will be supported in the future, so we will accept it.
2105 if (!in_array($parent_type, ["Post", "Comment"])) {
2109 $contact = self::allowedContactByHandle($importer, $sender, true);
2114 $message_id = self::messageExists($importer["uid"], $guid);
2119 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2120 if (!$parent_item) {
2124 $person = self::personByHandle($author);
2125 if (!is_array($person)) {
2126 Logger::log("unable to find author details");
2130 // Fetch the contact id - if we know this contact
2131 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2133 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2134 // We would accept this anyhow.
2135 if ($positive == "true") {
2136 $verb = Activity::LIKE;
2138 $verb = Activity::DISLIKE;
2143 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2145 $datarray["uid"] = $importer["uid"];
2146 $datarray["contact-id"] = $author_contact["cid"];
2147 $datarray["network"] = $author_contact["network"];
2149 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2150 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2152 $datarray["guid"] = $guid;
2153 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2155 $datarray["verb"] = $verb;
2156 $datarray["gravity"] = GRAVITY_ACTIVITY;
2157 $datarray["parent-uri"] = $parent_item["uri"];
2159 $datarray["object-type"] = Activity\ObjectType::NOTE;
2161 $datarray["body"] = $verb;
2163 // Diaspora doesn't provide a date for likes
2164 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2166 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2167 if ($parent_item['gravity'] != GRAVITY_PARENT) {
2168 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item['parent']]);
2169 $origin = $toplevel["origin"];
2171 $origin = $parent_item["origin"];
2174 // If we are the origin of the parent we store the original data.
2175 // We notify our followers during the item storage.
2177 $datarray['diaspora_signed_text'] = json_encode($data);
2180 $message_id = Item::insert($datarray);
2182 if ($message_id <= 0) {
2187 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2188 if ($datarray['uid'] == 0) {
2189 Item::distribute($message_id, json_encode($data));
2197 * Processes private messages
2199 * @param array $importer Array of the importer user
2200 * @param object $data The message object
2202 * @return bool Success?
2203 * @throws \Exception
2205 private static function receiveMessage(array $importer, $data)
2207 $author = Strings::escapeTags(XML::unescape($data->author));
2208 $guid = Strings::escapeTags(XML::unescape($data->guid));
2209 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2210 $text = XML::unescape($data->text);
2211 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2213 $contact = self::allowedContactByHandle($importer, $author, true);
2218 $conversation = null;
2220 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2221 $conversation = DBA::selectFirst('conv', [], $condition);
2223 if (!DBA::isResult($conversation)) {
2224 Logger::log("conversation not available.");
2228 $message_uri = $author.":".$guid;
2230 $person = self::personByHandle($author);
2232 Logger::log("unable to find author details");
2236 $body = Markdown::toBBCode($text);
2238 $body = self::replacePeopleGuid($body, $person["url"]);
2240 return Mail::insert([
2241 'uid' => $importer['uid'],
2243 'convid' => $conversation['id'],
2244 'from-name' => $person['name'],
2245 'from-photo' => $person['photo'],
2246 'from-url' => $person['url'],
2247 'contact-id' => $contact['id'],
2248 'title' => $conversation['subject'],
2251 'uri' => $message_uri,
2252 'parent-uri' => $author.":".$conversation['guid'],
2253 'created' => $created_at
2258 * Processes participations - unsupported by now
2260 * @param array $importer Array of the importer user
2261 * @param object $data The message object
2263 * @return bool success
2264 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2265 * @throws \ImagickException
2267 private static function receiveParticipation(array $importer, $data)
2269 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2270 $guid = Strings::escapeTags(XML::unescape($data->guid));
2271 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2273 $contact = self::allowedContactByHandle($importer, $author, true);
2278 if (self::messageExists($importer["uid"], $guid)) {
2282 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2283 if (!$parent_item) {
2287 if (!$parent_item['origin']) {
2288 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2291 if (!in_array($parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
2292 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2296 $person = self::personByHandle($author);
2297 if (!is_array($person)) {
2298 Logger::log("Person not found: ".$author);
2302 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2304 // Store participation
2307 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2309 $datarray["uid"] = $importer["uid"];
2310 $datarray["contact-id"] = $author_contact["cid"];
2311 $datarray["network"] = $author_contact["network"];
2313 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2314 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2316 $datarray["guid"] = $guid;
2317 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2319 $datarray["verb"] = Activity::FOLLOW;
2320 $datarray["gravity"] = GRAVITY_ACTIVITY;
2321 $datarray["parent-uri"] = $parent_item["uri"];
2323 $datarray["object-type"] = Activity\ObjectType::NOTE;
2325 $datarray["body"] = Activity::FOLLOW;
2327 // Diaspora doesn't provide a date for a participation
2328 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2330 $message_id = Item::insert($datarray);
2332 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2334 // Send all existing comments and likes to the requesting server
2335 $comments = Item::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
2336 ['parent' => $parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
2337 while ($comment = Item::fetch($comments)) {
2338 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2339 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2343 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2344 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2348 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2349 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2353 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2354 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2355 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2358 DBA::close($comments);
2364 * Processes photos - unneeded
2366 * @param array $importer Array of the importer user
2367 * @param object $data The message object
2369 * @return bool always true
2371 private static function receivePhoto(array $importer, $data)
2373 // There doesn't seem to be a reason for this function,
2374 // since the photo data is transmitted in the status message as well
2379 * Processes poll participations - unssupported
2381 * @param array $importer Array of the importer user
2382 * @param object $data The message object
2384 * @return bool always true
2386 private static function receivePollParticipation(array $importer, $data)
2388 // We don't support polls by now
2393 * Processes incoming profile updates
2395 * @param array $importer Array of the importer user
2396 * @param object $data The message object
2398 * @return bool Success
2399 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2400 * @throws \ImagickException
2402 private static function receiveProfile(array $importer, $data)
2404 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2406 $contact = self::contactByHandle($importer["uid"], $author);
2411 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2412 $image_url = XML::unescape($data->image_url);
2413 $birthday = XML::unescape($data->birthday);
2414 $about = Markdown::toBBCode(XML::unescape($data->bio));
2415 $location = Markdown::toBBCode(XML::unescape($data->location));
2416 $searchable = (XML::unescape($data->searchable) == "true");
2417 $nsfw = (XML::unescape($data->nsfw) == "true");
2418 $tags = XML::unescape($data->tag_string);
2420 $tags = explode("#", $tags);
2423 foreach ($tags as $tag) {
2424 $tag = trim(strtolower($tag));
2430 $keywords = implode(", ", $keywords);
2432 $handle_parts = explode("@", $author);
2433 $nick = $handle_parts[0];
2436 $name = $handle_parts[0];
2439 if (preg_match("|^https?://|", $image_url) === 0) {
2440 $image_url = "http://".$handle_parts[1].$image_url;
2443 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2445 // Generic birthday. We don't know the timezone. The year is irrelevant.
2447 $birthday = str_replace("1000", "1901", $birthday);
2449 if ($birthday != "") {
2450 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2453 // this is to prevent multiple birthday notifications in a single year
2454 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2456 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2457 $birthday = $contact["bd"];
2460 $fields = ['name' => $name, 'location' => $location,
2461 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2462 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2463 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2465 if (!empty($birthday)) {
2466 $fields['bd'] = $birthday;
2469 DBA::update('contact', $fields, ['id' => $contact['id']]);
2471 // @todo Update the public contact, then update the gcontact from that
2473 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2474 "photo" => $image_url, "name" => $name, "location" => $location,
2475 "about" => $about, "birthday" => $birthday,
2476 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2477 "hide" => !$searchable, "nsfw" => $nsfw];
2479 $gcid = GContact::update($gcontact);
2481 GContact::link($gcid, $importer["uid"], $contact["id"]);
2483 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2489 * Processes incoming friend requests
2491 * @param array $importer Array of the importer user
2492 * @param array $contact The contact that send the request
2494 * @throws \Exception
2496 private static function receiveRequestMakeFriend(array $importer, array $contact)
2498 if ($contact["rel"] == Contact::SHARING) {
2501 ['rel' => Contact::FRIEND, 'writable' => true],
2502 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2508 * Processes incoming sharing notification
2510 * @param array $importer Array of the importer user
2511 * @param object $data The message object
2513 * @return bool Success
2514 * @throws \Exception
2516 private static function receiveContactRequest(array $importer, $data)
2518 $author = XML::unescape($data->author);
2519 $recipient = XML::unescape($data->recipient);
2521 if (!$author || !$recipient) {
2525 // the current protocol version doesn't know these fields
2526 // That means that we will assume their existance
2527 if (isset($data->following)) {
2528 $following = (XML::unescape($data->following) == "true");
2533 if (isset($data->sharing)) {
2534 $sharing = (XML::unescape($data->sharing) == "true");
2539 $contact = self::contactByHandle($importer["uid"], $author);
2541 // perhaps we were already sharing with this person. Now they're sharing with us.
2542 // That makes us friends.
2545 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2546 self::receiveRequestMakeFriend($importer, $contact);
2548 // refetch the contact array
2549 $contact = self::contactByHandle($importer["uid"], $author);
2551 // If we are now friends, we are sending a share message.
2552 // Normally we needn't to do so, but the first message could have been vanished.
2553 if (in_array($contact["rel"], [Contact::FRIEND])) {
2554 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2555 if (DBA::isResult($user)) {
2556 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2557 self::sendShare($user, $contact);
2562 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2563 Contact::removeFollower($importer, $contact);
2568 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2569 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2571 } elseif (!$following && !$sharing) {
2572 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2574 } elseif (!$following && $sharing) {
2575 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2576 } elseif ($following && $sharing) {
2577 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2578 } elseif ($following && !$sharing) {
2579 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2582 $ret = self::personByHandle($author);
2584 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2585 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2589 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2591 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2596 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2597 'author-link' => $ret['url']];
2599 $result = Contact::addRelationship($importer, $contact, $item, false);
2600 if ($result === true) {
2601 $contact_record = self::contactByHandle($importer['uid'], $author);
2602 if (!$contact_record) {
2603 Logger::info('unable to locate newly created contact record.');
2607 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2608 if (DBA::isResult($user)) {
2609 self::sendShare($user, $contact_record);
2611 // Send the profile data, maybe it weren't transmitted before
2612 self::sendProfile($importer['uid'], [$contact_record]);
2620 * Fetches a message with a given guid
2622 * @param string $guid message guid
2623 * @param string $orig_author handle of the original post
2624 * @return array The fetched item
2625 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2626 * @throws \ImagickException
2628 public static function originalItem($guid, $orig_author)
2631 Logger::log('Empty guid. Quitting.');
2635 // Do we already have this item?
2636 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2637 'author-name', 'author-link', 'author-avatar'];
2638 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2639 $item = Item::selectFirst($fields, $condition);
2641 if (DBA::isResult($item)) {
2642 Logger::log("reshared message ".$guid." already exists on system.");
2644 // Maybe it is already a reshared item?
2645 // Then refetch the content, if it is a reshare from a reshare.
2646 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2647 if (self::isReshare($item["body"], true)) {
2649 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2650 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2652 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2654 // Add OEmbed and other information to the body
2655 $item["body"] = add_page_info_to_body($item["body"], false, true);
2663 if (!DBA::isResult($item)) {
2664 if (empty($orig_author)) {
2665 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2669 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2670 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2671 $stored = self::storeByGuid($guid, $server);
2674 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2675 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2676 $stored = self::storeByGuid($guid, $server);
2680 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2681 'author-name', 'author-link', 'author-avatar'];
2682 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2683 $item = Item::selectFirst($fields, $condition);
2685 if (DBA::isResult($item)) {
2686 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2687 if (self::isReshare($item["body"], false)) {
2688 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2689 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2700 * Stores a reshare activity
2702 * @param array $item Array of reshare post
2703 * @param integer $parent_message_id Id of the parent post
2704 * @param string $guid GUID string of reshare action
2705 * @param string $author Author handle
2707 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2709 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2713 $datarray['uid'] = $item['uid'];
2714 $datarray['contact-id'] = $item['contact-id'];
2715 $datarray['network'] = $item['network'];
2717 $datarray['author-link'] = $item['author-link'];
2718 $datarray['author-id'] = $item['author-id'];
2720 $datarray['owner-link'] = $datarray['author-link'];
2721 $datarray['owner-id'] = $datarray['author-id'];
2723 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2724 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2725 $datarray['parent-uri'] = $parent['uri'];
2727 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2728 $datarray['gravity'] = GRAVITY_ACTIVITY;
2729 $datarray['object-type'] = Activity\ObjectType::NOTE;
2731 $datarray['protocol'] = $item['protocol'];
2733 $datarray['plink'] = self::plink($author, $datarray['guid']);
2734 $datarray['private'] = $item['private'];
2735 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2737 $message_id = Item::insert($datarray);
2740 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2741 if ($datarray['uid'] == 0) {
2742 Item::distribute($message_id);
2748 * Processes a reshare message
2750 * @param array $importer Array of the importer user
2751 * @param object $data The message object
2752 * @param string $xml The original XML of the message
2754 * @return int the message id
2755 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2756 * @throws \ImagickException
2758 private static function receiveReshare(array $importer, $data, $xml)
2760 $author = Strings::escapeTags(XML::unescape($data->author));
2761 $guid = Strings::escapeTags(XML::unescape($data->guid));
2762 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2763 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2764 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2765 /// @todo handle unprocessed property "provider_display_name"
2766 $public = Strings::escapeTags(XML::unescape($data->public));
2768 $contact = self::allowedContactByHandle($importer, $author, false);
2773 $message_id = self::messageExists($importer["uid"], $guid);
2778 $original_item = self::originalItem($root_guid, $root_author);
2779 if (!$original_item) {
2783 $orig_url = DI::baseUrl()."/display/".$original_item["guid"];
2787 $datarray["uid"] = $importer["uid"];
2788 $datarray["contact-id"] = $contact["id"];
2789 $datarray["network"] = Protocol::DIASPORA;
2791 $datarray["author-link"] = $contact["url"];
2792 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2794 $datarray["owner-link"] = $datarray["author-link"];
2795 $datarray["owner-id"] = $datarray["author-id"];
2797 $datarray["guid"] = $guid;
2798 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2799 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2801 $datarray["verb"] = Activity::POST;
2802 $datarray["gravity"] = GRAVITY_PARENT;
2804 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2805 $datarray["source"] = $xml;
2807 /// @todo Copy tag data from original post
2809 $prefix = BBCode::getShareOpeningTag(
2810 $original_item["author-name"],
2811 $original_item["author-link"],
2812 $original_item["author-avatar"],
2814 $original_item["created"],
2815 $original_item["guid"]
2818 if (!empty($original_item['title'])) {
2819 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2822 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2824 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2826 $datarray["attach"] = $original_item["attach"];
2827 $datarray["app"] = $original_item["app"];
2829 $datarray["plink"] = self::plink($author, $guid);
2830 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2831 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2833 $datarray["object-type"] = $original_item["object-type"];
2835 self::fetchGuid($datarray);
2836 $message_id = Item::insert($datarray);
2838 self::sendParticipation($contact, $datarray);
2840 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2841 if ($root_message_id) {
2842 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2846 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2847 if ($datarray['uid'] == 0) {
2848 Item::distribute($message_id);
2857 * Processes retractions
2859 * @param array $importer Array of the importer user
2860 * @param array $contact The contact of the item owner
2861 * @param object $data The message object
2863 * @return bool success
2864 * @throws \Exception
2866 private static function itemRetraction(array $importer, array $contact, $data)
2868 $author = Strings::escapeTags(XML::unescape($data->author));
2869 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2870 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2872 $person = self::personByHandle($author);
2873 if (!is_array($person)) {
2874 Logger::log("unable to find author detail for ".$author);
2878 if (empty($contact["url"])) {
2879 $contact["url"] = $person["url"];
2882 // Fetch items that are about to be deleted
2883 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2885 // When we receive a public retraction, we delete every item that we find.
2886 if ($importer['uid'] == 0) {
2887 $condition = ['guid' => $target_guid, 'deleted' => false];
2889 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2892 $r = Item::select($fields, $condition);
2893 if (!DBA::isResult($r)) {
2894 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2898 while ($item = Item::fetch($r)) {
2899 if (strstr($item['file'], '[')) {
2900 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2904 // Fetch the parent item
2905 $parent = Item::selectFirst(['author-link'], ['id' => $item['parent']]);
2907 // Only delete it if the parent author really fits
2908 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2909 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2913 Item::markForDeletion(['id' => $item['id']]);
2915 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent'], Logger::DEBUG);
2922 * Receives retraction messages
2924 * @param array $importer Array of the importer user
2925 * @param string $sender The sender of the message
2926 * @param object $data The message object
2928 * @return bool Success
2929 * @throws \Exception
2931 private static function receiveRetraction(array $importer, $sender, $data)
2933 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2935 $contact = self::contactByHandle($importer["uid"], $sender);
2936 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2937 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2945 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2947 switch ($target_type) {
2952 case "StatusMessage":
2953 return self::itemRetraction($importer, $contact, $data);
2955 case "PollParticipation":
2957 // Currently unsupported
2961 Logger::log("Unknown target type ".$target_type);
2968 * Receives status messages
2970 * @param array $importer Array of the importer user
2971 * @param SimpleXMLElement $data The message object
2972 * @param string $xml The original XML of the message
2974 * @return int The message id of the newly created item
2975 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2976 * @throws \ImagickException
2978 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2980 $author = Strings::escapeTags(XML::unescape($data->author));
2981 $guid = Strings::escapeTags(XML::unescape($data->guid));
2982 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2983 $public = Strings::escapeTags(XML::unescape($data->public));
2984 $text = XML::unescape($data->text);
2985 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2987 $contact = self::allowedContactByHandle($importer, $author, false);
2992 $message_id = self::messageExists($importer["uid"], $guid);
2998 if ($data->location) {
2999 foreach ($data->location->children() as $fieldname => $data) {
3000 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
3004 $body = Markdown::toBBCode($text);
3008 // Attach embedded pictures to the body
3010 foreach ($data->photo as $photo) {
3011 $body = "[img]".XML::unescape($photo->remote_photo_path).
3012 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
3015 $datarray["object-type"] = Activity\ObjectType::IMAGE;
3017 $datarray["object-type"] = Activity\ObjectType::NOTE;
3019 // Add OEmbed and other information to the body
3020 if (!self::isHubzilla($contact["url"])) {
3021 $body = add_page_info_to_body($body, false, true);
3025 /// @todo enable support for polls
3026 //if ($data->poll) {
3027 // foreach ($data->poll AS $poll)
3032 /// @todo enable support for events
3034 $datarray["uid"] = $importer["uid"];
3035 $datarray["contact-id"] = $contact["id"];
3036 $datarray["network"] = Protocol::DIASPORA;
3038 $datarray["author-link"] = $contact["url"];
3039 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
3041 $datarray["owner-link"] = $datarray["author-link"];
3042 $datarray["owner-id"] = $datarray["author-id"];
3044 $datarray["guid"] = $guid;
3045 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3046 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
3048 $datarray["verb"] = Activity::POST;
3049 $datarray["gravity"] = GRAVITY_PARENT;
3051 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3052 $datarray["source"] = $xml;
3054 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3056 self::storeMentions($datarray['uri-id'], $text);
3057 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
3059 if ($provider_display_name != "") {
3060 $datarray["app"] = $provider_display_name;
3063 $datarray["plink"] = self::plink($author, $guid);
3064 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3065 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3067 if (isset($address["address"])) {
3068 $datarray["location"] = $address["address"];
3071 if (isset($address["lat"]) && isset($address["lng"])) {
3072 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3075 self::fetchGuid($datarray);
3076 $message_id = Item::insert($datarray);
3078 self::sendParticipation($contact, $datarray);
3081 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3082 if ($datarray['uid'] == 0) {
3083 Item::distribute($message_id);
3091 /* ************************************************************************************** *
3092 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3093 * ************************************************************************************** */
3096 * returnes the handle of a contact
3098 * @param array $contact contact array
3100 * @return string the handle in the format user@domain.tld
3101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3103 private static function myHandle(array $contact)
3105 if (!empty($contact["addr"])) {
3106 return $contact["addr"];
3109 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3110 // So - just in case - we build the the address here.
3111 if ($contact["nickname"] != "") {
3112 $nick = $contact["nickname"];
3114 $nick = $contact["nick"];
3117 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3122 * Creates the data for a private message in the new format
3124 * @param string $msg The message that is to be transmitted
3125 * @param array $user The record of the sender
3126 * @param array $contact Target of the communication
3127 * @param string $prvkey The private key of the sender
3128 * @param string $pubkey The public key of the receiver
3130 * @return string The encrypted data
3131 * @throws \Exception
3133 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3135 Logger::log("Message: ".$msg, Logger::DATA);
3137 // without a public key nothing will work
3139 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3143 $aes_key = openssl_random_pseudo_bytes(32);
3144 $b_aes_key = base64_encode($aes_key);
3145 $iv = openssl_random_pseudo_bytes(16);
3146 $b_iv = base64_encode($iv);
3148 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3150 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3152 $encrypted_key_bundle = "";
3153 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
3157 $json_object = json_encode(
3158 ["aes_key" => base64_encode($encrypted_key_bundle),
3159 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3162 return $json_object;
3166 * Creates the envelope for the "fetch" endpoint and for the new format
3168 * @param string $msg The message that is to be transmitted
3169 * @param array $user The record of the sender
3171 * @return string The envelope
3172 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3174 public static function buildMagicEnvelope($msg, array $user)
3176 $b64url_data = Strings::base64UrlEncode($msg);
3177 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3179 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3180 $type = "application/xml";
3181 $encoding = "base64url";
3182 $alg = "RSA-SHA256";
3183 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3185 // Fallback if the private key wasn't transmitted in the expected field
3186 if ($user['uprvkey'] == "") {
3187 $user['uprvkey'] = $user['prvkey'];
3190 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3191 $sig = Strings::base64UrlEncode($signature);
3193 $xmldata = ["me:env" => ["me:data" => $data,
3194 "@attributes" => ["type" => $type],
3195 "me:encoding" => $encoding,
3198 "@attributes2" => ["key_id" => $key_id]]];
3200 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3202 return XML::fromArray($xmldata, $xml, false, $namespaces);
3206 * Create the envelope for a message
3208 * @param string $msg The message that is to be transmitted
3209 * @param array $user The record of the sender
3210 * @param array $contact Target of the communication
3211 * @param string $prvkey The private key of the sender
3212 * @param string $pubkey The public key of the receiver
3213 * @param bool $public Is the message public?
3215 * @return string The message that will be transmitted to other servers
3216 * @throws \Exception
3218 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3220 // The message is put into an envelope with the sender's signature
3221 $envelope = self::buildMagicEnvelope($msg, $user);
3223 // Private messages are put into a second envelope, encrypted with the receivers public key
3225 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3232 * Creates a signature for a message
3234 * @param array $owner the array of the owner of the message
3235 * @param array $message The message that is to be signed
3237 * @return string The signature
3239 private static function signature($owner, $message)
3242 unset($sigmsg["author_signature"]);
3243 unset($sigmsg["parent_author_signature"]);
3245 $signed_text = implode(";", $sigmsg);
3247 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3251 * Transmit a message to a target server
3253 * @param array $owner the array of the item owner
3254 * @param array $contact Target of the communication
3255 * @param string $envelope The message that is to be transmitted
3256 * @param bool $public_batch Is it a public post?
3257 * @param string $guid message guid
3259 * @return int Result of the transmission
3260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3261 * @throws \ImagickException
3263 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3265 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3270 $logid = Strings::getRandomHex(4);
3272 // We always try to use the data from the fcontact table.
3273 // This is important for transmitting data to Friendica servers.
3274 if (!empty($contact['addr'])) {
3275 $fcontact = self::personByHandle($contact['addr']);
3276 if (!empty($fcontact)) {
3277 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3281 if (empty($dest_url)) {
3282 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3286 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3290 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3292 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3293 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3295 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3296 $return_code = $postResult->getReturnCode();
3298 Logger::log("test_mode");
3302 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3304 return $return_code ? $return_code : -1;
3309 * Build the post xml
3311 * @param string $type The message type
3312 * @param array $message The message data
3314 * @return string The post XML
3316 public static function buildPostXml($type, $message)
3318 $data = [$type => $message];
3320 return XML::fromArray($data, $xml);
3324 * Builds and transmit messages
3326 * @param array $owner the array of the item owner
3327 * @param array $contact Target of the communication
3328 * @param string $type The message type
3329 * @param array $message The message data
3330 * @param bool $public_batch Is it a public post?
3331 * @param string $guid message guid
3333 * @return int Result of the transmission
3334 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3335 * @throws \ImagickException
3337 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3339 $msg = self::buildPostXml($type, $message);
3341 Logger::log('message: '.$msg, Logger::DATA);
3342 Logger::log('send guid '.$guid, Logger::DEBUG);
3344 // Fallback if the private key wasn't transmitted in the expected field
3345 if (empty($owner['uprvkey'])) {
3346 $owner['uprvkey'] = $owner['prvkey'];
3349 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3351 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3353 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3355 return $return_code;
3359 * sends a participation (Used to get all further updates)
3361 * @param array $contact Target of the communication
3362 * @param array $item Item array
3364 * @return int The result of the transmission
3365 * @throws \Exception
3367 private static function sendParticipation(array $contact, array $item)
3369 // Don't send notifications for private postings
3370 if ($item['private'] == Item::PRIVATE) {
3374 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3376 $result = DI::cache()->get($cachekey);
3377 if (!is_null($result)) {
3381 // Fetch some user id to have a valid handle to transmit the participation.
3382 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3383 // If the item belongs to a user, we take this user id.
3384 if ($item['uid'] == 0) {
3385 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3386 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3387 $owner = User::getOwnerDataById($first_user['uid']);
3389 $owner = User::getOwnerDataById($item['uid']);
3392 $author = self::myHandle($owner);
3394 $message = ["author" => $author,
3395 "guid" => System::createUUID(),
3396 "parent_type" => "Post",
3397 "parent_guid" => $item["guid"]];
3399 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3401 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3402 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3404 return self::buildAndTransmit($owner, $contact, "participation", $message);
3408 * sends an account migration
3410 * @param array $owner the array of the item owner
3411 * @param array $contact Target of the communication
3412 * @param int $uid User ID
3414 * @return int The result of the transmission
3415 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3416 * @throws \ImagickException
3418 public static function sendAccountMigration(array $owner, array $contact, $uid)
3420 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3421 $profile = self::createProfileData($uid);
3423 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3424 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3426 $message = ["author" => $old_handle,
3427 "profile" => $profile,
3428 "signature" => $signature];
3430 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3432 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3436 * Sends a "share" message
3438 * @param array $owner the array of the item owner
3439 * @param array $contact Target of the communication
3441 * @return int The result of the transmission
3442 * @throws \Exception
3444 public static function sendShare(array $owner, array $contact)
3447 * @todo support the different possible combinations of "following" and "sharing"
3448 * Currently, Diaspora only interprets the "sharing" field
3450 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3454 switch ($contact["rel"]) {
3455 case Contact::FRIEND:
3459 case Contact::SHARING:
3463 case Contact::FOLLOWER:
3469 $message = ["author" => self::myHandle($owner),
3470 "recipient" => $contact["addr"],
3471 "following" => "true",
3472 "sharing" => "true"];
3474 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3476 return self::buildAndTransmit($owner, $contact, "contact", $message);
3480 * sends an "unshare"
3482 * @param array $owner the array of the item owner
3483 * @param array $contact Target of the communication
3485 * @return int The result of the transmission
3486 * @throws \Exception
3488 public static function sendUnshare(array $owner, array $contact)
3490 $message = ["author" => self::myHandle($owner),
3491 "recipient" => $contact["addr"],
3492 "following" => "false",
3493 "sharing" => "false"];
3495 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3497 return self::buildAndTransmit($owner, $contact, "contact", $message);
3501 * Checks a message body if it is a reshare
3503 * @param string $body The message body that is to be check
3504 * @param bool $complete Should it be a complete check or a simple check?
3506 * @return array|bool Reshare details or "false" if no reshare
3507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3508 * @throws \ImagickException
3510 public static function isReshare($body, $complete = true)
3512 $body = trim($body);
3514 $reshared = Item::getShareArray(['body' => $body]);
3515 if (empty($reshared)) {
3519 // Skip if it isn't a pure repeated messages
3520 // Does it start with a share?
3521 if (!empty($reshared['comment']) && $complete) {
3525 if (!empty($reshared['guid']) && $complete) {
3526 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3527 $item = Item::selectFirst(['contact-id'], $condition);
3528 if (DBA::isResult($item)) {
3530 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3531 $ret["root_guid"] = $reshared['guid'];
3533 } elseif ($complete) {
3534 // We are resharing something that isn't a DFRN or Diaspora post.
3535 // So we have to return "false" on "$complete" to not trigger a reshare.
3538 } elseif (empty($reshared['guid']) && $complete) {
3544 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3545 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3546 if (!empty($contact['addr'])) {
3547 $ret['root_handle'] = $contact['addr'];
3551 if (empty($ret) && !$complete) {
3559 * Create an event array
3561 * @param integer $event_id The id of the event
3563 * @return array with event data
3564 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3566 private static function buildEvent($event_id)
3568 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3569 if (!DBA::isResult($r)) {
3577 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3578 if (!DBA::isResult($r)) {
3584 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3585 if (!DBA::isResult($r)) {
3591 $eventdata['author'] = self::myHandle($owner);
3593 if ($event['guid']) {
3594 $eventdata['guid'] = $event['guid'];
3597 $mask = DateTimeFormat::ATOM;
3599 /// @todo - establish "all day" events in Friendica
3600 $eventdata["all_day"] = "false";
3602 $eventdata['timezone'] = 'UTC';
3603 if (!$event['adjust'] && $user['timezone']) {
3604 $eventdata['timezone'] = $user['timezone'];
3607 if ($event['start']) {
3608 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3610 if ($event['finish'] && !$event['nofinish']) {
3611 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3613 if ($event['summary']) {
3614 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3616 if ($event['desc']) {
3617 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3619 if ($event['location']) {
3620 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3621 $coord = Map::getCoordinates($event['location']);
3624 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3625 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3626 $location["lat"] = $coord['lat'];
3627 $location["lng"] = $coord['lon'];
3629 $location["lat"] = 0;
3630 $location["lng"] = 0;
3632 $eventdata['location'] = $location;
3639 * Create a post (status message or reshare)
3641 * @param array $item The item that will be exported
3642 * @param array $owner the array of the item owner
3645 * 'type' -> Message type ("status_message" or "reshare")
3646 * 'message' -> Array of XML elements of the status
3647 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3648 * @throws \ImagickException
3650 public static function buildStatus(array $item, array $owner)
3652 $cachekey = "diaspora:buildStatus:".$item['guid'];
3654 $result = DI::cache()->get($cachekey);
3655 if (!is_null($result)) {
3659 $myaddr = self::myHandle($owner);
3661 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3662 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3663 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3665 // Detect a share element and do a reshare
3666 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3667 $message = ["author" => $myaddr,
3668 "guid" => $item["guid"],
3669 "created_at" => $created,
3670 "root_author" => $ret["root_handle"],
3671 "root_guid" => $ret["root_guid"],
3672 "provider_display_name" => $item["app"],
3673 "public" => $public];
3677 $title = $item["title"];
3678 $body = $item["body"];
3680 // Fetch the title from an attached link - if there is one
3681 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3682 $page_data = BBCode::getAttachmentData($item['body']);
3683 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3684 $title = $page_data['title'];
3688 if ($item['author-link'] != $item['owner-link']) {
3689 require_once 'mod/share.php';
3690 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3691 $item['plink'], $item['created']) . $body . '[/share]';
3694 // convert to markdown
3695 $body = html_entity_decode(BBCode::toMarkdown($body));
3698 if (strlen($title)) {
3699 $body = "### ".html_entity_decode($title)."\n\n".$body;
3702 if ($item["attach"]) {
3703 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3705 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3706 foreach ($matches as $mtch) {
3707 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3714 if ($item["location"] != "")
3715 $location["address"] = $item["location"];
3717 if ($item["coord"] != "") {
3718 $coord = explode(" ", $item["coord"]);
3719 $location["lat"] = $coord[0];
3720 $location["lng"] = $coord[1];
3723 $message = ["author" => $myaddr,
3724 "guid" => $item["guid"],
3725 "created_at" => $created,
3726 "edited_at" => $edited,
3727 "public" => $public,
3729 "provider_display_name" => $item["app"],
3730 "location" => $location];
3732 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3733 if (!isset($location["lat"]) || !isset($location["lng"])) {
3734 unset($message["location"]);
3737 if ($item['event-id'] > 0) {
3738 $event = self::buildEvent($item['event-id']);
3739 if (count($event)) {
3740 $message['event'] = $event;
3742 if (!empty($event['location']['address']) &&
3743 !empty($event['location']['lat']) &&
3744 !empty($event['location']['lng'])) {
3745 $message['location'] = $event['location'];
3748 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3749 // $message['text'] = '';
3753 $type = "status_message";
3756 $msg = ["type" => $type, "message" => $message];
3758 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3763 private static function prependParentAuthorMention($body, $profile_url)
3765 $profile = Contact::getDetailsByURL($profile_url);
3766 if (!empty($profile['addr'])
3767 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3768 && !strstr($body, $profile['addr'])
3769 && !strstr($body, $profile_url)
3771 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3780 * @param array $item The item that will be exported
3781 * @param array $owner the array of the item owner
3782 * @param array $contact Target of the communication
3783 * @param bool $public_batch Is it a public post?
3785 * @return int The result of the transmission
3786 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3787 * @throws \ImagickException
3789 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3791 $status = self::buildStatus($item, $owner);
3793 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3797 * Creates a "like" object
3799 * @param array $item The item that will be exported
3800 * @param array $owner the array of the item owner
3802 * @return array The data for a "like"
3803 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3805 private static function constructLike(array $item, array $owner)
3807 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3808 if (!DBA::isResult($parent)) {
3812 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3814 if ($item['verb'] === Activity::LIKE) {
3816 } elseif ($item['verb'] === Activity::DISLIKE) {
3817 $positive = "false";
3820 return(["author" => self::myHandle($owner),
3821 "guid" => $item["guid"],
3822 "parent_guid" => $parent["guid"],
3823 "parent_type" => $target_type,
3824 "positive" => $positive,
3825 "author_signature" => ""]);
3829 * Creates an "EventParticipation" object
3831 * @param array $item The item that will be exported
3832 * @param array $owner the array of the item owner
3834 * @return array The data for an "EventParticipation"
3835 * @throws \Exception
3837 private static function constructAttend(array $item, array $owner)
3839 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3840 if (!DBA::isResult($parent)) {
3844 switch ($item['verb']) {
3845 case Activity::ATTEND:
3846 $attend_answer = 'accepted';
3848 case Activity::ATTENDNO:
3849 $attend_answer = 'declined';
3851 case Activity::ATTENDMAYBE:
3852 $attend_answer = 'tentative';
3855 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3859 return(["author" => self::myHandle($owner),
3860 "guid" => $item["guid"],
3861 "parent_guid" => $parent["guid"],
3862 "status" => $attend_answer,
3863 "author_signature" => ""]);
3867 * Creates the object for a comment
3869 * @param array $item The item that will be exported
3870 * @param array $owner the array of the item owner
3872 * @return array|false The data for a comment
3873 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3875 private static function constructComment(array $item, array $owner)
3877 $cachekey = "diaspora:constructComment:".$item['guid'];
3879 $result = DI::cache()->get($cachekey);
3880 if (!is_null($result)) {
3884 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3885 if (!DBA::isResult($toplevel_item)) {
3886 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3890 $thread_parent_item = $toplevel_item;
3891 if ($item['thr-parent'] != $item['parent-uri']) {
3892 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3895 $body = $item["body"];
3897 // The replied to autor mention is prepended for clarity if:
3898 // - Item replied isn't yours
3899 // - Item is public or explicit mentions are disabled
3900 // - Implicit mentions are enabled
3902 $item['author-id'] != $thread_parent_item['author-id']
3903 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3904 && !DI::config()->get('system', 'disable_implicit_mentions')
3906 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3909 $text = html_entity_decode(BBCode::toMarkdown($body));
3910 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3911 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3914 "author" => self::myHandle($owner),
3915 "guid" => $item["guid"],
3916 "created_at" => $created,
3917 "edited_at" => $edited,
3918 "parent_guid" => $toplevel_item["guid"],
3920 "author_signature" => ""
3923 // Send the thread parent guid only if it is a threaded comment
3924 if ($item['thr-parent'] != $item['parent-uri']) {
3925 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3928 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3934 * Send a like or a comment
3936 * @param array $item The item that will be exported
3937 * @param array $owner the array of the item owner
3938 * @param array $contact Target of the communication
3939 * @param bool $public_batch Is it a public post?
3941 * @return int The result of the transmission
3942 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3943 * @throws \ImagickException
3945 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3947 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3948 $message = self::constructAttend($item, $owner);
3949 $type = "event_participation";
3950 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3951 $message = self::constructLike($item, $owner);
3953 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3954 $message = self::constructComment($item, $owner);
3958 if (empty($message)) {
3962 $message["author_signature"] = self::signature($owner, $message);
3964 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3968 * Creates a message from a signature record entry
3970 * @param array $item The item that will be exported
3971 * @return array The message
3973 private static function messageFromSignature(array $item)
3975 // Split the signed text
3976 $signed_parts = explode(";", $item['signed_text']);
3978 if ($item["deleted"]) {
3979 $message = ["author" => $item['signer'],
3980 "target_guid" => $signed_parts[0],
3981 "target_type" => $signed_parts[1]];
3982 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3983 $message = ["author" => $signed_parts[4],
3984 "guid" => $signed_parts[1],
3985 "parent_guid" => $signed_parts[3],
3986 "parent_type" => $signed_parts[2],
3987 "positive" => $signed_parts[0],
3988 "author_signature" => $item['signature'],
3989 "parent_author_signature" => ""];
3991 // Remove the comment guid
3992 $guid = array_shift($signed_parts);
3994 // Remove the parent guid
3995 $parent_guid = array_shift($signed_parts);
3997 // Remove the handle
3998 $handle = array_pop($signed_parts);
4001 "author" => $handle,
4003 "parent_guid" => $parent_guid,
4004 "text" => implode(";", $signed_parts),
4005 "author_signature" => $item['signature'],
4006 "parent_author_signature" => ""
4013 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
4015 * @param array $item The item that will be exported
4016 * @param array $owner the array of the item owner
4017 * @param array $contact Target of the communication
4018 * @param bool $public_batch Is it a public post?
4020 * @return int The result of the transmission
4021 * @throws \Exception
4023 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
4025 if ($item["deleted"]) {
4026 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
4027 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4033 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
4035 $msg = json_decode($item['signed_text'], true);
4038 if (is_array($msg)) {
4039 foreach ($msg as $field => $data) {
4040 if (!$item["deleted"]) {
4041 if ($field == "diaspora_handle") {
4044 if ($field == "target_type") {
4045 $field = "parent_type";
4049 $message[$field] = $data;
4052 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4055 $message["parent_author_signature"] = self::signature($owner, $message);
4057 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4059 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4063 * Sends a retraction (deletion) of a message, like or comment
4065 * @param array $item The item that will be exported
4066 * @param array $owner the array of the item owner
4067 * @param array $contact Target of the communication
4068 * @param bool $public_batch Is it a public post?
4069 * @param bool $relay Is the retraction transmitted from a relay?
4071 * @return int The result of the transmission
4072 * @throws \Exception
4074 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4076 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4078 $msg_type = "retraction";
4080 if ($item['gravity'] == GRAVITY_PARENT) {
4081 $target_type = "Post";
4082 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4083 $target_type = "Like";
4085 $target_type = "Comment";
4088 $message = ["author" => $itemaddr,
4089 "target_guid" => $item['guid'],
4090 "target_type" => $target_type];
4092 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4094 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4100 * @param array $item The item that will be exported
4101 * @param array $owner The owner
4102 * @param array $contact Target of the communication
4104 * @return int The result of the transmission
4105 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4106 * @throws \ImagickException
4108 public static function sendMail(array $item, array $owner, array $contact)
4110 $myaddr = self::myHandle($owner);
4112 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4113 if (!DBA::isResult($cnv)) {
4114 Logger::log("conversation not found.");
4118 $body = BBCode::toMarkdown($item["body"]);
4119 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4122 "author" => $myaddr,
4123 "guid" => $item["guid"],
4124 "conversation_guid" => $cnv["guid"],
4126 "created_at" => $created,
4129 if ($item["reply"]) {
4134 "author" => $cnv["creator"],
4135 "guid" => $cnv["guid"],
4136 "subject" => $cnv["subject"],
4137 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4138 "participants" => $cnv["recips"],
4142 $type = "conversation";
4145 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4149 * Split a name into first name and last name
4151 * @param string $name The name
4153 * @return array The array with "first" and "last"
4155 public static function splitName($name) {
4156 $name = trim($name);
4158 // Is the name longer than 64 characters? Then cut the rest of it.
4159 if (strlen($name) > 64) {
4160 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4161 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4163 $name = substr($name, 0, 64);
4167 // Take the first word as first name
4168 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4169 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4170 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4171 return ['first' => $first, 'last' => $last];
4174 // Take the last word as last name
4175 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4176 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4178 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4179 return ['first' => $first, 'last' => $last];
4182 // Take the first 32 characters if there is no space in the first 32 characters
4183 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4184 $first = substr($name, 0, 32);
4185 $last = substr($name, 32);
4186 return ['first' => $first, 'last' => $last];
4189 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4190 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4192 // Check if the last name is longer than 32 characters
4193 if (strlen($last) > 32) {
4194 if (strpos($last, ' ') <= 32) {
4195 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4197 $last = substr($last, 0, 32);
4201 return ['first' => $first, 'last' => $last];
4205 * Create profile data
4207 * @param int $uid The user id
4209 * @return array The profile data
4210 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4212 private static function createProfileData($uid)
4214 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4215 if (!DBA::isResult($profile)) {
4219 $handle = $profile["addr"];
4221 $split_name = self::splitName($profile['name']);
4222 $first = $split_name['first'];
4223 $last = $split_name['last'];
4225 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4226 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4227 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4228 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4234 if ($searchable === 'true') {
4237 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4238 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4242 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4245 $about = BBCode::toMarkdown($profile['about']);
4247 $location = $profile['location'];
4249 if ($profile['pub_keywords']) {
4250 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4251 $kw = str_replace(' ', ' ', $kw);
4252 $arr = explode(' ', $kw);
4254 for ($x = 0; $x < 5; $x ++) {
4255 if (!empty($arr[$x])) {
4256 $tags .= '#'. trim($arr[$x]) .' ';
4261 $tags = trim($tags);
4264 return ["author" => $handle,
4265 "first_name" => $first,
4266 "last_name" => $last,
4267 "image_url" => $large,
4268 "image_url_medium" => $medium,
4269 "image_url_small" => $small,
4272 "location" => $location,
4273 "searchable" => $searchable,
4275 "tag_string" => $tags];
4279 * Sends profile data
4281 * @param int $uid The user id
4282 * @param bool $recips optional, default false
4284 * @throws \Exception
4286 public static function sendProfile($uid, $recips = false)
4292 $owner = User::getOwnerDataById($uid);
4299 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4300 AND `uid` = %d AND `rel` != %d",
4301 DBA::escape(Protocol::DIASPORA),
4303 intval(Contact::SHARING)
4311 $message = self::createProfileData($uid);
4313 // @ToDo Split this into single worker jobs
4314 foreach ($recips as $recip) {
4315 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4316 self::buildAndTransmit($owner, $recip, "profile", $message);
4321 * Creates the signature for likes that are created on our system
4323 * @param integer $uid The user of that comment
4324 * @param array $item Item array
4326 * @return array Signed content
4327 * @throws \Exception
4329 public static function createLikeSignature($uid, array $item)
4331 $owner = User::getOwnerDataById($uid);
4332 if (empty($owner)) {
4333 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4337 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4341 $message = self::constructLike($item, $owner);
4342 if ($message === false) {
4346 $message["author_signature"] = self::signature($owner, $message);
4352 * Creates the signature for Comments that are created on our system
4354 * @param integer $uid The user of that comment
4355 * @param array $item Item array
4357 * @return array Signed content
4358 * @throws \Exception
4360 public static function createCommentSignature($uid, array $item)
4362 $owner = User::getOwnerDataById($uid);
4363 if (empty($owner)) {
4364 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4368 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4369 $item['thr-parent'] = $item['parent-uri'];
4371 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4372 if (!DBA::isResult($parent)) {
4376 $item['parent-uri'] = $parent['parent-uri'];
4378 $message = self::constructComment($item, $owner);
4379 if ($message === false) {
4383 $message["author_signature"] = self::signature($owner, $message);