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\PageInfo;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Cache\Duration;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\GContact;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Network\HTTPRequest;
45 use Friendica\Network\Probe;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
52 use Friendica\Worker\Delivery;
56 * This class contain functions to create and send Diaspora XML files
61 * Mark the relay contact of the given contact for archival
62 * This is called whenever there is a communication issue with the server.
63 * It avoids sending stuff to servers who don't exist anymore.
64 * The relay contact is a technical contact entry that exists once per server.
66 * @param array $contact of the relay contact
68 public static function markRelayForArchival(array $contact)
70 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
71 // This is already the relay contact, we don't need to fetch it
72 $relay_contact = $contact;
73 } elseif (empty($contact['baseurl'])) {
74 if (!empty($contact['batch'])) {
75 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
76 $relay_contact = DBA::selectFirst('contact', [], $condition);
81 $relay_contact = self::getRelayContact($contact['baseurl'], []);
84 if (!empty($relay_contact)) {
85 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
86 Contact::markForArchival($relay_contact);
91 * Return a list of relay servers
93 * The list contains not only the official relays but also servers that we serve directly
95 * @param integer $item_id The id of the item that is sent
96 * @param array $contacts The previously fetched contacts
98 * @return array of relay servers
99 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
101 public static function relayList($item_id, array $contacts = [])
105 // Fetching relay servers
106 $serverdata = DI::config()->get("system", "relay_server");
108 if (!empty($serverdata)) {
109 $servers = explode(",", $serverdata);
110 foreach ($servers as $server) {
111 $serverlist[$server] = trim($server);
115 if (DI::config()->get("system", "relay_directly", false)) {
116 // We distribute our stuff based on the parent to ensure that the thread will be complete
117 $parent = Item::selectFirst(['uri-id'], ['id' => $item_id]);
118 if (!DBA::isResult($parent)) {
122 // Servers that want to get all content
123 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
124 while ($server = DBA::fetch($servers)) {
125 $serverlist[$server['url']] = $server['url'];
127 DBA::close($servers);
129 // All tags of the current post
130 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
132 while ($tag = DBA::fetch($tags)) {
133 $taglist[] = $tag['name'];
137 // All servers who wants content with this tag
139 if (!empty($taglist)) {
140 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
141 while ($server = DBA::fetch($tagserver)) {
142 $tagserverlist[] = $server['gserver-id'];
144 DBA::close($tagserver);
147 // All adresses with the given id
148 if (!empty($tagserverlist)) {
149 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
150 while ($server = DBA::fetch($servers)) {
151 $serverlist[$server['url']] = $server['url'];
153 DBA::close($servers);
157 // Now we are collecting all relay contacts
158 foreach ($serverlist as $server_url) {
159 // We don't send messages to ourselves
160 if (Strings::compareLink($server_url, DI::baseUrl())) {
163 $contact = self::getRelayContact($server_url);
164 if (is_bool($contact)) {
169 foreach ($contacts as $entry) {
170 if ($entry['batch'] == $contact['batch']) {
176 $contacts[] = $contact;
184 * Return a contact for a given server address or creates a dummy entry
186 * @param string $server_url The url of the server
187 * @param array $fields Fieldlist
188 * @return array with the contact
191 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
193 // Fetch the relay contact
194 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
195 'contact-type' => Contact::TYPE_RELAY];
196 $contact = DBA::selectFirst('contact', $fields, $condition);
198 if (DBA::isResult($contact)) {
199 if ($contact['archive'] || $contact['blocked']) {
204 self::setRelayContact($server_url);
206 $contact = DBA::selectFirst('contact', $fields, $condition);
207 if (DBA::isResult($contact)) {
212 // It should never happen that we arrive here
217 * Update or insert a relay contact
219 * @param string $server_url The url of the server
220 * @param array $network_fields Optional network specific fields
223 public static function setRelayContact($server_url, array $network_fields = [])
225 $fields = ['created' => DateTimeFormat::utcNow(),
226 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
227 'nurl' => Strings::normaliseLink($server_url),
228 'network' => Protocol::DIASPORA, 'uid' => 0,
229 'batch' => $server_url . '/receive/public',
230 'rel' => Contact::FOLLOWER, 'blocked' => false,
231 'pending' => false, 'writable' => true,
232 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
234 $fields = array_merge($fields, $network_fields);
236 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
237 $old = DBA::selectFirst('contact', [], $condition);
238 if (DBA::isResult($old)) {
239 unset($fields['created']);
240 $condition = ['id' => $old['id']];
242 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
243 DBA::update('contact', $fields, $condition, $old);
245 Logger::info('Create relay contact', ['fields' => $fields]);
246 Contact::insert($fields);
251 * Return a list of participating contacts for a thread
253 * This is used for the participation feature.
254 * One of the parameters is a contact array.
255 * This is done to avoid duplicates.
257 * @param array $item Item that is about to be delivered
258 * @param array $contacts The previously fetched contacts
260 * @return array of relay servers
263 public static function participantsForThread(array $item, array $contacts)
265 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
266 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
270 $items = Item::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
271 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
272 while ($item = DBA::fetch($items)) {
273 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
274 ['id' => $item['author-id']]);
275 if (!DBA::isResult($contact) || empty($contact['batch']) ||
276 ($contact['network'] != Protocol::DIASPORA) ||
277 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
282 foreach ($contacts as $entry) {
283 if ($entry['batch'] == $contact['batch']) {
289 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
290 $contacts[] = $contact;
299 * verify the envelope and return the verified data
301 * @param string $envelope The magic envelope
303 * @return string verified data
304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305 * @throws \ImagickException
307 private static function verifyMagicEnvelope($envelope)
309 $basedom = XML::parseString($envelope, true);
311 if (!is_object($basedom)) {
312 Logger::log("Envelope is no XML file");
316 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
318 if (sizeof($children) == 0) {
319 Logger::log("XML has no children");
325 $data = Strings::base64UrlDecode($children->data);
326 $type = $children->data->attributes()->type[0];
328 $encoding = $children->encoding;
330 $alg = $children->alg;
332 $sig = Strings::base64UrlDecode($children->sig);
333 $key_id = $children->sig->attributes()->key_id[0];
335 $handle = Strings::base64UrlDecode($key_id);
338 $b64url_data = Strings::base64UrlEncode($data);
339 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
341 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
344 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
348 $key = self::key($handle);
350 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
354 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
356 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
364 * encrypts data via AES
366 * @param string $key The AES key
367 * @param string $iv The IV (is used for CBC encoding)
368 * @param string $data The data that is to be encrypted
370 * @return string encrypted data
372 private static function aesEncrypt($key, $iv, $data)
374 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
378 * decrypts data via AES
380 * @param string $key The AES key
381 * @param string $iv The IV (is used for CBC encoding)
382 * @param string $encrypted The encrypted data
384 * @return string decrypted data
386 private static function aesDecrypt($key, $iv, $encrypted)
388 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
392 * Decodes incoming Diaspora message in the new format
394 * @param string $raw raw post message
395 * @param string $privKey The private key of the importer
396 * @param boolean $no_exit Don't do an http exit on error
399 * 'message' -> decoded Diaspora XML message
400 * 'author' -> author diaspora handle
401 * 'key' -> author public key (converted to pkcs#8)
402 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
403 * @throws \ImagickException
405 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
407 $data = json_decode($raw);
409 // Is it a private post? Then decrypt the outer Salmon
410 if (is_object($data)) {
411 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
412 $ciphertext = base64_decode($data->encrypted_magic_envelope);
414 $outer_key_bundle = '';
415 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
416 $j_outer_key_bundle = json_decode($outer_key_bundle);
418 if (!is_object($j_outer_key_bundle)) {
419 Logger::log('Outer Salmon did not verify. Discarding.');
423 throw new \Friendica\Network\HTTPException\BadRequestException();
427 $outer_iv = base64_decode($j_outer_key_bundle->iv);
428 $outer_key = base64_decode($j_outer_key_bundle->key);
430 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
435 $basedom = XML::parseString($xml, true);
437 if (!is_object($basedom)) {
438 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
442 throw new \Friendica\Network\HTTPException\BadRequestException();
446 $base = $basedom->children(ActivityNamespace::SALMON_ME);
448 // Not sure if this cleaning is needed
449 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
451 // Build the signed data
452 $type = $base->data[0]->attributes()->type[0];
453 $encoding = $base->encoding;
455 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
457 // This is the signature
458 $signature = Strings::base64UrlDecode($base->sig);
460 // Get the senders' public key
461 $key_id = $base->sig[0]->attributes()->key_id[0];
462 $author_addr = base64_decode($key_id);
463 if ($author_addr == '') {
464 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
468 throw new \Friendica\Network\HTTPException\BadRequestException();
472 $key = self::key($author_addr);
474 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
478 throw new \Friendica\Network\HTTPException\BadRequestException();
482 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
484 Logger::log('Message did not verify. Discarding.');
488 throw new \Friendica\Network\HTTPException\BadRequestException();
492 return ['message' => (string)Strings::base64UrlDecode($base->data),
493 'author' => XML::unescape($author_addr),
494 'key' => (string)$key];
498 * Decodes incoming Diaspora message in the deprecated format
500 * @param string $xml urldecoded Diaspora salmon
501 * @param string $privKey The private key of the importer
504 * 'message' -> decoded Diaspora XML message
505 * 'author' -> author diaspora handle
506 * 'key' -> author public key (converted to pkcs#8)
507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
508 * @throws \ImagickException
510 public static function decode(string $xml, string $privKey = '')
513 $basedom = XML::parseString($xml);
515 if (!is_object($basedom)) {
516 Logger::notice('XML is not parseable.');
519 $children = $basedom->children('https://joindiaspora.com/protocol');
521 $inner_aes_key = null;
524 if ($children->header) {
526 $author_link = str_replace('acct:', '', $children->header->author_id);
528 // This happens with posts from a relais
529 if (empty($privKey)) {
530 Logger::info('This is no private post in the old format');
534 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
536 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
537 $ciphertext = base64_decode($encrypted_header->ciphertext);
539 $outer_key_bundle = '';
540 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
542 $j_outer_key_bundle = json_decode($outer_key_bundle);
544 $outer_iv = base64_decode($j_outer_key_bundle->iv);
545 $outer_key = base64_decode($j_outer_key_bundle->key);
547 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
549 Logger::info('decrypted', ['data' => $decrypted]);
550 $idom = XML::parseString($decrypted);
552 $inner_iv = base64_decode($idom->iv);
553 $inner_aes_key = base64_decode($idom->aes_key);
555 $author_link = str_replace('acct:', '', $idom->author_id);
558 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
560 // figure out where in the DOM tree our data is hiding
563 if ($dom->provenance->data) {
564 $base = $dom->provenance;
565 } elseif ($dom->env->data) {
567 } elseif ($dom->data) {
572 Logger::log('unable to locate salmon data in xml');
573 throw new \Friendica\Network\HTTPException\BadRequestException();
577 // Stash the signature away for now. We have to find their key or it won't be good for anything.
578 $signature = Strings::base64UrlDecode($base->sig);
582 // strip whitespace so our data element will return to one big base64 blob
583 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
586 // stash away some other stuff for later
588 $type = $base->data[0]->attributes()->type[0];
589 $keyhash = $base->sig[0]->attributes()->keyhash[0];
590 $encoding = $base->encoding;
594 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
598 $data = Strings::base64UrlDecode($data);
602 $inner_decrypted = $data;
604 // Decode the encrypted blob
605 $inner_encrypted = base64_decode($data);
606 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
610 Logger::log('Could not retrieve author URI.');
611 throw new \Friendica\Network\HTTPException\BadRequestException();
613 // Once we have the author URI, go to the web and try to find their public key
614 // (first this will look it up locally if it is in the fcontact cache)
615 // This will also convert diaspora public key from pkcs#1 to pkcs#8
617 Logger::log('Fetching key for '.$author_link);
618 $key = self::key($author_link);
621 Logger::log('Could not retrieve author key.');
622 throw new \Friendica\Network\HTTPException\BadRequestException();
625 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
628 Logger::log('Message did not verify. Discarding.');
629 throw new \Friendica\Network\HTTPException\BadRequestException();
632 Logger::log('Message verified.');
634 return ['message' => (string)$inner_decrypted,
635 'author' => XML::unescape($author_link),
636 'key' => (string)$key];
641 * Dispatches public messages and find the fitting receivers
643 * @param array $msg The post that will be dispatched
645 * @return int The message id of the generated message, "true" or "false" if there was an error
646 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
647 * @throws \ImagickException
649 public static function dispatchPublic($msg)
651 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
653 Logger::log("diaspora is disabled");
657 if (!($fields = self::validPosting($msg))) {
658 Logger::log("Invalid posting");
662 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
663 $success = self::dispatch($importer, $msg, $fields);
669 * Dispatches the different message types to the different functions
671 * @param array $importer Array of the importer user
672 * @param array $msg The post that will be dispatched
673 * @param SimpleXMLElement $fields SimpleXML object that contains the message
675 * @return int The message id of the generated message, "true" or "false" if there was an error
676 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
677 * @throws \ImagickException
679 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
681 // The sender is the handle of the contact that sent the message.
682 // This will often be different with relayed messages (for example "like" and "comment")
683 $sender = $msg["author"];
685 // This is only needed for private postings since this is already done for public ones before
686 if (is_null($fields)) {
688 if (!($fields = self::validPosting($msg))) {
689 Logger::log("Invalid posting");
696 $type = $fields->getName();
698 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]);
701 case "account_migration":
703 Logger::log('Message with type ' . $type . ' is not private, quitting.');
706 return self::receiveAccountMigration($importer, $fields);
708 case "account_deletion":
709 return self::receiveAccountDeletion($fields);
712 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
716 Logger::log('Message with type ' . $type . ' is not private, quitting.');
719 return self::receiveContactRequest($importer, $fields);
723 Logger::log('Message with type ' . $type . ' is not private, quitting.');
726 return self::receiveConversation($importer, $msg, $fields);
729 return self::receiveLike($importer, $sender, $fields);
733 Logger::log('Message with type ' . $type . ' is not private, quitting.');
736 return self::receiveMessage($importer, $fields);
738 case "participation":
740 Logger::log('Message with type ' . $type . ' is not private, quitting.');
743 return self::receiveParticipation($importer, $fields);
745 case "photo": // Not implemented
746 return self::receivePhoto($importer, $fields);
748 case "poll_participation": // Not implemented
749 return self::receivePollParticipation($importer, $fields);
753 Logger::log('Message with type ' . $type . ' is not private, quitting.');
756 return self::receiveProfile($importer, $fields);
759 return self::receiveReshare($importer, $fields, $msg["message"]);
762 return self::receiveRetraction($importer, $sender, $fields);
764 case "status_message":
765 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
768 Logger::log("Unknown message type ".$type);
774 * Checks if a posting is valid and fetches the data fields.
776 * This function does not only check the signature.
777 * It also does the conversion between the old and the new diaspora format.
779 * @param array $msg Array with the XML, the sender handle and the sender signature
781 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
782 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
783 * @throws \ImagickException
785 private static function validPosting($msg)
787 $data = XML::parseString($msg["message"]);
789 if (!is_object($data)) {
790 Logger::info('No valid XML', ['message' => $msg['message']]);
794 // Is this the new or the old version?
795 if ($data->getName() == "XML") {
797 foreach ($data->post->children() as $child) {
805 $type = $element->getName();
808 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
810 // All retractions are handled identically from now on.
811 // In the new version there will only be "retraction".
812 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
813 $type = "retraction";
815 if ($type == "request") {
819 $fields = new SimpleXMLElement("<".$type."/>");
822 $author_signature = null;
823 $parent_author_signature = null;
825 foreach ($element->children() as $fieldname => $entry) {
827 // Translation for the old XML structure
828 if ($fieldname == "diaspora_handle") {
829 $fieldname = "author";
831 if ($fieldname == "participant_handles") {
832 $fieldname = "participants";
834 if (in_array($type, ["like", "participation"])) {
835 if ($fieldname == "target_type") {
836 $fieldname = "parent_type";
839 if ($fieldname == "sender_handle") {
840 $fieldname = "author";
842 if ($fieldname == "recipient_handle") {
843 $fieldname = "recipient";
845 if ($fieldname == "root_diaspora_id") {
846 $fieldname = "root_author";
848 if ($type == "status_message") {
849 if ($fieldname == "raw_message") {
853 if ($type == "retraction") {
854 if ($fieldname == "post_guid") {
855 $fieldname = "target_guid";
857 if ($fieldname == "type") {
858 $fieldname = "target_type";
863 if (($fieldname == "author_signature") && ($entry != "")) {
864 $author_signature = base64_decode($entry);
865 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
866 $parent_author_signature = base64_decode($entry);
867 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
868 if ($signed_data != "") {
872 $signed_data .= $entry;
874 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
875 || ($orig_type == "relayable_retraction")
877 XML::copy($entry, $fields, $fieldname);
881 // This is something that shouldn't happen at all.
882 if (in_array($type, ["status_message", "reshare", "profile"])) {
883 if ($msg["author"] != $fields->author) {
884 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
889 // Only some message types have signatures. So we quit here for the other types.
890 if (!in_array($type, ["comment", "like"])) {
893 // No author_signature? This is a must, so we quit.
894 if (!isset($author_signature)) {
895 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
899 if (isset($parent_author_signature)) {
900 $key = self::key($msg["author"]);
902 Logger::info('No key found for parent', ['author' => $msg["author"]]);
906 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
907 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);
912 $key = self::key($fields->author);
914 Logger::info('No key found', ['author' => $fields->author]);
918 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
919 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);
927 * Fetches the public key for a given handle
929 * @param string $handle The handle
931 * @return string The public key
932 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
933 * @throws \ImagickException
935 private static function key($handle)
937 $handle = strval($handle);
939 Logger::log("Fetching diaspora key for: ".$handle);
941 $r = self::personByHandle($handle);
950 * Fetches data for a given handle
952 * @param string $handle The handle
953 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
955 * @return array the queried data
956 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
957 * @throws \ImagickException
959 public static function personByHandle($handle, $update = null)
961 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
962 if (!DBA::isResult($person)) {
963 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
964 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
967 if (DBA::isResult($person)) {
968 Logger::debug('In cache', ['person' => $person]);
970 if (is_null($update)) {
971 // update record occasionally so it doesn't get stale
972 $d = strtotime($person["updated"]." +00:00");
973 if ($d < strtotime("now - 14 days")) {
977 if ($person["guid"] == "") {
981 } elseif (is_null($update)) {
982 $update = !DBA::isResult($person);
988 Logger::log("create or refresh", Logger::DEBUG);
989 $r = Probe::uri($handle, Protocol::DIASPORA);
991 // Note that Friendica contacts will return a "Diaspora person"
992 // if Diaspora connectivity is enabled on their server
993 if ($r && ($r["network"] === Protocol::DIASPORA)) {
994 self::updateFContact($r);
996 $person = self::personByHandle($handle, false);
1004 * Updates the fcontact table
1006 * @param array $arr The fcontact data
1007 * @throws \Exception
1009 private static function updateFContact($arr)
1011 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1012 'request' => $arr["request"], 'nick' => $arr["nick"],
1013 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1014 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1015 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1016 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1017 'updated' => DateTimeFormat::utcNow()];
1019 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1021 DBA::update('fcontact', $fields, $condition, true);
1025 * get a handle (user@domain.tld) from a given contact id
1027 * @param int $contact_id The id in the contact table
1028 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1030 * @return string the handle
1031 * @throws \Exception
1033 private static function handleFromContact($contact_id, $pcontact_id = 0)
1037 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1039 if ($pcontact_id != 0) {
1040 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1042 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1043 return strtolower($contact["addr"]);
1048 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1052 if (DBA::isResult($r)) {
1055 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1057 if ($contact['addr'] != "") {
1058 $handle = $contact['addr'];
1060 $baseurl_start = strpos($contact['url'], '://') + 3;
1061 // allows installations in a subdirectory--not sure how Diaspora will handle
1062 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1063 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1064 $handle = $contact['nick'].'@'.$baseurl;
1068 return strtolower($handle);
1072 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1075 * @param mixed $fcontact_guid Hexadecimal string guid
1077 * @return string the contact url or null
1078 * @throws \Exception
1080 public static function urlFromContactGuid($fcontact_guid)
1082 Logger::info('fcontact', ['guid' => $fcontact_guid]);
1085 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1086 DBA::escape(Protocol::DIASPORA),
1087 DBA::escape($fcontact_guid)
1090 if (DBA::isResult($r)) {
1091 return $r[0]['url'];
1098 * Get a contact id for a given handle
1100 * @todo Move to Friendica\Model\Contact
1102 * @param int $uid The user id
1103 * @param string $handle The handle in the format user@domain.tld
1105 * @return array Contact data
1106 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1107 * @throws \ImagickException
1109 private static function contactByHandle($uid, $handle)
1111 $cid = Contact::getIdForURL($handle, $uid);
1113 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1117 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1118 if (!DBA::isResult($contact)) {
1119 // This here shouldn't happen at all
1120 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1128 * Checks if the given contact url does support ActivityPub
1130 * @param string $url profile url
1131 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1133 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1134 * @throws \ImagickException
1136 public static function isSupportedByContactUrl($url, $update = null)
1138 return !empty(self::personByHandle($url, $update));
1142 * Check if posting is allowed for this contact
1144 * @param array $importer Array of the importer user
1145 * @param array $contact The contact that is checked
1146 * @param bool $is_comment Is the check for a comment?
1148 * @return bool is the contact allowed to post?
1150 private static function postAllow(array $importer, array $contact, $is_comment = false)
1153 * Perhaps we were already sharing with this person. Now they're sharing with us.
1154 * That makes us friends.
1155 * Normally this should have handled by getting a request - but this could get lost
1157 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1158 // It is not removed by now. Possibly the code is needed?
1159 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1162 // array('rel' => Contact::FRIEND, 'writable' => true),
1163 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1166 // $contact["rel"] = Contact::FRIEND;
1167 // Logger::log("defining user ".$contact["nick"]." as friend");
1170 // Contact server is blocked
1171 if (Network::isUrlBlocked($contact['url'])) {
1173 // We don't seem to like that person
1174 } elseif ($contact["blocked"]) {
1175 // Maybe blocked, don't accept.
1177 // We are following this person?
1178 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1179 // Yes, then it is fine.
1181 // Is it a post to a community?
1182 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1185 // Is the message a global user or a comment?
1186 } elseif (($importer["uid"] == 0) || $is_comment) {
1187 // Messages for the global users and comments are always accepted
1195 * Fetches the contact id for a handle and checks if posting is allowed
1197 * @param array $importer Array of the importer user
1198 * @param string $handle The checked handle in the format user@domain.tld
1199 * @param bool $is_comment Is the check for a comment?
1201 * @return array The contact data
1202 * @throws \Exception
1204 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1206 $contact = self::contactByHandle($importer["uid"], $handle);
1208 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1209 // If a contact isn't found, we accept it anyway if it is a comment
1210 if ($is_comment && ($importer["uid"] != 0)) {
1211 return self::contactByHandle(0, $handle);
1212 } elseif ($is_comment) {
1219 if (!self::postAllow($importer, $contact, $is_comment)) {
1220 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1227 * Does the message already exists on the system?
1229 * @param int $uid The user id
1230 * @param string $guid The guid of the message
1232 * @return int|bool message id if the message already was stored into the system - or false.
1233 * @throws \Exception
1235 private static function messageExists($uid, $guid)
1237 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1238 if (DBA::isResult($item)) {
1239 Logger::log("message ".$guid." already exists for user ".$uid);
1247 * Checks for links to posts in a message
1249 * @param array $item The item array
1252 private static function fetchGuid(array $item)
1254 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1255 preg_replace_callback(
1257 function ($match) use ($item) {
1258 self::fetchGuidSub($match, $item);
1263 preg_replace_callback(
1264 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1265 function ($match) use ($item) {
1266 self::fetchGuidSub($match, $item);
1273 * Checks for relative /people/* links in an item body to match local
1274 * contacts or prepends the remote host taken from the author link.
1276 * @param string $body The item body to replace links from
1277 * @param string $author_link The author link for missing local contact fallback
1279 * @return string the replaced string
1281 public static function replacePeopleGuid($body, $author_link)
1283 $return = preg_replace_callback(
1284 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1285 function ($match) use ($author_link) {
1287 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1288 // 1 => '0123456789abcdef'
1290 $handle = self::urlFromContactGuid($match[1]);
1293 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1295 // No local match, restoring absolute remote URL from author scheme and host
1296 $author_url = parse_url($author_link);
1297 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1309 * sub function of "fetchGuid" which checks for links in messages
1311 * @param array $match array containing a link that has to be checked for a message link
1312 * @param array $item The item array
1314 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1315 * @throws \ImagickException
1317 private static function fetchGuidSub($match, $item)
1319 if (!self::storeByGuid($match[1], $item["author-link"])) {
1320 self::storeByGuid($match[1], $item["owner-link"]);
1325 * Fetches an item with a given guid from a given server
1327 * @param string $guid the message guid
1328 * @param string $server The server address
1329 * @param int $uid The user id of the user
1331 * @return int the message id of the stored message or false
1332 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1333 * @throws \ImagickException
1335 private static function storeByGuid($guid, $server, $uid = 0)
1337 $serverparts = parse_url($server);
1339 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1343 $server = $serverparts["scheme"]."://".$serverparts["host"];
1345 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1347 $msg = self::message($guid, $server);
1353 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1355 // Now call the dispatcher
1356 return self::dispatchPublic($msg);
1360 * Fetches a message from a server
1362 * @param string $guid message guid
1363 * @param string $server The url of the server
1364 * @param int $level Endless loop prevention
1367 * 'message' => The message XML
1368 * 'author' => The author handle
1369 * 'key' => The public key of the author
1370 * @throws \Exception
1372 private static function message($guid, $server, $level = 0)
1378 // This will work for new Diaspora servers and Friendica servers from 3.5
1379 $source_url = $server."/fetch/post/".urlencode($guid);
1381 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1383 $envelope = HTTPRequest::fetchUrl($source_url);
1385 Logger::log("Envelope was fetched.", Logger::DEBUG);
1386 $x = self::verifyMagicEnvelope($envelope);
1388 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1390 Logger::log("Envelope was verified.", Logger::DEBUG);
1400 $source_xml = XML::parseString($x);
1402 if (!is_object($source_xml)) {
1406 if ($source_xml->post->reshare) {
1407 // Reshare of a reshare - old Diaspora version
1408 Logger::log("Message is a reshare", Logger::DEBUG);
1409 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1410 } elseif ($source_xml->getName() == "reshare") {
1411 // Reshare of a reshare - new Diaspora version
1412 Logger::log("Message is a new reshare", Logger::DEBUG);
1413 return self::message($source_xml->root_guid, $server, ++$level);
1418 // Fetch the author - for the old and the new Diaspora version
1419 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1420 $author = (string)$source_xml->post->status_message->diaspora_handle;
1421 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1422 $author = (string)$source_xml->author;
1425 // If this isn't a "status_message" then quit
1427 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1431 $msg = ["message" => $x, "author" => $author];
1433 $msg["key"] = self::key($msg["author"]);
1439 * Fetches an item with a given URL
1441 * @param string $url the message url
1443 * @return int the message id of the stored message or false
1444 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1445 * @throws \ImagickException
1447 public static function fetchByURL($url, $uid = 0)
1449 // Check for Diaspora (and Friendica) typical paths
1450 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1451 Logger::info('Invalid url', ['url' => $url]);
1455 $guid = urldecode($matches[2]);
1457 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1458 if (DBA::isResult($item)) {
1459 Logger::info('Found', ['id' => $item['id']]);
1463 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1464 $ret = self::storeByGuid($guid, $matches[1], $uid);
1465 Logger::info('Result', ['ret' => $ret]);
1467 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1468 if (DBA::isResult($item)) {
1469 Logger::info('Found', ['id' => $item['id']]);
1472 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1478 * Fetches the item record of a given guid
1480 * @param int $uid The user id
1481 * @param string $guid message guid
1482 * @param string $author The handle of the item
1483 * @param array $contact The contact of the item owner
1485 * @return array the item record
1486 * @throws \Exception
1488 private static function parentItem($uid, $guid, $author, array $contact)
1490 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1491 'author-name', 'author-link', 'author-avatar', 'gravity',
1492 'owner-name', 'owner-link', 'owner-avatar'];
1493 $condition = ['uid' => $uid, 'guid' => $guid];
1494 $item = Item::selectFirst($fields, $condition);
1496 if (!DBA::isResult($item)) {
1497 $person = self::personByHandle($author);
1498 $result = self::storeByGuid($guid, $person["url"], $uid);
1500 // We don't have an url for items that arrived at the public dispatcher
1501 if (!$result && !empty($contact["url"])) {
1502 $result = self::storeByGuid($guid, $contact["url"], $uid);
1506 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1508 $item = Item::selectFirst($fields, $condition);
1512 if (!DBA::isResult($item)) {
1513 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1516 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1522 * returns contact details
1524 * @param array $def_contact The default contact if the person isn't found
1525 * @param array $person The record of the person
1526 * @param int $uid The user id
1529 * 'cid' => contact id
1530 * 'network' => network type
1531 * @throws \Exception
1533 private static function authorContactByUrl($def_contact, $person, $uid)
1535 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1536 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1537 if (DBA::isResult($contact)) {
1538 $cid = $contact["id"];
1539 $network = $contact["network"];
1541 $cid = $def_contact["id"];
1542 $network = Protocol::DIASPORA;
1545 return ["cid" => $cid, "network" => $network];
1549 * Is the profile a hubzilla profile?
1551 * @param string $url The profile link
1553 * @return bool is it a hubzilla server?
1555 private static function isHubzilla($url)
1557 return(strstr($url, '/channel/'));
1561 * Generate a post link with a given handle and message guid
1563 * @param string $addr The user handle
1564 * @param string $guid message guid
1565 * @param string $parent_guid optional parent guid
1567 * @return string the post link
1568 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1569 * @throws \ImagickException
1571 private static function plink($addr, $guid, $parent_guid = '')
1573 $contact = Contact::getByURL($addr);
1574 if (empty($contact)) {
1575 Logger::info('No contact data for address', ['addr' => $addr]);
1579 if (empty($contact['baseurl'])) {
1580 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1581 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1585 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1586 if (!empty($gserver['platform'])) {
1587 $platform = strtolower($gserver['platform']);
1588 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1591 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1592 if (self::isHubzilla($contact['url'])) {
1593 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1594 $platform = 'hubzilla';
1595 } elseif ($contact['network'] == Protocol::DFRN) {
1596 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1597 $platform = 'friendica';
1601 if ($platform == 'friendica') {
1602 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1605 if ($platform == 'hubzilla') {
1606 return $contact['baseurl'] . '/item/' . $guid;
1609 if ($platform == 'socialhome') {
1610 return $contact['baseurl'] . '/content/' . $guid;
1613 if ($platform != 'diaspora') {
1614 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1618 if ($parent_guid != '') {
1619 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1621 return $contact['baseurl'] . '/posts/' . $guid;
1626 * Receives account migration
1628 * @param array $importer Array of the importer user
1629 * @param object $data The message object
1631 * @return bool Success
1632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1633 * @throws \ImagickException
1635 private static function receiveAccountMigration(array $importer, $data)
1637 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1638 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1639 $signature = Strings::escapeTags(XML::unescape($data->signature));
1641 $contact = self::contactByHandle($importer["uid"], $old_handle);
1643 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1647 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1650 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1651 $key = self::key($old_handle);
1652 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1653 Logger::log('No valid signature for migration.');
1657 // Update the profile
1658 self::receiveProfile($importer, $data->profile);
1660 // change the technical stuff in contact and gcontact
1661 $data = Probe::uri($new_handle);
1662 if ($data['network'] == Protocol::PHANTOM) {
1663 Logger::log('Account for '.$new_handle." couldn't be probed.");
1667 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1668 'name' => $data['name'], 'nick' => $data['nick'],
1669 'addr' => $data['addr'], 'batch' => $data['batch'],
1670 'notify' => $data['notify'], 'poll' => $data['poll'],
1671 'network' => $data['network']];
1673 DBA::update('contact', $fields, ['addr' => $old_handle]);
1675 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1676 'name' => $data['name'], 'nick' => $data['nick'],
1677 'addr' => $data['addr'], 'connect' => $data['addr'],
1678 'notify' => $data['notify'], 'photo' => $data['photo'],
1679 'server_url' => $data['baseurl'], 'network' => $data['network']];
1681 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1683 Logger::log('Contacts are updated.');
1689 * Processes an account deletion
1691 * @param object $data The message object
1693 * @return bool Success
1694 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1696 private static function receiveAccountDeletion($data)
1698 $author = Strings::escapeTags(XML::unescape($data->author));
1700 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1701 while ($contact = DBA::fetch($contacts)) {
1702 Contact::remove($contact["id"]);
1704 DBA::close($contacts);
1706 DBA::delete('gcontact', ['addr' => $author]);
1708 Logger::log('Removed contacts for ' . $author);
1714 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1716 * @param string $author Author handle
1717 * @param string $guid Message guid
1718 * @param boolean $onlyfound Only return uri when found in the database
1720 * @return string The constructed uri or the one from our database
1721 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1722 * @throws \ImagickException
1724 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1726 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1727 if (DBA::isResult($item)) {
1728 return $item["uri"];
1729 } elseif (!$onlyfound) {
1730 $person = self::personByHandle($author);
1732 $parts = parse_url($person['url']);
1733 unset($parts['path']);
1734 $host_url = Network::unparseURL($parts);
1736 return $host_url . '/objects/' . $guid;
1743 * Fetch the guid from our database with a given uri
1745 * @param string $uri Message uri
1746 * @param string $uid Author handle
1748 * @return string The post guid
1749 * @throws \Exception
1751 private static function getGuidFromUri($uri, $uid)
1753 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1754 if (DBA::isResult($item)) {
1755 return $item["guid"];
1762 * Find the best importer for a comment, like, ...
1764 * @param string $guid The guid of the item
1766 * @return array|boolean the origin owner of that post - or false
1767 * @throws \Exception
1769 private static function importerForGuid($guid)
1771 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1772 if (DBA::isResult($item)) {
1773 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1774 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1775 if (DBA::isResult($contact)) {
1783 * Store the mentions in the tag table
1785 * @param integer $uriid
1786 * @param string $text
1788 private static function storeMentions(int $uriid, string $text)
1790 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1791 if (empty($matches)) {
1796 * Matching values for the preg match
1797 * [1] = mention type (@ or !)
1798 * [2] = name (optional)
1802 foreach ($matches as $match) {
1803 if (empty($match)) {
1807 $person = self::personByHandle($match[3]);
1808 if (empty($person)) {
1812 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1817 * Processes an incoming comment
1819 * @param array $importer Array of the importer user
1820 * @param string $sender The sender of the message
1821 * @param object $data The message object
1822 * @param string $xml The original XML of the message
1824 * @return int The message id of the generated comment or "false" if there was an error
1825 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1826 * @throws \ImagickException
1828 private static function receiveComment(array $importer, $sender, $data, $xml)
1830 $author = Strings::escapeTags(XML::unescape($data->author));
1831 $guid = Strings::escapeTags(XML::unescape($data->guid));
1832 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1833 $text = XML::unescape($data->text);
1835 if (isset($data->created_at)) {
1836 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1838 $created_at = DateTimeFormat::utcNow();
1841 if (isset($data->thread_parent_guid)) {
1842 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1843 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1848 $contact = self::allowedContactByHandle($importer, $sender, true);
1853 $message_id = self::messageExists($importer["uid"], $guid);
1858 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1859 if (!$parent_item) {
1863 $person = self::personByHandle($author);
1864 if (!is_array($person)) {
1865 Logger::log("unable to find author details");
1869 // Fetch the contact id - if we know this contact
1870 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1874 $datarray["uid"] = $importer["uid"];
1875 $datarray["contact-id"] = $author_contact["cid"];
1876 $datarray["network"] = $author_contact["network"];
1878 $datarray["author-link"] = $person["url"];
1879 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1881 $datarray["owner-link"] = $contact["url"];
1882 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1884 $datarray["guid"] = $guid;
1885 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1886 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1888 $datarray["verb"] = Activity::POST;
1889 $datarray["gravity"] = GRAVITY_COMMENT;
1891 if ($thr_uri != "") {
1892 $datarray["parent-uri"] = $thr_uri;
1894 $datarray["parent-uri"] = $parent_item["uri"];
1897 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1899 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1900 $datarray["source"] = $xml;
1902 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1904 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1905 $body = Markdown::toBBCode($text);
1907 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1909 self::storeMentions($datarray['uri-id'], $text);
1910 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1912 self::fetchGuid($datarray);
1914 // If we are the origin of the parent we store the original data.
1915 // We notify our followers during the item storage.
1916 if ($parent_item["origin"]) {
1917 $datarray['diaspora_signed_text'] = json_encode($data);
1920 $message_id = Item::insert($datarray);
1922 if ($message_id <= 0) {
1927 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1928 if ($datarray['uid'] == 0) {
1929 Item::distribute($message_id, json_encode($data));
1937 * processes and stores private messages
1939 * @param array $importer Array of the importer user
1940 * @param array $contact The contact of the message
1941 * @param object $data The message object
1942 * @param array $msg Array of the processed message, author handle and key
1943 * @param object $mesg The private message
1944 * @param array $conversation The conversation record to which this message belongs
1946 * @return bool "true" if it was successful
1947 * @throws \Exception
1949 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1951 $author = Strings::escapeTags(XML::unescape($data->author));
1952 $guid = Strings::escapeTags(XML::unescape($data->guid));
1953 $subject = Strings::escapeTags(XML::unescape($data->subject));
1955 // "diaspora_handle" is the element name from the old version
1956 // "author" is the element name from the new version
1957 if ($mesg->author) {
1958 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1959 } elseif ($mesg->diaspora_handle) {
1960 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1965 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1966 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1967 $msg_text = XML::unescape($mesg->text);
1968 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1970 if ($msg_conversation_guid != $guid) {
1971 Logger::log("message conversation guid does not belong to the current conversation.");
1975 $body = Markdown::toBBCode($msg_text);
1976 $message_uri = $msg_author.":".$msg_guid;
1978 $person = self::personByHandle($msg_author);
1980 return Mail::insert([
1981 'uid' => $importer['uid'],
1982 'guid' => $msg_guid,
1983 'convid' => $conversation['id'],
1984 'from-name' => $person['name'],
1985 'from-photo' => $person['photo'],
1986 'from-url' => $person['url'],
1987 'contact-id' => $contact['id'],
1988 'title' => $subject,
1990 'uri' => $message_uri,
1991 'parent-uri' => $author . ':' . $guid,
1992 'created' => $msg_created_at
1997 * Processes new private messages (answers to private messages are processed elsewhere)
1999 * @param array $importer Array of the importer user
2000 * @param array $msg Array of the processed message, author handle and key
2001 * @param object $data The message object
2003 * @return bool Success
2004 * @throws \Exception
2006 private static function receiveConversation(array $importer, $msg, $data)
2008 $author = Strings::escapeTags(XML::unescape($data->author));
2009 $guid = Strings::escapeTags(XML::unescape($data->guid));
2010 $subject = Strings::escapeTags(XML::unescape($data->subject));
2011 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2012 $participants = Strings::escapeTags(XML::unescape($data->participants));
2014 $messages = $data->message;
2016 if (!count($messages)) {
2017 Logger::log("empty conversation");
2021 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2026 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2027 if (!DBA::isResult($conversation)) {
2029 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2030 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2031 intval($importer["uid"]),
2033 DBA::escape($author),
2034 DBA::escape($created_at),
2035 DBA::escape(DateTimeFormat::utcNow()),
2036 DBA::escape($subject),
2037 DBA::escape($participants)
2040 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2043 if (!$conversation) {
2044 Logger::log("unable to create conversation.");
2048 foreach ($messages as $mesg) {
2049 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2056 * Processes "like" messages
2058 * @param array $importer Array of the importer user
2059 * @param string $sender The sender of the message
2060 * @param object $data The message object
2062 * @return int The message id of the generated like or "false" if there was an error
2063 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2064 * @throws \ImagickException
2066 private static function receiveLike(array $importer, $sender, $data)
2068 $author = Strings::escapeTags(XML::unescape($data->author));
2069 $guid = Strings::escapeTags(XML::unescape($data->guid));
2070 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2071 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2072 $positive = Strings::escapeTags(XML::unescape($data->positive));
2074 // likes on comments aren't supported by Diaspora - only on posts
2075 // But maybe this will be supported in the future, so we will accept it.
2076 if (!in_array($parent_type, ["Post", "Comment"])) {
2080 $contact = self::allowedContactByHandle($importer, $sender, true);
2085 $message_id = self::messageExists($importer["uid"], $guid);
2090 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2091 if (!$parent_item) {
2095 $person = self::personByHandle($author);
2096 if (!is_array($person)) {
2097 Logger::log("unable to find author details");
2101 // Fetch the contact id - if we know this contact
2102 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2104 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2105 // We would accept this anyhow.
2106 if ($positive == "true") {
2107 $verb = Activity::LIKE;
2109 $verb = Activity::DISLIKE;
2114 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2116 $datarray["uid"] = $importer["uid"];
2117 $datarray["contact-id"] = $author_contact["cid"];
2118 $datarray["network"] = $author_contact["network"];
2120 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2121 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2123 $datarray["guid"] = $guid;
2124 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2126 $datarray["verb"] = $verb;
2127 $datarray["gravity"] = GRAVITY_ACTIVITY;
2128 $datarray["parent-uri"] = $parent_item["uri"];
2130 $datarray["object-type"] = Activity\ObjectType::NOTE;
2132 $datarray["body"] = $verb;
2134 // Diaspora doesn't provide a date for likes
2135 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2137 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2138 if ($parent_item['gravity'] != GRAVITY_PARENT) {
2139 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item['parent']]);
2140 $origin = $toplevel["origin"];
2142 $origin = $parent_item["origin"];
2145 // If we are the origin of the parent we store the original data.
2146 // We notify our followers during the item storage.
2148 $datarray['diaspora_signed_text'] = json_encode($data);
2151 $message_id = Item::insert($datarray);
2153 if ($message_id <= 0) {
2158 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2159 if ($datarray['uid'] == 0) {
2160 Item::distribute($message_id, json_encode($data));
2168 * Processes private messages
2170 * @param array $importer Array of the importer user
2171 * @param object $data The message object
2173 * @return bool Success?
2174 * @throws \Exception
2176 private static function receiveMessage(array $importer, $data)
2178 $author = Strings::escapeTags(XML::unescape($data->author));
2179 $guid = Strings::escapeTags(XML::unescape($data->guid));
2180 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2181 $text = XML::unescape($data->text);
2182 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2184 $contact = self::allowedContactByHandle($importer, $author, true);
2189 $conversation = null;
2191 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2192 $conversation = DBA::selectFirst('conv', [], $condition);
2194 if (!DBA::isResult($conversation)) {
2195 Logger::log("conversation not available.");
2199 $message_uri = $author.":".$guid;
2201 $person = self::personByHandle($author);
2203 Logger::log("unable to find author details");
2207 $body = Markdown::toBBCode($text);
2209 $body = self::replacePeopleGuid($body, $person["url"]);
2211 return Mail::insert([
2212 'uid' => $importer['uid'],
2214 'convid' => $conversation['id'],
2215 'from-name' => $person['name'],
2216 'from-photo' => $person['photo'],
2217 'from-url' => $person['url'],
2218 'contact-id' => $contact['id'],
2219 'title' => $conversation['subject'],
2222 'uri' => $message_uri,
2223 'parent-uri' => $author.":".$conversation['guid'],
2224 'created' => $created_at
2229 * Processes participations - unsupported by now
2231 * @param array $importer Array of the importer user
2232 * @param object $data The message object
2234 * @return bool success
2235 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2236 * @throws \ImagickException
2238 private static function receiveParticipation(array $importer, $data)
2240 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2241 $guid = Strings::escapeTags(XML::unescape($data->guid));
2242 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2244 $contact = self::allowedContactByHandle($importer, $author, true);
2249 if (self::messageExists($importer["uid"], $guid)) {
2253 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2254 if (!$parent_item) {
2258 if (!$parent_item['origin']) {
2259 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2262 if (!in_array($parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
2263 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2267 $person = self::personByHandle($author);
2268 if (!is_array($person)) {
2269 Logger::log("Person not found: ".$author);
2273 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2275 // Store participation
2278 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2280 $datarray["uid"] = $importer["uid"];
2281 $datarray["contact-id"] = $author_contact["cid"];
2282 $datarray["network"] = $author_contact["network"];
2284 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2285 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2287 $datarray["guid"] = $guid;
2288 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2290 $datarray["verb"] = Activity::FOLLOW;
2291 $datarray["gravity"] = GRAVITY_ACTIVITY;
2292 $datarray["parent-uri"] = $parent_item["uri"];
2294 $datarray["object-type"] = Activity\ObjectType::NOTE;
2296 $datarray["body"] = Activity::FOLLOW;
2298 // Diaspora doesn't provide a date for a participation
2299 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2301 $message_id = Item::insert($datarray);
2303 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2305 // Send all existing comments and likes to the requesting server
2306 $comments = Item::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
2307 ['parent' => $parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
2308 while ($comment = Item::fetch($comments)) {
2309 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2310 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2314 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2315 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2319 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2320 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2324 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2325 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2326 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2329 DBA::close($comments);
2335 * Processes photos - unneeded
2337 * @param array $importer Array of the importer user
2338 * @param object $data The message object
2340 * @return bool always true
2342 private static function receivePhoto(array $importer, $data)
2344 // There doesn't seem to be a reason for this function,
2345 // since the photo data is transmitted in the status message as well
2350 * Processes poll participations - unssupported
2352 * @param array $importer Array of the importer user
2353 * @param object $data The message object
2355 * @return bool always true
2357 private static function receivePollParticipation(array $importer, $data)
2359 // We don't support polls by now
2364 * Processes incoming profile updates
2366 * @param array $importer Array of the importer user
2367 * @param object $data The message object
2369 * @return bool Success
2370 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2371 * @throws \ImagickException
2373 private static function receiveProfile(array $importer, $data)
2375 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2377 $contact = self::contactByHandle($importer["uid"], $author);
2382 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2383 $image_url = XML::unescape($data->image_url);
2384 $birthday = XML::unescape($data->birthday);
2385 $about = Markdown::toBBCode(XML::unescape($data->bio));
2386 $location = Markdown::toBBCode(XML::unescape($data->location));
2387 $searchable = (XML::unescape($data->searchable) == "true");
2388 $nsfw = (XML::unescape($data->nsfw) == "true");
2389 $tags = XML::unescape($data->tag_string);
2391 $tags = explode("#", $tags);
2394 foreach ($tags as $tag) {
2395 $tag = trim(strtolower($tag));
2401 $keywords = implode(", ", $keywords);
2403 $handle_parts = explode("@", $author);
2404 $nick = $handle_parts[0];
2407 $name = $handle_parts[0];
2410 if (preg_match("|^https?://|", $image_url) === 0) {
2411 $image_url = "http://".$handle_parts[1].$image_url;
2414 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2416 // Generic birthday. We don't know the timezone. The year is irrelevant.
2418 $birthday = str_replace("1000", "1901", $birthday);
2420 if ($birthday != "") {
2421 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2424 // this is to prevent multiple birthday notifications in a single year
2425 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2427 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2428 $birthday = $contact["bd"];
2431 $fields = ['name' => $name, 'location' => $location,
2432 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2433 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2434 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2436 if (!empty($birthday)) {
2437 $fields['bd'] = $birthday;
2440 DBA::update('contact', $fields, ['id' => $contact['id']]);
2442 // @todo Update the public contact, then update the gcontact from that
2444 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2445 "photo" => $image_url, "name" => $name, "location" => $location,
2446 "about" => $about, "birthday" => $birthday,
2447 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2448 "hide" => !$searchable, "nsfw" => $nsfw];
2450 $gcid = GContact::update($gcontact);
2452 GContact::link($gcid, $importer["uid"], $contact["id"]);
2454 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2460 * Processes incoming friend requests
2462 * @param array $importer Array of the importer user
2463 * @param array $contact The contact that send the request
2465 * @throws \Exception
2467 private static function receiveRequestMakeFriend(array $importer, array $contact)
2469 if ($contact["rel"] == Contact::SHARING) {
2472 ['rel' => Contact::FRIEND, 'writable' => true],
2473 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2479 * Processes incoming sharing notification
2481 * @param array $importer Array of the importer user
2482 * @param object $data The message object
2484 * @return bool Success
2485 * @throws \Exception
2487 private static function receiveContactRequest(array $importer, $data)
2489 $author = XML::unescape($data->author);
2490 $recipient = XML::unescape($data->recipient);
2492 if (!$author || !$recipient) {
2496 // the current protocol version doesn't know these fields
2497 // That means that we will assume their existance
2498 if (isset($data->following)) {
2499 $following = (XML::unescape($data->following) == "true");
2504 if (isset($data->sharing)) {
2505 $sharing = (XML::unescape($data->sharing) == "true");
2510 $contact = self::contactByHandle($importer["uid"], $author);
2512 // perhaps we were already sharing with this person. Now they're sharing with us.
2513 // That makes us friends.
2516 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2517 self::receiveRequestMakeFriend($importer, $contact);
2519 // refetch the contact array
2520 $contact = self::contactByHandle($importer["uid"], $author);
2522 // If we are now friends, we are sending a share message.
2523 // Normally we needn't to do so, but the first message could have been vanished.
2524 if (in_array($contact["rel"], [Contact::FRIEND])) {
2525 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2526 if (DBA::isResult($user)) {
2527 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2528 self::sendShare($user, $contact);
2533 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2534 Contact::removeFollower($importer, $contact);
2539 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2540 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2542 } elseif (!$following && !$sharing) {
2543 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2545 } elseif (!$following && $sharing) {
2546 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2547 } elseif ($following && $sharing) {
2548 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2549 } elseif ($following && !$sharing) {
2550 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2553 $ret = self::personByHandle($author);
2555 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2556 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2560 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2562 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2567 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2568 'author-link' => $ret['url']];
2570 $result = Contact::addRelationship($importer, $contact, $item, false);
2571 if ($result === true) {
2572 $contact_record = self::contactByHandle($importer['uid'], $author);
2573 if (!$contact_record) {
2574 Logger::info('unable to locate newly created contact record.');
2578 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2579 if (DBA::isResult($user)) {
2580 self::sendShare($user, $contact_record);
2582 // Send the profile data, maybe it weren't transmitted before
2583 self::sendProfile($importer['uid'], [$contact_record]);
2591 * Fetches a message with a given guid
2593 * @param string $guid message guid
2594 * @param string $orig_author handle of the original post
2595 * @return array The fetched item
2596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2597 * @throws \ImagickException
2599 public static function originalItem($guid, $orig_author)
2602 Logger::log('Empty guid. Quitting.');
2606 // Do we already have this item?
2607 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2608 'author-name', 'author-link', 'author-avatar', 'plink'];
2609 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2610 $item = Item::selectFirst($fields, $condition);
2612 if (DBA::isResult($item)) {
2613 Logger::log("reshared message ".$guid." already exists on system.");
2615 // Maybe it is already a reshared item?
2616 // Then refetch the content, if it is a reshare from a reshare.
2617 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2618 if (self::isReshare($item["body"], true)) {
2620 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2621 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2623 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2625 // Add OEmbed and other information to the body
2626 $item["body"] = PageInfo::searchAndAppendToBody($item["body"], false, true);
2634 if (!DBA::isResult($item)) {
2635 if (empty($orig_author)) {
2636 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2640 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2641 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2642 $stored = self::storeByGuid($guid, $server);
2645 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2646 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2647 $stored = self::storeByGuid($guid, $server);
2651 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2652 'author-name', 'author-link', 'author-avatar', 'plink'];
2653 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2654 $item = Item::selectFirst($fields, $condition);
2656 if (DBA::isResult($item)) {
2657 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2658 if (self::isReshare($item["body"], false)) {
2659 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2660 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2671 * Stores a reshare activity
2673 * @param array $item Array of reshare post
2674 * @param integer $parent_message_id Id of the parent post
2675 * @param string $guid GUID string of reshare action
2676 * @param string $author Author handle
2678 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2680 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2684 $datarray['uid'] = $item['uid'];
2685 $datarray['contact-id'] = $item['contact-id'];
2686 $datarray['network'] = $item['network'];
2688 $datarray['author-link'] = $item['author-link'];
2689 $datarray['author-id'] = $item['author-id'];
2691 $datarray['owner-link'] = $datarray['author-link'];
2692 $datarray['owner-id'] = $datarray['author-id'];
2694 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2695 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2696 $datarray['parent-uri'] = $parent['uri'];
2698 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2699 $datarray['gravity'] = GRAVITY_ACTIVITY;
2700 $datarray['object-type'] = Activity\ObjectType::NOTE;
2702 $datarray['protocol'] = $item['protocol'];
2704 $datarray['plink'] = self::plink($author, $datarray['guid']);
2705 $datarray['private'] = $item['private'];
2706 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2708 $message_id = Item::insert($datarray);
2711 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2712 if ($datarray['uid'] == 0) {
2713 Item::distribute($message_id);
2719 * Processes a reshare message
2721 * @param array $importer Array of the importer user
2722 * @param object $data The message object
2723 * @param string $xml The original XML of the message
2725 * @return int the message id
2726 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2727 * @throws \ImagickException
2729 private static function receiveReshare(array $importer, $data, $xml)
2731 $author = Strings::escapeTags(XML::unescape($data->author));
2732 $guid = Strings::escapeTags(XML::unescape($data->guid));
2733 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2734 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2735 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2736 /// @todo handle unprocessed property "provider_display_name"
2737 $public = Strings::escapeTags(XML::unescape($data->public));
2739 $contact = self::allowedContactByHandle($importer, $author, false);
2744 $message_id = self::messageExists($importer["uid"], $guid);
2749 $original_item = self::originalItem($root_guid, $root_author);
2750 if (!$original_item) {
2756 $datarray["uid"] = $importer["uid"];
2757 $datarray["contact-id"] = $contact["id"];
2758 $datarray["network"] = Protocol::DIASPORA;
2760 $datarray["author-link"] = $contact["url"];
2761 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2763 $datarray["owner-link"] = $datarray["author-link"];
2764 $datarray["owner-id"] = $datarray["author-id"];
2766 $datarray["guid"] = $guid;
2767 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2768 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2770 $datarray["verb"] = Activity::POST;
2771 $datarray["gravity"] = GRAVITY_PARENT;
2773 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2774 $datarray["source"] = $xml;
2776 /// @todo Copy tag data from original post
2778 $prefix = BBCode::getShareOpeningTag(
2779 $original_item["author-name"],
2780 $original_item["author-link"],
2781 $original_item["author-avatar"],
2782 $original_item["plink"],
2783 $original_item["created"],
2784 $original_item["guid"]
2787 if (!empty($original_item['title'])) {
2788 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2791 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2793 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2795 $datarray["attach"] = $original_item["attach"];
2796 $datarray["app"] = $original_item["app"];
2798 $datarray["plink"] = self::plink($author, $guid);
2799 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2800 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2802 $datarray["object-type"] = $original_item["object-type"];
2804 self::fetchGuid($datarray);
2805 $message_id = Item::insert($datarray);
2807 self::sendParticipation($contact, $datarray);
2809 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2810 if ($root_message_id) {
2811 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2815 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2816 if ($datarray['uid'] == 0) {
2817 Item::distribute($message_id);
2826 * Processes retractions
2828 * @param array $importer Array of the importer user
2829 * @param array $contact The contact of the item owner
2830 * @param object $data The message object
2832 * @return bool success
2833 * @throws \Exception
2835 private static function itemRetraction(array $importer, array $contact, $data)
2837 $author = Strings::escapeTags(XML::unescape($data->author));
2838 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2839 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2841 $person = self::personByHandle($author);
2842 if (!is_array($person)) {
2843 Logger::log("unable to find author detail for ".$author);
2847 if (empty($contact["url"])) {
2848 $contact["url"] = $person["url"];
2851 // Fetch items that are about to be deleted
2852 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2854 // When we receive a public retraction, we delete every item that we find.
2855 if ($importer['uid'] == 0) {
2856 $condition = ['guid' => $target_guid, 'deleted' => false];
2858 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2861 $r = Item::select($fields, $condition);
2862 if (!DBA::isResult($r)) {
2863 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2867 while ($item = Item::fetch($r)) {
2868 if (strstr($item['file'], '[')) {
2869 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2873 // Fetch the parent item
2874 $parent = Item::selectFirst(['author-link'], ['id' => $item['parent']]);
2876 // Only delete it if the parent author really fits
2877 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2878 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2882 Item::markForDeletion(['id' => $item['id']]);
2884 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent'], Logger::DEBUG);
2891 * Receives retraction messages
2893 * @param array $importer Array of the importer user
2894 * @param string $sender The sender of the message
2895 * @param object $data The message object
2897 * @return bool Success
2898 * @throws \Exception
2900 private static function receiveRetraction(array $importer, $sender, $data)
2902 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2904 $contact = self::contactByHandle($importer["uid"], $sender);
2905 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2906 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2914 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2916 switch ($target_type) {
2921 case "StatusMessage":
2922 return self::itemRetraction($importer, $contact, $data);
2924 case "PollParticipation":
2926 // Currently unsupported
2930 Logger::log("Unknown target type ".$target_type);
2937 * Receives status messages
2939 * @param array $importer Array of the importer user
2940 * @param SimpleXMLElement $data The message object
2941 * @param string $xml The original XML of the message
2943 * @return int The message id of the newly created item
2944 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2945 * @throws \ImagickException
2947 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2949 $author = Strings::escapeTags(XML::unescape($data->author));
2950 $guid = Strings::escapeTags(XML::unescape($data->guid));
2951 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2952 $public = Strings::escapeTags(XML::unescape($data->public));
2953 $text = XML::unescape($data->text);
2954 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2956 $contact = self::allowedContactByHandle($importer, $author, false);
2961 $message_id = self::messageExists($importer["uid"], $guid);
2967 if ($data->location) {
2968 foreach ($data->location->children() as $fieldname => $data) {
2969 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2973 $body = Markdown::toBBCode($text);
2977 // Attach embedded pictures to the body
2979 foreach ($data->photo as $photo) {
2980 $body = "[img]".XML::unescape($photo->remote_photo_path).
2981 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2984 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2986 $datarray["object-type"] = Activity\ObjectType::NOTE;
2988 // Add OEmbed and other information to the body
2989 if (!self::isHubzilla($contact["url"])) {
2990 $body = PageInfo::searchAndAppendToBody($body, false, true);
2994 /// @todo enable support for polls
2995 //if ($data->poll) {
2996 // foreach ($data->poll AS $poll)
3001 /// @todo enable support for events
3003 $datarray["uid"] = $importer["uid"];
3004 $datarray["contact-id"] = $contact["id"];
3005 $datarray["network"] = Protocol::DIASPORA;
3007 $datarray["author-link"] = $contact["url"];
3008 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
3010 $datarray["owner-link"] = $datarray["author-link"];
3011 $datarray["owner-id"] = $datarray["author-id"];
3013 $datarray["guid"] = $guid;
3014 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3015 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
3017 $datarray["verb"] = Activity::POST;
3018 $datarray["gravity"] = GRAVITY_PARENT;
3020 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3021 $datarray["source"] = $xml;
3023 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3025 self::storeMentions($datarray['uri-id'], $text);
3026 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
3028 if ($provider_display_name != "") {
3029 $datarray["app"] = $provider_display_name;
3032 $datarray["plink"] = self::plink($author, $guid);
3033 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3034 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3036 if (isset($address["address"])) {
3037 $datarray["location"] = $address["address"];
3040 if (isset($address["lat"]) && isset($address["lng"])) {
3041 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3044 self::fetchGuid($datarray);
3045 $message_id = Item::insert($datarray);
3047 self::sendParticipation($contact, $datarray);
3050 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3051 if ($datarray['uid'] == 0) {
3052 Item::distribute($message_id);
3060 /* ************************************************************************************** *
3061 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3062 * ************************************************************************************** */
3065 * returnes the handle of a contact
3067 * @param array $contact contact array
3069 * @return string the handle in the format user@domain.tld
3070 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3072 private static function myHandle(array $contact)
3074 if (!empty($contact["addr"])) {
3075 return $contact["addr"];
3078 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3079 // So - just in case - we build the the address here.
3080 if ($contact["nickname"] != "") {
3081 $nick = $contact["nickname"];
3083 $nick = $contact["nick"];
3086 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3091 * Creates the data for a private message in the new format
3093 * @param string $msg The message that is to be transmitted
3094 * @param array $user The record of the sender
3095 * @param array $contact Target of the communication
3096 * @param string $prvkey The private key of the sender
3097 * @param string $pubkey The public key of the receiver
3099 * @return string The encrypted data
3100 * @throws \Exception
3102 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3104 Logger::log("Message: ".$msg, Logger::DATA);
3106 // without a public key nothing will work
3108 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3112 $aes_key = openssl_random_pseudo_bytes(32);
3113 $b_aes_key = base64_encode($aes_key);
3114 $iv = openssl_random_pseudo_bytes(16);
3115 $b_iv = base64_encode($iv);
3117 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3119 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3121 $encrypted_key_bundle = "";
3122 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
3126 $json_object = json_encode(
3127 ["aes_key" => base64_encode($encrypted_key_bundle),
3128 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3131 return $json_object;
3135 * Creates the envelope for the "fetch" endpoint and for the new format
3137 * @param string $msg The message that is to be transmitted
3138 * @param array $user The record of the sender
3140 * @return string The envelope
3141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3143 public static function buildMagicEnvelope($msg, array $user)
3145 $b64url_data = Strings::base64UrlEncode($msg);
3146 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3148 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3149 $type = "application/xml";
3150 $encoding = "base64url";
3151 $alg = "RSA-SHA256";
3152 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3154 // Fallback if the private key wasn't transmitted in the expected field
3155 if ($user['uprvkey'] == "") {
3156 $user['uprvkey'] = $user['prvkey'];
3159 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3160 $sig = Strings::base64UrlEncode($signature);
3162 $xmldata = ["me:env" => ["me:data" => $data,
3163 "@attributes" => ["type" => $type],
3164 "me:encoding" => $encoding,
3167 "@attributes2" => ["key_id" => $key_id]]];
3169 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3171 return XML::fromArray($xmldata, $xml, false, $namespaces);
3175 * Create the envelope for a message
3177 * @param string $msg The message that is to be transmitted
3178 * @param array $user The record of the sender
3179 * @param array $contact Target of the communication
3180 * @param string $prvkey The private key of the sender
3181 * @param string $pubkey The public key of the receiver
3182 * @param bool $public Is the message public?
3184 * @return string The message that will be transmitted to other servers
3185 * @throws \Exception
3187 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3189 // The message is put into an envelope with the sender's signature
3190 $envelope = self::buildMagicEnvelope($msg, $user);
3192 // Private messages are put into a second envelope, encrypted with the receivers public key
3194 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3201 * Creates a signature for a message
3203 * @param array $owner the array of the owner of the message
3204 * @param array $message The message that is to be signed
3206 * @return string The signature
3208 private static function signature($owner, $message)
3211 unset($sigmsg["author_signature"]);
3212 unset($sigmsg["parent_author_signature"]);
3214 $signed_text = implode(";", $sigmsg);
3216 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3220 * Transmit a message to a target server
3222 * @param array $owner the array of the item owner
3223 * @param array $contact Target of the communication
3224 * @param string $envelope The message that is to be transmitted
3225 * @param bool $public_batch Is it a public post?
3226 * @param string $guid message guid
3228 * @return int Result of the transmission
3229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3230 * @throws \ImagickException
3232 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3234 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3239 $logid = Strings::getRandomHex(4);
3241 // We always try to use the data from the fcontact table.
3242 // This is important for transmitting data to Friendica servers.
3243 if (!empty($contact['addr'])) {
3244 $fcontact = self::personByHandle($contact['addr']);
3245 if (!empty($fcontact)) {
3246 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3250 if (empty($dest_url)) {
3251 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3255 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3259 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3261 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3262 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3264 $postResult = HTTPRequest::post($dest_url . "/", $envelope, ["Content-Type: " . $content_type]);
3265 $return_code = $postResult->getReturnCode();
3267 Logger::log("test_mode");
3271 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3273 return $return_code ? $return_code : -1;
3278 * Build the post xml
3280 * @param string $type The message type
3281 * @param array $message The message data
3283 * @return string The post XML
3285 public static function buildPostXml($type, $message)
3287 $data = [$type => $message];
3289 return XML::fromArray($data, $xml);
3293 * Builds and transmit messages
3295 * @param array $owner the array of the item owner
3296 * @param array $contact Target of the communication
3297 * @param string $type The message type
3298 * @param array $message The message data
3299 * @param bool $public_batch Is it a public post?
3300 * @param string $guid message guid
3302 * @return int Result of the transmission
3303 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3304 * @throws \ImagickException
3306 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3308 $msg = self::buildPostXml($type, $message);
3310 Logger::log('message: '.$msg, Logger::DATA);
3311 Logger::log('send guid '.$guid, Logger::DEBUG);
3313 // Fallback if the private key wasn't transmitted in the expected field
3314 if (empty($owner['uprvkey'])) {
3315 $owner['uprvkey'] = $owner['prvkey'];
3318 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3320 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3322 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3324 return $return_code;
3328 * sends a participation (Used to get all further updates)
3330 * @param array $contact Target of the communication
3331 * @param array $item Item array
3333 * @return int The result of the transmission
3334 * @throws \Exception
3336 private static function sendParticipation(array $contact, array $item)
3338 // Don't send notifications for private postings
3339 if ($item['private'] == Item::PRIVATE) {
3343 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3345 $result = DI::cache()->get($cachekey);
3346 if (!is_null($result)) {
3350 // Fetch some user id to have a valid handle to transmit the participation.
3351 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3352 // If the item belongs to a user, we take this user id.
3353 if ($item['uid'] == 0) {
3354 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3355 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3356 $owner = User::getOwnerDataById($first_user['uid']);
3358 $owner = User::getOwnerDataById($item['uid']);
3361 $author = self::myHandle($owner);
3363 $message = ["author" => $author,
3364 "guid" => System::createUUID(),
3365 "parent_type" => "Post",
3366 "parent_guid" => $item["guid"]];
3368 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3370 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3371 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3373 return self::buildAndTransmit($owner, $contact, "participation", $message);
3377 * sends an account migration
3379 * @param array $owner the array of the item owner
3380 * @param array $contact Target of the communication
3381 * @param int $uid User ID
3383 * @return int The result of the transmission
3384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3385 * @throws \ImagickException
3387 public static function sendAccountMigration(array $owner, array $contact, $uid)
3389 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3390 $profile = self::createProfileData($uid);
3392 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3393 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3395 $message = ["author" => $old_handle,
3396 "profile" => $profile,
3397 "signature" => $signature];
3399 Logger::info('Send account migration', ['msg' => $message]);
3401 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3405 * Sends a "share" message
3407 * @param array $owner the array of the item owner
3408 * @param array $contact Target of the communication
3410 * @return int The result of the transmission
3411 * @throws \Exception
3413 public static function sendShare(array $owner, array $contact)
3416 * @todo support the different possible combinations of "following" and "sharing"
3417 * Currently, Diaspora only interprets the "sharing" field
3419 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3423 switch ($contact["rel"]) {
3424 case Contact::FRIEND:
3428 case Contact::SHARING:
3432 case Contact::FOLLOWER:
3438 $message = ["author" => self::myHandle($owner),
3439 "recipient" => $contact["addr"],
3440 "following" => "true",
3441 "sharing" => "true"];
3443 Logger::info('Send share', ['msg' => $message]);
3445 return self::buildAndTransmit($owner, $contact, "contact", $message);
3449 * sends an "unshare"
3451 * @param array $owner the array of the item owner
3452 * @param array $contact Target of the communication
3454 * @return int The result of the transmission
3455 * @throws \Exception
3457 public static function sendUnshare(array $owner, array $contact)
3459 $message = ["author" => self::myHandle($owner),
3460 "recipient" => $contact["addr"],
3461 "following" => "false",
3462 "sharing" => "false"];
3464 Logger::info('Send unshare', ['msg' => $message]);
3466 return self::buildAndTransmit($owner, $contact, "contact", $message);
3470 * Checks a message body if it is a reshare
3472 * @param string $body The message body that is to be check
3473 * @param bool $complete Should it be a complete check or a simple check?
3475 * @return array|bool Reshare details or "false" if no reshare
3476 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3477 * @throws \ImagickException
3479 public static function isReshare($body, $complete = true)
3481 $body = trim($body);
3483 $reshared = Item::getShareArray(['body' => $body]);
3484 if (empty($reshared)) {
3488 // Skip if it isn't a pure repeated messages
3489 // Does it start with a share?
3490 if (!empty($reshared['comment']) && $complete) {
3494 if (!empty($reshared['guid']) && $complete) {
3495 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3496 $item = Item::selectFirst(['contact-id'], $condition);
3497 if (DBA::isResult($item)) {
3499 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3500 $ret["root_guid"] = $reshared['guid'];
3502 } elseif ($complete) {
3503 // We are resharing something that isn't a DFRN or Diaspora post.
3504 // So we have to return "false" on "$complete" to not trigger a reshare.
3507 } elseif (empty($reshared['guid']) && $complete) {
3513 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3514 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3515 if (!empty($contact['addr'])) {
3516 $ret['root_handle'] = $contact['addr'];
3520 if (empty($ret) && !$complete) {
3528 * Create an event array
3530 * @param integer $event_id The id of the event
3532 * @return array with event data
3533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3535 private static function buildEvent($event_id)
3537 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3538 if (!DBA::isResult($r)) {
3546 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3547 if (!DBA::isResult($r)) {
3553 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3554 if (!DBA::isResult($r)) {
3560 $eventdata['author'] = self::myHandle($owner);
3562 if ($event['guid']) {
3563 $eventdata['guid'] = $event['guid'];
3566 $mask = DateTimeFormat::ATOM;
3568 /// @todo - establish "all day" events in Friendica
3569 $eventdata["all_day"] = "false";
3571 $eventdata['timezone'] = 'UTC';
3572 if (!$event['adjust'] && $user['timezone']) {
3573 $eventdata['timezone'] = $user['timezone'];
3576 if ($event['start']) {
3577 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3579 if ($event['finish'] && !$event['nofinish']) {
3580 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3582 if ($event['summary']) {
3583 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3585 if ($event['desc']) {
3586 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3588 if ($event['location']) {
3589 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3590 $coord = Map::getCoordinates($event['location']);
3593 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3594 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3595 $location["lat"] = $coord['lat'];
3596 $location["lng"] = $coord['lon'];
3598 $location["lat"] = 0;
3599 $location["lng"] = 0;
3601 $eventdata['location'] = $location;
3608 * Create a post (status message or reshare)
3610 * @param array $item The item that will be exported
3611 * @param array $owner the array of the item owner
3614 * 'type' -> Message type ("status_message" or "reshare")
3615 * 'message' -> Array of XML elements of the status
3616 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3617 * @throws \ImagickException
3619 public static function buildStatus(array $item, array $owner)
3621 $cachekey = "diaspora:buildStatus:".$item['guid'];
3623 $result = DI::cache()->get($cachekey);
3624 if (!is_null($result)) {
3628 $myaddr = self::myHandle($owner);
3630 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3631 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3632 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3634 // Detect a share element and do a reshare
3635 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3636 $message = ["author" => $myaddr,
3637 "guid" => $item["guid"],
3638 "created_at" => $created,
3639 "root_author" => $ret["root_handle"],
3640 "root_guid" => $ret["root_guid"],
3641 "provider_display_name" => $item["app"],
3642 "public" => $public];
3646 $title = $item["title"];
3647 $body = $item["body"];
3649 // Fetch the title from an attached link - if there is one
3650 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3651 $page_data = BBCode::getAttachmentData($item['body']);
3652 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3653 $title = $page_data['title'];
3657 if ($item['author-link'] != $item['owner-link']) {
3658 require_once 'mod/share.php';
3659 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3660 $item['plink'], $item['created']) . $body . '[/share]';
3663 // convert to markdown
3664 $body = html_entity_decode(BBCode::toMarkdown($body));
3667 if (strlen($title)) {
3668 $body = "### ".html_entity_decode($title)."\n\n".$body;
3671 if ($item["attach"]) {
3672 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3674 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3675 foreach ($matches as $mtch) {
3676 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3683 if ($item["location"] != "")
3684 $location["address"] = $item["location"];
3686 if ($item["coord"] != "") {
3687 $coord = explode(" ", $item["coord"]);
3688 $location["lat"] = $coord[0];
3689 $location["lng"] = $coord[1];
3692 $message = ["author" => $myaddr,
3693 "guid" => $item["guid"],
3694 "created_at" => $created,
3695 "edited_at" => $edited,
3696 "public" => $public,
3698 "provider_display_name" => $item["app"],
3699 "location" => $location];
3701 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3702 if (!isset($location["lat"]) || !isset($location["lng"])) {
3703 unset($message["location"]);
3706 if ($item['event-id'] > 0) {
3707 $event = self::buildEvent($item['event-id']);
3708 if (count($event)) {
3709 $message['event'] = $event;
3711 if (!empty($event['location']['address']) &&
3712 !empty($event['location']['lat']) &&
3713 !empty($event['location']['lng'])) {
3714 $message['location'] = $event['location'];
3717 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3718 // $message['text'] = '';
3722 $type = "status_message";
3725 $msg = ["type" => $type, "message" => $message];
3727 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3732 private static function prependParentAuthorMention($body, $profile_url)
3734 $profile = Contact::getByURL($profile_url, false, ['addr', 'name', 'contact-type']);
3735 if (!empty($profile['addr'])
3736 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3737 && !strstr($body, $profile['addr'])
3738 && !strstr($body, $profile_url)
3740 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3749 * @param array $item The item that will be exported
3750 * @param array $owner the array of the item owner
3751 * @param array $contact Target of the communication
3752 * @param bool $public_batch Is it a public post?
3754 * @return int The result of the transmission
3755 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3756 * @throws \ImagickException
3758 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3760 $status = self::buildStatus($item, $owner);
3762 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3766 * Creates a "like" object
3768 * @param array $item The item that will be exported
3769 * @param array $owner the array of the item owner
3771 * @return array The data for a "like"
3772 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3774 private static function constructLike(array $item, array $owner)
3776 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3777 if (!DBA::isResult($parent)) {
3781 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3783 if ($item['verb'] === Activity::LIKE) {
3785 } elseif ($item['verb'] === Activity::DISLIKE) {
3786 $positive = "false";
3789 return(["author" => self::myHandle($owner),
3790 "guid" => $item["guid"],
3791 "parent_guid" => $parent["guid"],
3792 "parent_type" => $target_type,
3793 "positive" => $positive,
3794 "author_signature" => ""]);
3798 * Creates an "EventParticipation" object
3800 * @param array $item The item that will be exported
3801 * @param array $owner the array of the item owner
3803 * @return array The data for an "EventParticipation"
3804 * @throws \Exception
3806 private static function constructAttend(array $item, array $owner)
3808 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3809 if (!DBA::isResult($parent)) {
3813 switch ($item['verb']) {
3814 case Activity::ATTEND:
3815 $attend_answer = 'accepted';
3817 case Activity::ATTENDNO:
3818 $attend_answer = 'declined';
3820 case Activity::ATTENDMAYBE:
3821 $attend_answer = 'tentative';
3824 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3828 return(["author" => self::myHandle($owner),
3829 "guid" => $item["guid"],
3830 "parent_guid" => $parent["guid"],
3831 "status" => $attend_answer,
3832 "author_signature" => ""]);
3836 * Creates the object for a comment
3838 * @param array $item The item that will be exported
3839 * @param array $owner the array of the item owner
3841 * @return array|false The data for a comment
3842 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3844 private static function constructComment(array $item, array $owner)
3846 $cachekey = "diaspora:constructComment:".$item['guid'];
3848 $result = DI::cache()->get($cachekey);
3849 if (!is_null($result)) {
3853 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3854 if (!DBA::isResult($toplevel_item)) {
3855 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3859 $thread_parent_item = $toplevel_item;
3860 if ($item['thr-parent'] != $item['parent-uri']) {
3861 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3864 $body = $item["body"];
3866 // The replied to autor mention is prepended for clarity if:
3867 // - Item replied isn't yours
3868 // - Item is public or explicit mentions are disabled
3869 // - Implicit mentions are enabled
3871 $item['author-id'] != $thread_parent_item['author-id']
3872 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3873 && !DI::config()->get('system', 'disable_implicit_mentions')
3875 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3878 $text = html_entity_decode(BBCode::toMarkdown($body));
3879 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3880 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3883 "author" => self::myHandle($owner),
3884 "guid" => $item["guid"],
3885 "created_at" => $created,
3886 "edited_at" => $edited,
3887 "parent_guid" => $toplevel_item["guid"],
3889 "author_signature" => ""
3892 // Send the thread parent guid only if it is a threaded comment
3893 if ($item['thr-parent'] != $item['parent-uri']) {
3894 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3897 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3903 * Send a like or a comment
3905 * @param array $item The item that will be exported
3906 * @param array $owner the array of the item owner
3907 * @param array $contact Target of the communication
3908 * @param bool $public_batch Is it a public post?
3910 * @return int The result of the transmission
3911 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3912 * @throws \ImagickException
3914 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3916 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3917 $message = self::constructAttend($item, $owner);
3918 $type = "event_participation";
3919 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3920 $message = self::constructLike($item, $owner);
3922 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3923 $message = self::constructComment($item, $owner);
3927 if (empty($message)) {
3931 $message["author_signature"] = self::signature($owner, $message);
3933 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3937 * Creates a message from a signature record entry
3939 * @param array $item The item that will be exported
3940 * @return array The message
3942 private static function messageFromSignature(array $item)
3944 // Split the signed text
3945 $signed_parts = explode(";", $item['signed_text']);
3947 if ($item["deleted"]) {
3948 $message = ["author" => $item['signer'],
3949 "target_guid" => $signed_parts[0],
3950 "target_type" => $signed_parts[1]];
3951 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3952 $message = ["author" => $signed_parts[4],
3953 "guid" => $signed_parts[1],
3954 "parent_guid" => $signed_parts[3],
3955 "parent_type" => $signed_parts[2],
3956 "positive" => $signed_parts[0],
3957 "author_signature" => $item['signature'],
3958 "parent_author_signature" => ""];
3960 // Remove the comment guid
3961 $guid = array_shift($signed_parts);
3963 // Remove the parent guid
3964 $parent_guid = array_shift($signed_parts);
3966 // Remove the handle
3967 $handle = array_pop($signed_parts);
3970 "author" => $handle,
3972 "parent_guid" => $parent_guid,
3973 "text" => implode(";", $signed_parts),
3974 "author_signature" => $item['signature'],
3975 "parent_author_signature" => ""
3982 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3984 * @param array $item The item that will be exported
3985 * @param array $owner the array of the item owner
3986 * @param array $contact Target of the communication
3987 * @param bool $public_batch Is it a public post?
3989 * @return int The result of the transmission
3990 * @throws \Exception
3992 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3994 if ($item["deleted"]) {
3995 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3996 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4002 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
4004 $msg = json_decode($item['signed_text'], true);
4007 if (is_array($msg)) {
4008 foreach ($msg as $field => $data) {
4009 if (!$item["deleted"]) {
4010 if ($field == "diaspora_handle") {
4013 if ($field == "target_type") {
4014 $field = "parent_type";
4018 $message[$field] = $data;
4021 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4024 $message["parent_author_signature"] = self::signature($owner, $message);
4026 Logger::info('Relayed data', ['msg' => $message]);
4028 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4032 * Sends a retraction (deletion) of a message, like or comment
4034 * @param array $item The item that will be exported
4035 * @param array $owner the array of the item owner
4036 * @param array $contact Target of the communication
4037 * @param bool $public_batch Is it a public post?
4038 * @param bool $relay Is the retraction transmitted from a relay?
4040 * @return int The result of the transmission
4041 * @throws \Exception
4043 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4045 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4047 $msg_type = "retraction";
4049 if ($item['gravity'] == GRAVITY_PARENT) {
4050 $target_type = "Post";
4051 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4052 $target_type = "Like";
4054 $target_type = "Comment";
4057 $message = ["author" => $itemaddr,
4058 "target_guid" => $item['guid'],
4059 "target_type" => $target_type];
4061 Logger::info('Got message', ['msg' => $message]);
4063 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4069 * @param array $item The item that will be exported
4070 * @param array $owner The owner
4071 * @param array $contact Target of the communication
4073 * @return int The result of the transmission
4074 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4075 * @throws \ImagickException
4077 public static function sendMail(array $item, array $owner, array $contact)
4079 $myaddr = self::myHandle($owner);
4081 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4082 if (!DBA::isResult($cnv)) {
4083 Logger::log("conversation not found.");
4087 $body = BBCode::toMarkdown($item["body"]);
4088 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4091 "author" => $myaddr,
4092 "guid" => $item["guid"],
4093 "conversation_guid" => $cnv["guid"],
4095 "created_at" => $created,
4098 if ($item["reply"]) {
4103 "author" => $cnv["creator"],
4104 "guid" => $cnv["guid"],
4105 "subject" => $cnv["subject"],
4106 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4107 "participants" => $cnv["recips"],
4111 $type = "conversation";
4114 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4118 * Split a name into first name and last name
4120 * @param string $name The name
4122 * @return array The array with "first" and "last"
4124 public static function splitName($name) {
4125 $name = trim($name);
4127 // Is the name longer than 64 characters? Then cut the rest of it.
4128 if (strlen($name) > 64) {
4129 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4130 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4132 $name = substr($name, 0, 64);
4136 // Take the first word as first name
4137 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4138 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4139 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4140 return ['first' => $first, 'last' => $last];
4143 // Take the last word as last name
4144 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4145 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4147 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4148 return ['first' => $first, 'last' => $last];
4151 // Take the first 32 characters if there is no space in the first 32 characters
4152 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4153 $first = substr($name, 0, 32);
4154 $last = substr($name, 32);
4155 return ['first' => $first, 'last' => $last];
4158 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4159 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4161 // Check if the last name is longer than 32 characters
4162 if (strlen($last) > 32) {
4163 if (strpos($last, ' ') <= 32) {
4164 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4166 $last = substr($last, 0, 32);
4170 return ['first' => $first, 'last' => $last];
4174 * Create profile data
4176 * @param int $uid The user id
4178 * @return array The profile data
4179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4181 private static function createProfileData($uid)
4183 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4184 if (!DBA::isResult($profile)) {
4188 $handle = $profile["addr"];
4190 $split_name = self::splitName($profile['name']);
4191 $first = $split_name['first'];
4192 $last = $split_name['last'];
4194 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4195 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4196 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4197 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4203 if ($searchable === 'true') {
4206 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4207 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4211 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4214 $about = BBCode::toMarkdown($profile['about']);
4216 $location = $profile['location'];
4218 if ($profile['pub_keywords']) {
4219 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4220 $kw = str_replace(' ', ' ', $kw);
4221 $arr = explode(' ', $kw);
4223 for ($x = 0; $x < 5; $x ++) {
4224 if (!empty($arr[$x])) {
4225 $tags .= '#'. trim($arr[$x]) .' ';
4230 $tags = trim($tags);
4233 return ["author" => $handle,
4234 "first_name" => $first,
4235 "last_name" => $last,
4236 "image_url" => $large,
4237 "image_url_medium" => $medium,
4238 "image_url_small" => $small,
4241 "location" => $location,
4242 "searchable" => $searchable,
4244 "tag_string" => $tags];
4248 * Sends profile data
4250 * @param int $uid The user id
4251 * @param bool $recips optional, default false
4253 * @throws \Exception
4255 public static function sendProfile($uid, $recips = false)
4261 $owner = User::getOwnerDataById($uid);
4268 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4269 AND `uid` = %d AND `rel` != %d",
4270 DBA::escape(Protocol::DIASPORA),
4272 intval(Contact::SHARING)
4280 $message = self::createProfileData($uid);
4282 // @ToDo Split this into single worker jobs
4283 foreach ($recips as $recip) {
4284 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4285 self::buildAndTransmit($owner, $recip, "profile", $message);
4290 * Creates the signature for likes that are created on our system
4292 * @param integer $uid The user of that comment
4293 * @param array $item Item array
4295 * @return array Signed content
4296 * @throws \Exception
4298 public static function createLikeSignature($uid, array $item)
4300 $owner = User::getOwnerDataById($uid);
4301 if (empty($owner)) {
4302 Logger::info('No owner post, so not storing signature');
4306 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4310 $message = self::constructLike($item, $owner);
4311 if ($message === false) {
4315 $message["author_signature"] = self::signature($owner, $message);
4321 * Creates the signature for Comments 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 createCommentSignature($uid, array $item)
4331 $owner = User::getOwnerDataById($uid);
4332 if (empty($owner)) {
4333 Logger::info('No owner post, so not storing signature');
4337 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4338 $item['thr-parent'] = $item['parent-uri'];
4340 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4341 if (!DBA::isResult($parent)) {
4345 $item['parent-uri'] = $parent['parent-uri'];
4347 $message = self::constructComment($item, $owner);
4348 if ($message === false) {
4352 $message["author_signature"] = self::signature($owner, $message);