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\FContact;
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\Probe;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Map;
48 use Friendica\Util\Network;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
51 use Friendica\Worker\Delivery;
55 * This class contain functions to create and send Diaspora XML files
60 * Mark the relay contact of the given contact for archival
61 * This is called whenever there is a communication issue with the server.
62 * It avoids sending stuff to servers who don't exist anymore.
63 * The relay contact is a technical contact entry that exists once per server.
65 * @param array $contact of the relay contact
67 public static function markRelayForArchival(array $contact)
69 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
70 // This is already the relay contact, we don't need to fetch it
71 $relay_contact = $contact;
72 } elseif (empty($contact['baseurl'])) {
73 if (!empty($contact['batch'])) {
74 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
75 $relay_contact = DBA::selectFirst('contact', [], $condition);
80 $relay_contact = self::getRelayContact($contact['baseurl'], []);
83 if (!empty($relay_contact)) {
84 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
85 Contact::markForArchival($relay_contact);
90 * Return a list of relay servers
92 * The list contains not only the official relays but also servers that we serve directly
94 * @param integer $item_id The id of the item that is sent
95 * @param array $contacts The previously fetched contacts
97 * @return array of relay servers
98 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
100 public static function relayList($item_id, array $contacts = [])
104 // Fetching relay servers
105 $serverdata = DI::config()->get("system", "relay_server");
107 if (!empty($serverdata)) {
108 $servers = explode(",", $serverdata);
109 foreach ($servers as $server) {
110 $serverlist[$server] = trim($server);
114 if (DI::config()->get("system", "relay_directly", false)) {
115 // We distribute our stuff based on the parent to ensure that the thread will be complete
116 $parent = Item::selectFirst(['uri-id'], ['id' => $item_id]);
117 if (!DBA::isResult($parent)) {
121 // Servers that want to get all content
122 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
123 while ($server = DBA::fetch($servers)) {
124 $serverlist[$server['url']] = $server['url'];
126 DBA::close($servers);
128 // All tags of the current post
129 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
131 while ($tag = DBA::fetch($tags)) {
132 $taglist[] = $tag['name'];
136 // All servers who wants content with this tag
138 if (!empty($taglist)) {
139 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
140 while ($server = DBA::fetch($tagserver)) {
141 $tagserverlist[] = $server['gserver-id'];
143 DBA::close($tagserver);
146 // All adresses with the given id
147 if (!empty($tagserverlist)) {
148 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
149 while ($server = DBA::fetch($servers)) {
150 $serverlist[$server['url']] = $server['url'];
152 DBA::close($servers);
156 // Now we are collecting all relay contacts
157 foreach ($serverlist as $server_url) {
158 // We don't send messages to ourselves
159 if (Strings::compareLink($server_url, DI::baseUrl())) {
162 $contact = self::getRelayContact($server_url);
163 if (is_bool($contact)) {
168 foreach ($contacts as $entry) {
169 if ($entry['batch'] == $contact['batch']) {
175 $contacts[] = $contact;
183 * Return a contact for a given server address or creates a dummy entry
185 * @param string $server_url The url of the server
186 * @param array $fields Fieldlist
187 * @return array with the contact
190 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
192 // Fetch the relay contact
193 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
194 'contact-type' => Contact::TYPE_RELAY];
195 $contact = DBA::selectFirst('contact', $fields, $condition);
197 if (DBA::isResult($contact)) {
198 if ($contact['archive'] || $contact['blocked']) {
203 self::setRelayContact($server_url);
205 $contact = DBA::selectFirst('contact', $fields, $condition);
206 if (DBA::isResult($contact)) {
211 // It should never happen that we arrive here
216 * Update or insert a relay contact
218 * @param string $server_url The url of the server
219 * @param array $network_fields Optional network specific fields
222 public static function setRelayContact($server_url, array $network_fields = [])
224 $fields = ['created' => DateTimeFormat::utcNow(),
225 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
226 'nurl' => Strings::normaliseLink($server_url),
227 'network' => Protocol::DIASPORA, 'uid' => 0,
228 'batch' => $server_url . '/receive/public',
229 'rel' => Contact::FOLLOWER, 'blocked' => false,
230 'pending' => false, 'writable' => true,
231 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
233 $fields = array_merge($fields, $network_fields);
235 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
236 $old = DBA::selectFirst('contact', [], $condition);
237 if (DBA::isResult($old)) {
238 unset($fields['created']);
239 $condition = ['id' => $old['id']];
241 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
242 DBA::update('contact', $fields, $condition, $old);
244 Logger::info('Create relay contact', ['fields' => $fields]);
245 Contact::insert($fields);
250 * Return a list of participating contacts for a thread
252 * This is used for the participation feature.
253 * One of the parameters is a contact array.
254 * This is done to avoid duplicates.
256 * @param array $item Item that is about to be delivered
257 * @param array $contacts The previously fetched contacts
259 * @return array of relay servers
262 public static function participantsForThread(array $item, array $contacts)
264 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
265 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
269 $items = Item::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
270 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
271 while ($item = DBA::fetch($items)) {
272 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
273 ['id' => $item['author-id']]);
274 if (!DBA::isResult($contact) || empty($contact['batch']) ||
275 ($contact['network'] != Protocol::DIASPORA) ||
276 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
281 foreach ($contacts as $entry) {
282 if ($entry['batch'] == $contact['batch']) {
288 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
289 $contacts[] = $contact;
298 * verify the envelope and return the verified data
300 * @param string $envelope The magic envelope
302 * @return string verified data
303 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
304 * @throws \ImagickException
306 private static function verifyMagicEnvelope($envelope)
308 $basedom = XML::parseString($envelope, true);
310 if (!is_object($basedom)) {
311 Logger::log("Envelope is no XML file");
315 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
317 if (sizeof($children) == 0) {
318 Logger::log("XML has no children");
324 $data = Strings::base64UrlDecode($children->data);
325 $type = $children->data->attributes()->type[0];
327 $encoding = $children->encoding;
329 $alg = $children->alg;
331 $sig = Strings::base64UrlDecode($children->sig);
332 $key_id = $children->sig->attributes()->key_id[0];
334 $handle = Strings::base64UrlDecode($key_id);
337 $b64url_data = Strings::base64UrlEncode($data);
338 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
340 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
343 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
347 $key = self::key($handle);
349 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
353 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
355 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
363 * encrypts data via AES
365 * @param string $key The AES key
366 * @param string $iv The IV (is used for CBC encoding)
367 * @param string $data The data that is to be encrypted
369 * @return string encrypted data
371 private static function aesEncrypt($key, $iv, $data)
373 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
377 * decrypts data via AES
379 * @param string $key The AES key
380 * @param string $iv The IV (is used for CBC encoding)
381 * @param string $encrypted The encrypted data
383 * @return string decrypted data
385 private static function aesDecrypt($key, $iv, $encrypted)
387 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
391 * Decodes incoming Diaspora message in the new format
393 * @param string $raw raw post message
394 * @param string $privKey The private key of the importer
395 * @param boolean $no_exit Don't do an http exit on error
398 * 'message' -> decoded Diaspora XML message
399 * 'author' -> author diaspora handle
400 * 'key' -> author public key (converted to pkcs#8)
401 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
402 * @throws \ImagickException
404 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
406 $data = json_decode($raw);
408 // Is it a private post? Then decrypt the outer Salmon
409 if (is_object($data)) {
410 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
411 $ciphertext = base64_decode($data->encrypted_magic_envelope);
413 $outer_key_bundle = '';
414 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
415 $j_outer_key_bundle = json_decode($outer_key_bundle);
417 if (!is_object($j_outer_key_bundle)) {
418 Logger::log('Outer Salmon did not verify. Discarding.');
422 throw new \Friendica\Network\HTTPException\BadRequestException();
426 $outer_iv = base64_decode($j_outer_key_bundle->iv);
427 $outer_key = base64_decode($j_outer_key_bundle->key);
429 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
434 $basedom = XML::parseString($xml, true);
436 if (!is_object($basedom)) {
437 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
441 throw new \Friendica\Network\HTTPException\BadRequestException();
445 $base = $basedom->children(ActivityNamespace::SALMON_ME);
447 // Not sure if this cleaning is needed
448 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
450 // Build the signed data
451 $type = $base->data[0]->attributes()->type[0];
452 $encoding = $base->encoding;
454 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
456 // This is the signature
457 $signature = Strings::base64UrlDecode($base->sig);
459 // Get the senders' public key
460 $key_id = $base->sig[0]->attributes()->key_id[0];
461 $author_addr = base64_decode($key_id);
462 if ($author_addr == '') {
463 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
467 throw new \Friendica\Network\HTTPException\BadRequestException();
471 $key = self::key($author_addr);
473 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
477 throw new \Friendica\Network\HTTPException\BadRequestException();
481 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
483 Logger::log('Message did not verify. Discarding.');
487 throw new \Friendica\Network\HTTPException\BadRequestException();
491 return ['message' => (string)Strings::base64UrlDecode($base->data),
492 'author' => XML::unescape($author_addr),
493 'key' => (string)$key];
497 * Decodes incoming Diaspora message in the deprecated format
499 * @param string $xml urldecoded Diaspora salmon
500 * @param string $privKey The private key of the importer
503 * 'message' -> decoded Diaspora XML message
504 * 'author' -> author diaspora handle
505 * 'key' -> author public key (converted to pkcs#8)
506 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
507 * @throws \ImagickException
509 public static function decode(string $xml, string $privKey = '')
512 $basedom = XML::parseString($xml);
514 if (!is_object($basedom)) {
515 Logger::notice('XML is not parseable.');
518 $children = $basedom->children('https://joindiaspora.com/protocol');
520 $inner_aes_key = null;
523 if ($children->header) {
525 $author_link = str_replace('acct:', '', $children->header->author_id);
527 // This happens with posts from a relais
528 if (empty($privKey)) {
529 Logger::info('This is no private post in the old format');
533 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
535 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
536 $ciphertext = base64_decode($encrypted_header->ciphertext);
538 $outer_key_bundle = '';
539 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
541 $j_outer_key_bundle = json_decode($outer_key_bundle);
543 $outer_iv = base64_decode($j_outer_key_bundle->iv);
544 $outer_key = base64_decode($j_outer_key_bundle->key);
546 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
548 Logger::info('decrypted', ['data' => $decrypted]);
549 $idom = XML::parseString($decrypted);
551 $inner_iv = base64_decode($idom->iv);
552 $inner_aes_key = base64_decode($idom->aes_key);
554 $author_link = str_replace('acct:', '', $idom->author_id);
557 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
559 // figure out where in the DOM tree our data is hiding
562 if ($dom->provenance->data) {
563 $base = $dom->provenance;
564 } elseif ($dom->env->data) {
566 } elseif ($dom->data) {
571 Logger::log('unable to locate salmon data in xml');
572 throw new \Friendica\Network\HTTPException\BadRequestException();
576 // Stash the signature away for now. We have to find their key or it won't be good for anything.
577 $signature = Strings::base64UrlDecode($base->sig);
581 // strip whitespace so our data element will return to one big base64 blob
582 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
585 // stash away some other stuff for later
587 $type = $base->data[0]->attributes()->type[0];
588 $keyhash = $base->sig[0]->attributes()->keyhash[0];
589 $encoding = $base->encoding;
593 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
597 $data = Strings::base64UrlDecode($data);
601 $inner_decrypted = $data;
603 // Decode the encrypted blob
604 $inner_encrypted = base64_decode($data);
605 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
609 Logger::log('Could not retrieve author URI.');
610 throw new \Friendica\Network\HTTPException\BadRequestException();
612 // Once we have the author URI, go to the web and try to find their public key
613 // (first this will look it up locally if it is in the fcontact cache)
614 // This will also convert diaspora public key from pkcs#1 to pkcs#8
616 Logger::log('Fetching key for '.$author_link);
617 $key = self::key($author_link);
620 Logger::log('Could not retrieve author key.');
621 throw new \Friendica\Network\HTTPException\BadRequestException();
624 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
627 Logger::log('Message did not verify. Discarding.');
628 throw new \Friendica\Network\HTTPException\BadRequestException();
631 Logger::log('Message verified.');
633 return ['message' => (string)$inner_decrypted,
634 'author' => XML::unescape($author_link),
635 'key' => (string)$key];
640 * Dispatches public messages and find the fitting receivers
642 * @param array $msg The post that will be dispatched
643 * @param bool $fetched The message had been fetched (default "false")
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, bool $fetched = false)
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, $fetched);
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
674 * @param bool $fetched The message had been fetched (default "false")
676 * @return int The message id of the generated message, "true" or "false" if there was an error
677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
678 * @throws \ImagickException
680 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null, bool $fetched = false)
682 // The sender is the handle of the contact that sent the message.
683 // This will often be different with relayed messages (for example "like" and "comment")
684 $sender = $msg["author"];
686 // This is only needed for private postings since this is already done for public ones before
687 if (is_null($fields)) {
689 if (!($fields = self::validPosting($msg))) {
690 Logger::log("Invalid posting");
697 $type = $fields->getName();
699 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]);
702 case "account_migration":
704 Logger::log('Message with type ' . $type . ' is not private, quitting.');
707 return self::receiveAccountMigration($importer, $fields);
709 case "account_deletion":
710 return self::receiveAccountDeletion($fields);
713 return self::receiveComment($importer, $sender, $fields, $msg["message"], $fetched);
717 Logger::log('Message with type ' . $type . ' is not private, quitting.');
720 return self::receiveContactRequest($importer, $fields);
724 Logger::log('Message with type ' . $type . ' is not private, quitting.');
727 return self::receiveConversation($importer, $msg, $fields);
730 return self::receiveLike($importer, $sender, $fields);
734 Logger::log('Message with type ' . $type . ' is not private, quitting.');
737 return self::receiveMessage($importer, $fields);
739 case "participation":
741 Logger::log('Message with type ' . $type . ' is not private, quitting.');
744 return self::receiveParticipation($importer, $fields);
746 case "photo": // Not implemented
747 return self::receivePhoto($importer, $fields);
749 case "poll_participation": // Not implemented
750 return self::receivePollParticipation($importer, $fields);
754 Logger::log('Message with type ' . $type . ' is not private, quitting.');
757 return self::receiveProfile($importer, $fields);
760 return self::receiveReshare($importer, $fields, $msg["message"]);
763 return self::receiveRetraction($importer, $sender, $fields);
765 case "status_message":
766 return self::receiveStatusMessage($importer, $fields, $msg["message"], $fetched);
769 Logger::log("Unknown message type ".$type);
775 * Checks if a posting is valid and fetches the data fields.
777 * This function does not only check the signature.
778 * It also does the conversion between the old and the new diaspora format.
780 * @param array $msg Array with the XML, the sender handle and the sender signature
782 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
783 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
784 * @throws \ImagickException
786 private static function validPosting($msg)
788 $data = XML::parseString($msg["message"]);
790 if (!is_object($data)) {
791 Logger::info('No valid XML', ['message' => $msg['message']]);
795 // Is this the new or the old version?
796 if ($data->getName() == "XML") {
798 foreach ($data->post->children() as $child) {
806 $type = $element->getName();
809 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
811 // All retractions are handled identically from now on.
812 // In the new version there will only be "retraction".
813 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
814 $type = "retraction";
816 if ($type == "request") {
820 $fields = new SimpleXMLElement("<".$type."/>");
823 $author_signature = null;
824 $parent_author_signature = null;
826 foreach ($element->children() as $fieldname => $entry) {
828 // Translation for the old XML structure
829 if ($fieldname == "diaspora_handle") {
830 $fieldname = "author";
832 if ($fieldname == "participant_handles") {
833 $fieldname = "participants";
835 if (in_array($type, ["like", "participation"])) {
836 if ($fieldname == "target_type") {
837 $fieldname = "parent_type";
840 if ($fieldname == "sender_handle") {
841 $fieldname = "author";
843 if ($fieldname == "recipient_handle") {
844 $fieldname = "recipient";
846 if ($fieldname == "root_diaspora_id") {
847 $fieldname = "root_author";
849 if ($type == "status_message") {
850 if ($fieldname == "raw_message") {
854 if ($type == "retraction") {
855 if ($fieldname == "post_guid") {
856 $fieldname = "target_guid";
858 if ($fieldname == "type") {
859 $fieldname = "target_type";
864 if (($fieldname == "author_signature") && ($entry != "")) {
865 $author_signature = base64_decode($entry);
866 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
867 $parent_author_signature = base64_decode($entry);
868 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
869 if ($signed_data != "") {
873 $signed_data .= $entry;
875 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
876 || ($orig_type == "relayable_retraction")
878 XML::copy($entry, $fields, $fieldname);
882 // This is something that shouldn't happen at all.
883 if (in_array($type, ["status_message", "reshare", "profile"])) {
884 if ($msg["author"] != $fields->author) {
885 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
890 // Only some message types have signatures. So we quit here for the other types.
891 if (!in_array($type, ["comment", "like"])) {
894 // No author_signature? This is a must, so we quit.
895 if (!isset($author_signature)) {
896 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
900 if (isset($parent_author_signature)) {
901 $key = self::key($msg["author"]);
903 Logger::info('No key found for parent', ['author' => $msg["author"]]);
907 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
908 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);
913 $key = self::key($fields->author);
915 Logger::info('No key found', ['author' => $fields->author]);
919 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
920 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);
928 * Fetches the public key for a given handle
930 * @param string $handle The handle
932 * @return string The public key
933 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
934 * @throws \ImagickException
936 private static function key($handle)
938 $handle = strval($handle);
940 Logger::log("Fetching diaspora key for: ".$handle);
942 $r = FContact::getByURL($handle);
951 * get a handle (user@domain.tld) from a given contact id
953 * @param int $contact_id The id in the contact table
954 * @param int $pcontact_id The id in the contact table (Used for the public contact)
956 * @return string the handle
959 private static function handleFromContact($contact_id, $pcontact_id = 0)
963 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
965 if ($pcontact_id != 0) {
966 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
968 if (DBA::isResult($contact) && !empty($contact["addr"])) {
969 return strtolower($contact["addr"]);
974 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
978 if (DBA::isResult($r)) {
981 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
983 if ($contact['addr'] != "") {
984 $handle = $contact['addr'];
986 $baseurl_start = strpos($contact['url'], '://') + 3;
987 // allows installations in a subdirectory--not sure how Diaspora will handle
988 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
989 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
990 $handle = $contact['nick'].'@'.$baseurl;
994 return strtolower($handle);
998 * Get a contact id for a given handle
1000 * @todo Move to Friendica\Model\Contact
1002 * @param int $uid The user id
1003 * @param string $handle The handle in the format user@domain.tld
1005 * @return array Contact data
1006 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1007 * @throws \ImagickException
1009 private static function contactByHandle($uid, $handle)
1011 return Contact::getByURL($handle, null, [], $uid);
1015 * Checks if the given contact url does support ActivityPub
1017 * @param string $url profile url
1018 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1020 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1021 * @throws \ImagickException
1023 public static function isSupportedByContactUrl($url, $update = null)
1025 return !empty(FContact::getByURL($url, $update));
1029 * Check if posting is allowed for this contact
1031 * @param array $importer Array of the importer user
1032 * @param array $contact The contact that is checked
1033 * @param bool $is_comment Is the check for a comment?
1035 * @return bool is the contact allowed to post?
1037 private static function postAllow(array $importer, array $contact, $is_comment = false)
1040 * Perhaps we were already sharing with this person. Now they're sharing with us.
1041 * That makes us friends.
1042 * Normally this should have handled by getting a request - but this could get lost
1044 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1045 // It is not removed by now. Possibly the code is needed?
1046 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1049 // array('rel' => Contact::FRIEND, 'writable' => true),
1050 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1053 // $contact["rel"] = Contact::FRIEND;
1054 // Logger::log("defining user ".$contact["nick"]." as friend");
1057 // Contact server is blocked
1058 if (Network::isUrlBlocked($contact['url'])) {
1060 // We don't seem to like that person
1061 } elseif ($contact["blocked"]) {
1062 // Maybe blocked, don't accept.
1064 // We are following this person?
1065 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1066 // Yes, then it is fine.
1068 // Is it a post to a community?
1069 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1072 // Is the message a global user or a comment?
1073 } elseif (($importer["uid"] == 0) || $is_comment) {
1074 // Messages for the global users and comments are always accepted
1082 * Fetches the contact id for a handle and checks if posting is allowed
1084 * @param array $importer Array of the importer user
1085 * @param string $handle The checked handle in the format user@domain.tld
1086 * @param bool $is_comment Is the check for a comment?
1088 * @return array The contact data
1089 * @throws \Exception
1091 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1093 $contact = self::contactByHandle($importer["uid"], $handle);
1095 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1096 // If a contact isn't found, we accept it anyway if it is a comment
1097 if ($is_comment && ($importer["uid"] != 0)) {
1098 return self::contactByHandle(0, $handle);
1099 } elseif ($is_comment) {
1106 if (!self::postAllow($importer, $contact, $is_comment)) {
1107 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1114 * Does the message already exists on the system?
1116 * @param int $uid The user id
1117 * @param string $guid The guid of the message
1119 * @return int|bool message id if the message already was stored into the system - or false.
1120 * @throws \Exception
1122 private static function messageExists($uid, $guid)
1124 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1125 if (DBA::isResult($item)) {
1126 Logger::log("message ".$guid." already exists for user ".$uid);
1134 * Checks for links to posts in a message
1136 * @param array $item The item array
1139 private static function fetchGuid(array $item)
1141 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1142 preg_replace_callback(
1144 function ($match) use ($item) {
1145 self::fetchGuidSub($match, $item);
1150 preg_replace_callback(
1151 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1152 function ($match) use ($item) {
1153 self::fetchGuidSub($match, $item);
1160 * Checks for relative /people/* links in an item body to match local
1161 * contacts or prepends the remote host taken from the author link.
1163 * @param string $body The item body to replace links from
1164 * @param string $author_link The author link for missing local contact fallback
1166 * @return string the replaced string
1168 public static function replacePeopleGuid($body, $author_link)
1170 $return = preg_replace_callback(
1171 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1172 function ($match) use ($author_link) {
1174 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1175 // 1 => '0123456789abcdef'
1177 $handle = FContact::getUrlByGuid($match[1]);
1180 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1182 // No local match, restoring absolute remote URL from author scheme and host
1183 $author_url = parse_url($author_link);
1184 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1196 * sub function of "fetchGuid" which checks for links in messages
1198 * @param array $match array containing a link that has to be checked for a message link
1199 * @param array $item The item array
1201 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1202 * @throws \ImagickException
1204 private static function fetchGuidSub($match, $item)
1206 if (!self::storeByGuid($match[1], $item["author-link"])) {
1207 self::storeByGuid($match[1], $item["owner-link"]);
1212 * Fetches an item with a given guid from a given server
1214 * @param string $guid the message guid
1215 * @param string $server The server address
1216 * @param int $uid The user id of the user
1218 * @return int the message id of the stored message or false
1219 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1220 * @throws \ImagickException
1222 private static function storeByGuid($guid, $server, $uid = 0)
1224 $serverparts = parse_url($server);
1226 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1230 $server = $serverparts["scheme"]."://".$serverparts["host"];
1232 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1234 $msg = self::message($guid, $server);
1240 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1242 // Now call the dispatcher
1243 return self::dispatchPublic($msg, true);
1247 * Fetches a message from a server
1249 * @param string $guid message guid
1250 * @param string $server The url of the server
1251 * @param int $level Endless loop prevention
1254 * 'message' => The message XML
1255 * 'author' => The author handle
1256 * 'key' => The public key of the author
1257 * @throws \Exception
1259 private static function message($guid, $server, $level = 0)
1265 // This will work for new Diaspora servers and Friendica servers from 3.5
1266 $source_url = $server."/fetch/post/".urlencode($guid);
1268 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1270 $envelope = DI::httpRequest()->fetch($source_url);
1272 Logger::log("Envelope was fetched.", Logger::DEBUG);
1273 $x = self::verifyMagicEnvelope($envelope);
1275 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1277 Logger::log("Envelope was verified.", Logger::DEBUG);
1287 $source_xml = XML::parseString($x);
1289 if (!is_object($source_xml)) {
1293 if ($source_xml->post->reshare) {
1294 // Reshare of a reshare - old Diaspora version
1295 Logger::log("Message is a reshare", Logger::DEBUG);
1296 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1297 } elseif ($source_xml->getName() == "reshare") {
1298 // Reshare of a reshare - new Diaspora version
1299 Logger::log("Message is a new reshare", Logger::DEBUG);
1300 return self::message($source_xml->root_guid, $server, ++$level);
1305 // Fetch the author - for the old and the new Diaspora version
1306 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1307 $author = (string)$source_xml->post->status_message->diaspora_handle;
1308 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1309 $author = (string)$source_xml->author;
1312 // If this isn't a "status_message" then quit
1314 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1318 $msg = ["message" => $x, "author" => $author];
1320 $msg["key"] = self::key($msg["author"]);
1326 * Fetches an item with a given URL
1328 * @param string $url the message url
1330 * @return int the message id of the stored message or false
1331 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1332 * @throws \ImagickException
1334 public static function fetchByURL($url, $uid = 0)
1336 // Check for Diaspora (and Friendica) typical paths
1337 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1338 Logger::info('Invalid url', ['url' => $url]);
1342 $guid = urldecode($matches[2]);
1344 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1345 if (DBA::isResult($item)) {
1346 Logger::info('Found', ['id' => $item['id']]);
1350 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1351 $ret = self::storeByGuid($guid, $matches[1], $uid);
1352 Logger::info('Result', ['ret' => $ret]);
1354 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1355 if (DBA::isResult($item)) {
1356 Logger::info('Found', ['id' => $item['id']]);
1359 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1365 * Fetches the item record of a given guid
1367 * @param int $uid The user id
1368 * @param string $guid message guid
1369 * @param string $author The handle of the item
1370 * @param array $contact The contact of the item owner
1372 * @return array the item record
1373 * @throws \Exception
1375 private static function parentItem($uid, $guid, $author, array $contact)
1377 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1378 'author-name', 'author-link', 'author-avatar', 'gravity',
1379 'owner-name', 'owner-link', 'owner-avatar'];
1380 $condition = ['uid' => $uid, 'guid' => $guid];
1381 $item = Item::selectFirst($fields, $condition);
1383 if (!DBA::isResult($item)) {
1384 $person = FContact::getByURL($author);
1385 $result = self::storeByGuid($guid, $person["url"], $uid);
1387 // We don't have an url for items that arrived at the public dispatcher
1388 if (!$result && !empty($contact["url"])) {
1389 $result = self::storeByGuid($guid, $contact["url"], $uid);
1393 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1395 $item = Item::selectFirst($fields, $condition);
1399 if (!DBA::isResult($item)) {
1400 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1403 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1409 * returns contact details
1411 * @param array $def_contact The default contact if the person isn't found
1412 * @param array $person The record of the person
1413 * @param int $uid The user id
1416 * 'cid' => contact id
1417 * 'network' => network type
1418 * @throws \Exception
1420 private static function authorContactByUrl($def_contact, $person, $uid)
1422 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1423 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1424 if (DBA::isResult($contact)) {
1425 $cid = $contact["id"];
1426 $network = $contact["network"];
1428 $cid = $def_contact["id"];
1429 $network = Protocol::DIASPORA;
1432 return ["cid" => $cid, "network" => $network];
1436 * Is the profile a hubzilla profile?
1438 * @param string $url The profile link
1440 * @return bool is it a hubzilla server?
1442 private static function isHubzilla($url)
1444 return(strstr($url, '/channel/'));
1448 * Generate a post link with a given handle and message guid
1450 * @param string $addr The user handle
1451 * @param string $guid message guid
1452 * @param string $parent_guid optional parent guid
1454 * @return string the post link
1455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1456 * @throws \ImagickException
1458 private static function plink($addr, $guid, $parent_guid = '')
1460 $contact = Contact::getByURL($addr);
1461 if (empty($contact)) {
1462 Logger::info('No contact data for address', ['addr' => $addr]);
1466 if (empty($contact['baseurl'])) {
1467 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1468 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1472 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1473 if (!empty($gserver['platform'])) {
1474 $platform = strtolower($gserver['platform']);
1475 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1478 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1479 if (self::isHubzilla($contact['url'])) {
1480 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1481 $platform = 'hubzilla';
1482 } elseif ($contact['network'] == Protocol::DFRN) {
1483 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1484 $platform = 'friendica';
1488 if ($platform == 'friendica') {
1489 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1492 if ($platform == 'hubzilla') {
1493 return $contact['baseurl'] . '/item/' . $guid;
1496 if ($platform == 'socialhome') {
1497 return $contact['baseurl'] . '/content/' . $guid;
1500 if ($platform != 'diaspora') {
1501 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1505 if ($parent_guid != '') {
1506 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1508 return $contact['baseurl'] . '/posts/' . $guid;
1513 * Receives account migration
1515 * @param array $importer Array of the importer user
1516 * @param object $data The message object
1518 * @return bool Success
1519 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1520 * @throws \ImagickException
1522 private static function receiveAccountMigration(array $importer, $data)
1524 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1525 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1526 $signature = Strings::escapeTags(XML::unescape($data->signature));
1528 $contact = self::contactByHandle($importer["uid"], $old_handle);
1530 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1534 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1537 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1538 $key = self::key($old_handle);
1539 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1540 Logger::log('No valid signature for migration.');
1544 // Update the profile
1545 self::receiveProfile($importer, $data->profile);
1547 // change the technical stuff in contact
1548 $data = Probe::uri($new_handle);
1549 if ($data['network'] == Protocol::PHANTOM) {
1550 Logger::log('Account for '.$new_handle." couldn't be probed.");
1554 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1555 'name' => $data['name'], 'nick' => $data['nick'],
1556 'addr' => $data['addr'], 'batch' => $data['batch'],
1557 'notify' => $data['notify'], 'poll' => $data['poll'],
1558 'network' => $data['network']];
1560 DBA::update('contact', $fields, ['addr' => $old_handle]);
1562 Logger::log('Contacts are updated.');
1568 * Processes an account deletion
1570 * @param object $data The message object
1572 * @return bool Success
1573 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1575 private static function receiveAccountDeletion($data)
1577 $author = Strings::escapeTags(XML::unescape($data->author));
1579 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1580 while ($contact = DBA::fetch($contacts)) {
1581 Contact::remove($contact["id"]);
1583 DBA::close($contacts);
1585 Logger::log('Removed contacts for ' . $author);
1591 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1593 * @param string $author Author handle
1594 * @param string $guid Message guid
1595 * @param boolean $onlyfound Only return uri when found in the database
1597 * @return string The constructed uri or the one from our database
1598 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1599 * @throws \ImagickException
1601 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1603 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1604 if (DBA::isResult($item)) {
1605 return $item["uri"];
1606 } elseif (!$onlyfound) {
1607 $person = FContact::getByURL($author);
1609 $parts = parse_url($person['url']);
1610 unset($parts['path']);
1611 $host_url = Network::unparseURL($parts);
1613 return $host_url . '/objects/' . $guid;
1620 * Fetch the guid from our database with a given uri
1622 * @param string $uri Message uri
1623 * @param string $uid Author handle
1625 * @return string The post guid
1626 * @throws \Exception
1628 private static function getGuidFromUri($uri, $uid)
1630 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1631 if (DBA::isResult($item)) {
1632 return $item["guid"];
1639 * Store the mentions in the tag table
1641 * @param integer $uriid
1642 * @param string $text
1644 private static function storeMentions(int $uriid, string $text)
1646 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1647 if (empty($matches)) {
1652 * Matching values for the preg match
1653 * [1] = mention type (@ or !)
1654 * [2] = name (optional)
1658 foreach ($matches as $match) {
1659 if (empty($match)) {
1663 $person = FContact::getByURL($match[3]);
1664 if (empty($person)) {
1668 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1673 * Processes an incoming comment
1675 * @param array $importer Array of the importer user
1676 * @param string $sender The sender of the message
1677 * @param object $data The message object
1678 * @param string $xml The original XML of the message
1679 * @param bool $fetched The message had been fetched and not pushed
1681 * @return int The message id of the generated comment or "false" if there was an error
1682 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1683 * @throws \ImagickException
1685 private static function receiveComment(array $importer, $sender, $data, $xml, bool $fetched)
1687 $author = Strings::escapeTags(XML::unescape($data->author));
1688 $guid = Strings::escapeTags(XML::unescape($data->guid));
1689 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1690 $text = XML::unescape($data->text);
1692 if (isset($data->created_at)) {
1693 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1695 $created_at = DateTimeFormat::utcNow();
1698 if (isset($data->thread_parent_guid)) {
1699 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1700 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1705 $contact = self::allowedContactByHandle($importer, $sender, true);
1710 $message_id = self::messageExists($importer["uid"], $guid);
1715 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1716 if (!$parent_item) {
1720 $person = FContact::getByURL($author);
1721 if (!is_array($person)) {
1722 Logger::log("unable to find author details");
1726 // Fetch the contact id - if we know this contact
1727 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1731 $datarray["uid"] = $importer["uid"];
1732 $datarray["contact-id"] = $author_contact["cid"];
1733 $datarray["network"] = $author_contact["network"];
1735 $datarray["author-link"] = $person["url"];
1736 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1738 $datarray["owner-link"] = $contact["url"];
1739 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1741 // Will be overwritten for sharing accounts in Item::insert
1743 $datarray["post-type"] = Item::PT_FETCHED;
1744 } elseif ($datarray["uid"] == 0) {
1745 $datarray["post-type"] = Item::PT_GLOBAL;
1747 $datarray["post-type"] = Item::PT_COMMENT;
1750 $datarray["guid"] = $guid;
1751 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1752 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1754 $datarray["verb"] = Activity::POST;
1755 $datarray["gravity"] = GRAVITY_COMMENT;
1757 if ($thr_uri != "") {
1758 $datarray["parent-uri"] = $thr_uri;
1760 $datarray["parent-uri"] = $parent_item["uri"];
1763 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1765 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1766 $datarray["source"] = $xml;
1768 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1770 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1771 $body = Markdown::toBBCode($text);
1773 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1775 self::storeMentions($datarray['uri-id'], $text);
1776 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1778 self::fetchGuid($datarray);
1780 // If we are the origin of the parent we store the original data.
1781 // We notify our followers during the item storage.
1782 if ($parent_item["origin"]) {
1783 $datarray['diaspora_signed_text'] = json_encode($data);
1786 $message_id = Item::insert($datarray);
1788 if ($message_id <= 0) {
1793 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1794 if ($datarray['uid'] == 0) {
1795 Item::distribute($message_id, json_encode($data));
1803 * processes and stores private messages
1805 * @param array $importer Array of the importer user
1806 * @param array $contact The contact of the message
1807 * @param object $data The message object
1808 * @param array $msg Array of the processed message, author handle and key
1809 * @param object $mesg The private message
1810 * @param array $conversation The conversation record to which this message belongs
1812 * @return bool "true" if it was successful
1813 * @throws \Exception
1815 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1817 $author = Strings::escapeTags(XML::unescape($data->author));
1818 $guid = Strings::escapeTags(XML::unescape($data->guid));
1819 $subject = Strings::escapeTags(XML::unescape($data->subject));
1821 // "diaspora_handle" is the element name from the old version
1822 // "author" is the element name from the new version
1823 if ($mesg->author) {
1824 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1825 } elseif ($mesg->diaspora_handle) {
1826 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1831 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1832 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1833 $msg_text = XML::unescape($mesg->text);
1834 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1836 if ($msg_conversation_guid != $guid) {
1837 Logger::log("message conversation guid does not belong to the current conversation.");
1841 $body = Markdown::toBBCode($msg_text);
1842 $message_uri = $msg_author.":".$msg_guid;
1844 $person = FContact::getByURL($msg_author);
1846 return Mail::insert([
1847 'uid' => $importer['uid'],
1848 'guid' => $msg_guid,
1849 'convid' => $conversation['id'],
1850 'from-name' => $person['name'],
1851 'from-photo' => $person['photo'],
1852 'from-url' => $person['url'],
1853 'contact-id' => $contact['id'],
1854 'title' => $subject,
1856 'uri' => $message_uri,
1857 'parent-uri' => $author . ':' . $guid,
1858 'created' => $msg_created_at
1863 * Processes new private messages (answers to private messages are processed elsewhere)
1865 * @param array $importer Array of the importer user
1866 * @param array $msg Array of the processed message, author handle and key
1867 * @param object $data The message object
1869 * @return bool Success
1870 * @throws \Exception
1872 private static function receiveConversation(array $importer, $msg, $data)
1874 $author = Strings::escapeTags(XML::unescape($data->author));
1875 $guid = Strings::escapeTags(XML::unescape($data->guid));
1876 $subject = Strings::escapeTags(XML::unescape($data->subject));
1877 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1878 $participants = Strings::escapeTags(XML::unescape($data->participants));
1880 $messages = $data->message;
1882 if (!count($messages)) {
1883 Logger::log("empty conversation");
1887 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1892 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1893 if (!DBA::isResult($conversation)) {
1895 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1896 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1897 intval($importer["uid"]),
1899 DBA::escape($author),
1900 DBA::escape($created_at),
1901 DBA::escape(DateTimeFormat::utcNow()),
1902 DBA::escape($subject),
1903 DBA::escape($participants)
1906 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1909 if (!$conversation) {
1910 Logger::log("unable to create conversation.");
1914 foreach ($messages as $mesg) {
1915 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1922 * Processes "like" messages
1924 * @param array $importer Array of the importer user
1925 * @param string $sender The sender of the message
1926 * @param object $data The message object
1928 * @return int The message id of the generated like or "false" if there was an error
1929 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1930 * @throws \ImagickException
1932 private static function receiveLike(array $importer, $sender, $data)
1934 $author = Strings::escapeTags(XML::unescape($data->author));
1935 $guid = Strings::escapeTags(XML::unescape($data->guid));
1936 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1937 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1938 $positive = Strings::escapeTags(XML::unescape($data->positive));
1940 // likes on comments aren't supported by Diaspora - only on posts
1941 // But maybe this will be supported in the future, so we will accept it.
1942 if (!in_array($parent_type, ["Post", "Comment"])) {
1946 $contact = self::allowedContactByHandle($importer, $sender, true);
1951 $message_id = self::messageExists($importer["uid"], $guid);
1956 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1957 if (!$parent_item) {
1961 $person = FContact::getByURL($author);
1962 if (!is_array($person)) {
1963 Logger::log("unable to find author details");
1967 // Fetch the contact id - if we know this contact
1968 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1970 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1971 // We would accept this anyhow.
1972 if ($positive == "true") {
1973 $verb = Activity::LIKE;
1975 $verb = Activity::DISLIKE;
1980 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1982 $datarray["uid"] = $importer["uid"];
1983 $datarray["contact-id"] = $author_contact["cid"];
1984 $datarray["network"] = $author_contact["network"];
1986 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1987 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1989 $datarray["guid"] = $guid;
1990 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1992 $datarray["verb"] = $verb;
1993 $datarray["gravity"] = GRAVITY_ACTIVITY;
1994 $datarray["parent-uri"] = $parent_item["uri"];
1996 $datarray["object-type"] = Activity\ObjectType::NOTE;
1998 $datarray["body"] = $verb;
2000 // Diaspora doesn't provide a date for likes
2001 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2003 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2004 if ($parent_item['gravity'] != GRAVITY_PARENT) {
2005 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item['parent']]);
2006 $origin = $toplevel["origin"];
2008 $origin = $parent_item["origin"];
2011 // If we are the origin of the parent we store the original data.
2012 // We notify our followers during the item storage.
2014 $datarray['diaspora_signed_text'] = json_encode($data);
2017 $message_id = Item::insert($datarray);
2019 if ($message_id <= 0) {
2024 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2025 if ($datarray['uid'] == 0) {
2026 Item::distribute($message_id, json_encode($data));
2034 * Processes private messages
2036 * @param array $importer Array of the importer user
2037 * @param object $data The message object
2039 * @return bool Success?
2040 * @throws \Exception
2042 private static function receiveMessage(array $importer, $data)
2044 $author = Strings::escapeTags(XML::unescape($data->author));
2045 $guid = Strings::escapeTags(XML::unescape($data->guid));
2046 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2047 $text = XML::unescape($data->text);
2048 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2050 $contact = self::allowedContactByHandle($importer, $author, true);
2055 $conversation = null;
2057 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2058 $conversation = DBA::selectFirst('conv', [], $condition);
2060 if (!DBA::isResult($conversation)) {
2061 Logger::log("conversation not available.");
2065 $message_uri = $author.":".$guid;
2067 $person = FContact::getByURL($author);
2069 Logger::log("unable to find author details");
2073 $body = Markdown::toBBCode($text);
2075 $body = self::replacePeopleGuid($body, $person["url"]);
2077 return Mail::insert([
2078 'uid' => $importer['uid'],
2080 'convid' => $conversation['id'],
2081 'from-name' => $person['name'],
2082 'from-photo' => $person['photo'],
2083 'from-url' => $person['url'],
2084 'contact-id' => $contact['id'],
2085 'title' => $conversation['subject'],
2088 'uri' => $message_uri,
2089 'parent-uri' => $author.":".$conversation['guid'],
2090 'created' => $created_at
2095 * Processes participations - unsupported by now
2097 * @param array $importer Array of the importer user
2098 * @param object $data The message object
2100 * @return bool success
2101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2102 * @throws \ImagickException
2104 private static function receiveParticipation(array $importer, $data)
2106 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2107 $guid = Strings::escapeTags(XML::unescape($data->guid));
2108 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2110 $contact = self::allowedContactByHandle($importer, $author, true);
2115 if (self::messageExists($importer["uid"], $guid)) {
2119 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2120 if (!$parent_item) {
2124 if (!$parent_item['origin']) {
2125 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2128 if (!in_array($parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
2129 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2133 $person = FContact::getByURL($author);
2134 if (!is_array($person)) {
2135 Logger::log("Person not found: ".$author);
2139 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2141 // Store participation
2144 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2146 $datarray["uid"] = $importer["uid"];
2147 $datarray["contact-id"] = $author_contact["cid"];
2148 $datarray["network"] = $author_contact["network"];
2150 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2151 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2153 $datarray["guid"] = $guid;
2154 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2156 $datarray["verb"] = Activity::FOLLOW;
2157 $datarray["gravity"] = GRAVITY_ACTIVITY;
2158 $datarray["parent-uri"] = $parent_item["uri"];
2160 $datarray["object-type"] = Activity\ObjectType::NOTE;
2162 $datarray["body"] = Activity::FOLLOW;
2164 // Diaspora doesn't provide a date for a participation
2165 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2167 $message_id = Item::insert($datarray);
2169 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2171 // Send all existing comments and likes to the requesting server
2172 $comments = Item::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
2173 ['parent' => $parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
2174 while ($comment = Item::fetch($comments)) {
2175 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2176 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2180 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2181 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2185 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2186 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2190 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2191 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2192 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2195 DBA::close($comments);
2201 * Processes photos - unneeded
2203 * @param array $importer Array of the importer user
2204 * @param object $data The message object
2206 * @return bool always true
2208 private static function receivePhoto(array $importer, $data)
2210 // There doesn't seem to be a reason for this function,
2211 // since the photo data is transmitted in the status message as well
2216 * Processes poll participations - unssupported
2218 * @param array $importer Array of the importer user
2219 * @param object $data The message object
2221 * @return bool always true
2223 private static function receivePollParticipation(array $importer, $data)
2225 // We don't support polls by now
2230 * Processes incoming profile updates
2232 * @param array $importer Array of the importer user
2233 * @param object $data The message object
2235 * @return bool Success
2236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2237 * @throws \ImagickException
2239 private static function receiveProfile(array $importer, $data)
2241 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2243 $contact = self::contactByHandle($importer["uid"], $author);
2248 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2249 $image_url = XML::unescape($data->image_url);
2250 $birthday = XML::unescape($data->birthday);
2251 $about = Markdown::toBBCode(XML::unescape($data->bio));
2252 $location = Markdown::toBBCode(XML::unescape($data->location));
2253 $searchable = (XML::unescape($data->searchable) == "true");
2254 $nsfw = (XML::unescape($data->nsfw) == "true");
2255 $tags = XML::unescape($data->tag_string);
2257 $tags = explode("#", $tags);
2260 foreach ($tags as $tag) {
2261 $tag = trim(strtolower($tag));
2267 $keywords = implode(", ", $keywords);
2269 $handle_parts = explode("@", $author);
2270 $nick = $handle_parts[0];
2273 $name = $handle_parts[0];
2276 if (preg_match("|^https?://|", $image_url) === 0) {
2277 $image_url = "http://".$handle_parts[1].$image_url;
2280 Contact::updateAvatar($contact["id"], $image_url);
2282 // Generic birthday. We don't know the timezone. The year is irrelevant.
2284 $birthday = str_replace("1000", "1901", $birthday);
2286 if ($birthday != "") {
2287 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2290 // this is to prevent multiple birthday notifications in a single year
2291 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2293 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2294 $birthday = $contact["bd"];
2297 $fields = ['name' => $name, 'location' => $location,
2298 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2299 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2300 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2302 if (!empty($birthday)) {
2303 $fields['bd'] = $birthday;
2306 DBA::update('contact', $fields, ['id' => $contact['id']]);
2308 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2314 * Processes incoming friend requests
2316 * @param array $importer Array of the importer user
2317 * @param array $contact The contact that send the request
2319 * @throws \Exception
2321 private static function receiveRequestMakeFriend(array $importer, array $contact)
2323 if ($contact["rel"] == Contact::SHARING) {
2326 ['rel' => Contact::FRIEND, 'writable' => true],
2327 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2333 * Processes incoming sharing notification
2335 * @param array $importer Array of the importer user
2336 * @param object $data The message object
2338 * @return bool Success
2339 * @throws \Exception
2341 private static function receiveContactRequest(array $importer, $data)
2343 $author = XML::unescape($data->author);
2344 $recipient = XML::unescape($data->recipient);
2346 if (!$author || !$recipient) {
2350 // the current protocol version doesn't know these fields
2351 // That means that we will assume their existance
2352 if (isset($data->following)) {
2353 $following = (XML::unescape($data->following) == "true");
2358 if (isset($data->sharing)) {
2359 $sharing = (XML::unescape($data->sharing) == "true");
2364 $contact = self::contactByHandle($importer["uid"], $author);
2366 // perhaps we were already sharing with this person. Now they're sharing with us.
2367 // That makes us friends.
2370 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2371 self::receiveRequestMakeFriend($importer, $contact);
2373 // refetch the contact array
2374 $contact = self::contactByHandle($importer["uid"], $author);
2376 // If we are now friends, we are sending a share message.
2377 // Normally we needn't to do so, but the first message could have been vanished.
2378 if (in_array($contact["rel"], [Contact::FRIEND])) {
2379 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2380 if (DBA::isResult($user)) {
2381 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2382 self::sendShare($user, $contact);
2387 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2388 Contact::removeFollower($importer, $contact);
2393 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2394 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2396 } elseif (!$following && !$sharing) {
2397 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2399 } elseif (!$following && $sharing) {
2400 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2401 } elseif ($following && $sharing) {
2402 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2403 } elseif ($following && !$sharing) {
2404 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2407 $ret = FContact::getByURL($author);
2409 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2410 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2414 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2416 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2421 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2422 'author-link' => $ret['url']];
2424 $result = Contact::addRelationship($importer, $contact, $item, false);
2425 if ($result === true) {
2426 $contact_record = self::contactByHandle($importer['uid'], $author);
2427 if (!$contact_record) {
2428 Logger::info('unable to locate newly created contact record.');
2432 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2433 if (DBA::isResult($user)) {
2434 self::sendShare($user, $contact_record);
2436 // Send the profile data, maybe it weren't transmitted before
2437 self::sendProfile($importer['uid'], [$contact_record]);
2445 * Fetches a message with a given guid
2447 * @param string $guid message guid
2448 * @param string $orig_author handle of the original post
2449 * @return array The fetched item
2450 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2451 * @throws \ImagickException
2453 public static function originalItem($guid, $orig_author)
2456 Logger::log('Empty guid. Quitting.');
2460 // Do we already have this item?
2461 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2462 'author-name', 'author-link', 'author-avatar', 'plink'];
2463 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2464 $item = Item::selectFirst($fields, $condition);
2466 if (DBA::isResult($item)) {
2467 Logger::log("reshared message ".$guid." already exists on system.");
2469 // Maybe it is already a reshared item?
2470 // Then refetch the content, if it is a reshare from a reshare.
2471 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2472 if (self::isReshare($item["body"], true)) {
2474 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2475 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2477 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2479 // Add OEmbed and other information to the body
2480 $item["body"] = PageInfo::searchAndAppendToBody($item["body"], false, true);
2488 if (!DBA::isResult($item)) {
2489 if (empty($orig_author)) {
2490 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2494 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2495 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2496 $stored = self::storeByGuid($guid, $server);
2499 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2500 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2501 $stored = self::storeByGuid($guid, $server);
2505 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2506 'author-name', 'author-link', 'author-avatar', 'plink'];
2507 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2508 $item = Item::selectFirst($fields, $condition);
2510 if (DBA::isResult($item)) {
2511 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2512 if (self::isReshare($item["body"], false)) {
2513 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2514 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2525 * Stores a reshare activity
2527 * @param array $item Array of reshare post
2528 * @param integer $parent_message_id Id of the parent post
2529 * @param string $guid GUID string of reshare action
2530 * @param string $author Author handle
2532 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2534 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2538 $datarray['uid'] = $item['uid'];
2539 $datarray['contact-id'] = $item['contact-id'];
2540 $datarray['network'] = $item['network'];
2542 $datarray['author-link'] = $item['author-link'];
2543 $datarray['author-id'] = $item['author-id'];
2545 $datarray['owner-link'] = $datarray['author-link'];
2546 $datarray['owner-id'] = $datarray['author-id'];
2548 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2549 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2550 $datarray['parent-uri'] = $parent['uri'];
2552 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2553 $datarray['gravity'] = GRAVITY_ACTIVITY;
2554 $datarray['object-type'] = Activity\ObjectType::NOTE;
2556 $datarray['protocol'] = $item['protocol'];
2558 $datarray['plink'] = self::plink($author, $datarray['guid']);
2559 $datarray['private'] = $item['private'];
2560 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2562 $message_id = Item::insert($datarray);
2565 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2566 if ($datarray['uid'] == 0) {
2567 Item::distribute($message_id);
2573 * Processes a reshare message
2575 * @param array $importer Array of the importer user
2576 * @param object $data The message object
2577 * @param string $xml The original XML of the message
2579 * @return int the message id
2580 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2581 * @throws \ImagickException
2583 private static function receiveReshare(array $importer, $data, $xml)
2585 $author = Strings::escapeTags(XML::unescape($data->author));
2586 $guid = Strings::escapeTags(XML::unescape($data->guid));
2587 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2588 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2589 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2590 /// @todo handle unprocessed property "provider_display_name"
2591 $public = Strings::escapeTags(XML::unescape($data->public));
2593 $contact = self::allowedContactByHandle($importer, $author, false);
2598 $message_id = self::messageExists($importer["uid"], $guid);
2603 $original_item = self::originalItem($root_guid, $root_author);
2604 if (!$original_item) {
2610 $datarray["uid"] = $importer["uid"];
2611 $datarray["contact-id"] = $contact["id"];
2612 $datarray["network"] = Protocol::DIASPORA;
2614 $datarray["author-link"] = $contact["url"];
2615 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2617 $datarray["owner-link"] = $datarray["author-link"];
2618 $datarray["owner-id"] = $datarray["author-id"];
2620 $datarray["guid"] = $guid;
2621 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2622 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2624 $datarray["verb"] = Activity::POST;
2625 $datarray["gravity"] = GRAVITY_PARENT;
2627 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2628 $datarray["source"] = $xml;
2630 /// @todo Copy tag data from original post
2632 $prefix = BBCode::getShareOpeningTag(
2633 $original_item["author-name"],
2634 $original_item["author-link"],
2635 $original_item["author-avatar"],
2636 $original_item["plink"],
2637 $original_item["created"],
2638 $original_item["guid"]
2641 if (!empty($original_item['title'])) {
2642 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2645 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2647 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2649 $datarray["attach"] = $original_item["attach"];
2650 $datarray["app"] = $original_item["app"];
2652 $datarray["plink"] = self::plink($author, $guid);
2653 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2654 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2656 $datarray["object-type"] = $original_item["object-type"];
2658 self::fetchGuid($datarray);
2659 $message_id = Item::insert($datarray);
2661 self::sendParticipation($contact, $datarray);
2663 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2664 if ($root_message_id) {
2665 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2669 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2670 if ($datarray['uid'] == 0) {
2671 Item::distribute($message_id);
2680 * Processes retractions
2682 * @param array $importer Array of the importer user
2683 * @param array $contact The contact of the item owner
2684 * @param object $data The message object
2686 * @return bool success
2687 * @throws \Exception
2689 private static function itemRetraction(array $importer, array $contact, $data)
2691 $author = Strings::escapeTags(XML::unescape($data->author));
2692 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2693 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2695 $person = FContact::getByURL($author);
2696 if (!is_array($person)) {
2697 Logger::log("unable to find author detail for ".$author);
2701 if (empty($contact["url"])) {
2702 $contact["url"] = $person["url"];
2705 // Fetch items that are about to be deleted
2706 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2708 // When we receive a public retraction, we delete every item that we find.
2709 if ($importer['uid'] == 0) {
2710 $condition = ['guid' => $target_guid, 'deleted' => false];
2712 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2715 $r = Item::select($fields, $condition);
2716 if (!DBA::isResult($r)) {
2717 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2721 while ($item = Item::fetch($r)) {
2722 if (strstr($item['file'], '[')) {
2723 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2727 // Fetch the parent item
2728 $parent = Item::selectFirst(['author-link'], ['id' => $item['parent']]);
2730 // Only delete it if the parent author really fits
2731 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2732 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2736 Item::markForDeletion(['id' => $item['id']]);
2738 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent'], Logger::DEBUG);
2745 * Receives retraction messages
2747 * @param array $importer Array of the importer user
2748 * @param string $sender The sender of the message
2749 * @param object $data The message object
2751 * @return bool Success
2752 * @throws \Exception
2754 private static function receiveRetraction(array $importer, $sender, $data)
2756 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2758 $contact = self::contactByHandle($importer["uid"], $sender);
2759 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2760 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2768 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2770 switch ($target_type) {
2775 case "StatusMessage":
2776 return self::itemRetraction($importer, $contact, $data);
2778 case "PollParticipation":
2780 // Currently unsupported
2784 Logger::log("Unknown target type ".$target_type);
2791 * Checks if an incoming message is wanted
2793 * @param string $url
2794 * @param integer $uriid
2795 * @param string $author
2796 * @param string $body
2797 * @return boolean Is the message wanted?
2799 private static function isSolicitedMessage(string $url, int $uriid, string $author, string $body)
2801 $contact = Contact::getByURL($author);
2802 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
2803 $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
2804 Logger::info('Author has got followers - accepted', ['url' => $url, 'author' => $author]);
2808 $taglist = Tag::getByURIId($uriid, [Tag::HASHTAG]);
2809 $tags = array_column($taglist, 'name');
2810 return Relay::isSolicitedPost($tags, $body, $contact['id'], $url, Protocol::DIASPORA);
2814 * Store an attached photo in the post-media table
2817 * @param object $photo
2820 private static function storePhotoAsMedia(int $uriid, $photo)
2823 $data['uri-id'] = $uriid;
2824 $data['type'] = Post\Media::IMAGE;
2825 $data['url'] = XML::unescape($photo->remote_photo_path) . XML::unescape($photo->remote_photo_name);
2826 $data['height'] = (int)XML::unescape($photo->height ?? 0);
2827 $data['width'] = (int)XML::unescape($photo->width ?? 0);
2828 $data['description'] = XML::unescape($photo->text ?? '');
2830 Post\Media::insert($data);
2834 * Receives status messages
2836 * @param array $importer Array of the importer user
2837 * @param SimpleXMLElement $data The message object
2838 * @param string $xml The original XML of the message
2839 * @param bool $fetched The message had been fetched and not pushed
2840 * @return int The message id of the newly created item
2841 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2842 * @throws \ImagickException
2844 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml, bool $fetched)
2846 $author = Strings::escapeTags(XML::unescape($data->author));
2847 $guid = Strings::escapeTags(XML::unescape($data->guid));
2848 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2849 $public = Strings::escapeTags(XML::unescape($data->public));
2850 $text = XML::unescape($data->text);
2851 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2853 $contact = self::allowedContactByHandle($importer, $author, false);
2858 $message_id = self::messageExists($importer["uid"], $guid);
2864 if ($data->location) {
2865 foreach ($data->location->children() as $fieldname => $data) {
2866 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2870 $raw_body = $body = Markdown::toBBCode($text);
2874 $datarray["guid"] = $guid;
2875 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2876 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2878 // Attach embedded pictures to the body
2880 foreach ($data->photo as $photo) {
2881 self::storePhotoAsMedia($datarray['uri-id'], $photo);
2882 $body = "[img]".XML::unescape($photo->remote_photo_path).
2883 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2886 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2888 $datarray["object-type"] = Activity\ObjectType::NOTE;
2890 // Add OEmbed and other information to the body
2891 if (!self::isHubzilla($contact["url"])) {
2892 $body = PageInfo::searchAndAppendToBody($body, false, true);
2896 /// @todo enable support for polls
2897 //if ($data->poll) {
2898 // foreach ($data->poll AS $poll)
2903 /// @todo enable support for events
2905 $datarray["uid"] = $importer["uid"];
2906 $datarray["contact-id"] = $contact["id"];
2907 $datarray["network"] = Protocol::DIASPORA;
2909 $datarray["author-link"] = $contact["url"];
2910 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2912 $datarray["owner-link"] = $datarray["author-link"];
2913 $datarray["owner-id"] = $datarray["author-id"];
2915 $datarray["verb"] = Activity::POST;
2916 $datarray["gravity"] = GRAVITY_PARENT;
2918 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2919 $datarray["source"] = $xml;
2922 $datarray["post-type"] = Item::PT_FETCHED;
2923 } elseif ($datarray["uid"] == 0) {
2924 $datarray["post-type"] = Item::PT_GLOBAL;
2927 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2928 $datarray["raw-body"] = self::replacePeopleGuid($raw_body, $contact["url"]);
2930 self::storeMentions($datarray['uri-id'], $text);
2931 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
2933 if (!$fetched && !self::isSolicitedMessage($datarray["uri"], $datarray['uri-id'], $author, $body)) {
2934 DBA::delete('item-uri', ['uri' => $datarray['uri']]);
2938 if ($provider_display_name != "") {
2939 $datarray["app"] = $provider_display_name;
2942 $datarray["plink"] = self::plink($author, $guid);
2943 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2944 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2946 if (isset($address["address"])) {
2947 $datarray["location"] = $address["address"];
2950 if (isset($address["lat"]) && isset($address["lng"])) {
2951 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2954 self::fetchGuid($datarray);
2955 $message_id = Item::insert($datarray);
2957 self::sendParticipation($contact, $datarray);
2960 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2961 if ($datarray['uid'] == 0) {
2962 Item::distribute($message_id);
2970 /* ************************************************************************************** *
2971 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2972 * ************************************************************************************** */
2975 * returnes the handle of a contact
2977 * @param array $contact contact array
2979 * @return string the handle in the format user@domain.tld
2980 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2982 private static function myHandle(array $contact)
2984 if (!empty($contact["addr"])) {
2985 return $contact["addr"];
2988 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2989 // So - just in case - we build the the address here.
2990 if ($contact["nickname"] != "") {
2991 $nick = $contact["nickname"];
2993 $nick = $contact["nick"];
2996 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3001 * Creates the data for a private message in the new format
3003 * @param string $msg The message that is to be transmitted
3004 * @param array $user The record of the sender
3005 * @param array $contact Target of the communication
3006 * @param string $prvkey The private key of the sender
3007 * @param string $pubkey The public key of the receiver
3009 * @return string The encrypted data
3010 * @throws \Exception
3012 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3014 Logger::log("Message: ".$msg, Logger::DATA);
3016 // without a public key nothing will work
3018 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3022 $aes_key = openssl_random_pseudo_bytes(32);
3023 $b_aes_key = base64_encode($aes_key);
3024 $iv = openssl_random_pseudo_bytes(16);
3025 $b_iv = base64_encode($iv);
3027 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3029 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3031 $encrypted_key_bundle = "";
3032 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
3036 $json_object = json_encode(
3037 ["aes_key" => base64_encode($encrypted_key_bundle),
3038 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3041 return $json_object;
3045 * Creates the envelope for the "fetch" endpoint and for the new format
3047 * @param string $msg The message that is to be transmitted
3048 * @param array $user The record of the sender
3050 * @return string The envelope
3051 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3053 public static function buildMagicEnvelope($msg, array $user)
3055 $b64url_data = Strings::base64UrlEncode($msg);
3056 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3058 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3059 $type = "application/xml";
3060 $encoding = "base64url";
3061 $alg = "RSA-SHA256";
3062 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3064 // Fallback if the private key wasn't transmitted in the expected field
3065 if ($user['uprvkey'] == "") {
3066 $user['uprvkey'] = $user['prvkey'];
3069 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3070 $sig = Strings::base64UrlEncode($signature);
3072 $xmldata = ["me:env" => ["me:data" => $data,
3073 "@attributes" => ["type" => $type],
3074 "me:encoding" => $encoding,
3077 "@attributes2" => ["key_id" => $key_id]]];
3079 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3081 return XML::fromArray($xmldata, $xml, false, $namespaces);
3085 * Create the envelope for a message
3087 * @param string $msg The message that is to be transmitted
3088 * @param array $user The record of the sender
3089 * @param array $contact Target of the communication
3090 * @param string $prvkey The private key of the sender
3091 * @param string $pubkey The public key of the receiver
3092 * @param bool $public Is the message public?
3094 * @return string The message that will be transmitted to other servers
3095 * @throws \Exception
3097 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3099 // The message is put into an envelope with the sender's signature
3100 $envelope = self::buildMagicEnvelope($msg, $user);
3102 // Private messages are put into a second envelope, encrypted with the receivers public key
3104 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3111 * Creates a signature for a message
3113 * @param array $owner the array of the owner of the message
3114 * @param array $message The message that is to be signed
3116 * @return string The signature
3118 private static function signature($owner, $message)
3121 unset($sigmsg["author_signature"]);
3122 unset($sigmsg["parent_author_signature"]);
3124 $signed_text = implode(";", $sigmsg);
3126 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3130 * Transmit a message to a target server
3132 * @param array $owner the array of the item owner
3133 * @param array $contact Target of the communication
3134 * @param string $envelope The message that is to be transmitted
3135 * @param bool $public_batch Is it a public post?
3136 * @param string $guid message guid
3138 * @return int Result of the transmission
3139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3140 * @throws \ImagickException
3142 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3144 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3149 $logid = Strings::getRandomHex(4);
3151 // We always try to use the data from the fcontact table.
3152 // This is important for transmitting data to Friendica servers.
3153 if (!empty($contact['addr'])) {
3154 $fcontact = FContact::getByURL($contact['addr']);
3155 if (!empty($fcontact)) {
3156 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3160 if (empty($dest_url)) {
3161 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3165 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3169 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3171 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3172 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3174 $postResult = DI::httpRequest()->post($dest_url . "/", $envelope, ["Content-Type: " . $content_type]);
3175 $return_code = $postResult->getReturnCode();
3177 Logger::log("test_mode");
3181 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3183 return $return_code ? $return_code : -1;
3188 * Build the post xml
3190 * @param string $type The message type
3191 * @param array $message The message data
3193 * @return string The post XML
3195 public static function buildPostXml($type, $message)
3197 $data = [$type => $message];
3199 return XML::fromArray($data, $xml);
3203 * Builds and transmit messages
3205 * @param array $owner the array of the item owner
3206 * @param array $contact Target of the communication
3207 * @param string $type The message type
3208 * @param array $message The message data
3209 * @param bool $public_batch Is it a public post?
3210 * @param string $guid message guid
3212 * @return int Result of the transmission
3213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3214 * @throws \ImagickException
3216 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3218 $msg = self::buildPostXml($type, $message);
3220 Logger::log('message: '.$msg, Logger::DATA);
3221 Logger::log('send guid '.$guid, Logger::DEBUG);
3223 // Fallback if the private key wasn't transmitted in the expected field
3224 if (empty($owner['uprvkey'])) {
3225 $owner['uprvkey'] = $owner['prvkey'];
3228 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3230 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3232 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3234 return $return_code;
3238 * sends a participation (Used to get all further updates)
3240 * @param array $contact Target of the communication
3241 * @param array $item Item array
3243 * @return int The result of the transmission
3244 * @throws \Exception
3246 private static function sendParticipation(array $contact, array $item)
3248 // Don't send notifications for private postings
3249 if ($item['private'] == Item::PRIVATE) {
3253 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3255 $result = DI::cache()->get($cachekey);
3256 if (!is_null($result)) {
3260 // Fetch some user id to have a valid handle to transmit the participation.
3261 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3262 // If the item belongs to a user, we take this user id.
3263 if ($item['uid'] == 0) {
3264 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3265 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3266 $owner = User::getOwnerDataById($first_user['uid']);
3268 $owner = User::getOwnerDataById($item['uid']);
3271 $author = self::myHandle($owner);
3273 $message = ["author" => $author,
3274 "guid" => System::createUUID(),
3275 "parent_type" => "Post",
3276 "parent_guid" => $item["guid"]];
3278 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3280 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3281 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3283 return self::buildAndTransmit($owner, $contact, "participation", $message);
3287 * sends an account migration
3289 * @param array $owner the array of the item owner
3290 * @param array $contact Target of the communication
3291 * @param int $uid User ID
3293 * @return int The result of the transmission
3294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3295 * @throws \ImagickException
3297 public static function sendAccountMigration(array $owner, array $contact, $uid)
3299 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3300 $profile = self::createProfileData($uid);
3302 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3303 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3305 $message = ["author" => $old_handle,
3306 "profile" => $profile,
3307 "signature" => $signature];
3309 Logger::info('Send account migration', ['msg' => $message]);
3311 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3315 * Sends a "share" message
3317 * @param array $owner the array of the item owner
3318 * @param array $contact Target of the communication
3320 * @return int The result of the transmission
3321 * @throws \Exception
3323 public static function sendShare(array $owner, array $contact)
3326 * @todo support the different possible combinations of "following" and "sharing"
3327 * Currently, Diaspora only interprets the "sharing" field
3329 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3333 switch ($contact["rel"]) {
3334 case Contact::FRIEND:
3338 case Contact::SHARING:
3342 case Contact::FOLLOWER:
3348 $message = ["author" => self::myHandle($owner),
3349 "recipient" => $contact["addr"],
3350 "following" => "true",
3351 "sharing" => "true"];
3353 Logger::info('Send share', ['msg' => $message]);
3355 return self::buildAndTransmit($owner, $contact, "contact", $message);
3359 * sends an "unshare"
3361 * @param array $owner the array of the item owner
3362 * @param array $contact Target of the communication
3364 * @return int The result of the transmission
3365 * @throws \Exception
3367 public static function sendUnshare(array $owner, array $contact)
3369 $message = ["author" => self::myHandle($owner),
3370 "recipient" => $contact["addr"],
3371 "following" => "false",
3372 "sharing" => "false"];
3374 Logger::info('Send unshare', ['msg' => $message]);
3376 return self::buildAndTransmit($owner, $contact, "contact", $message);
3380 * Checks a message body if it is a reshare
3382 * @param string $body The message body that is to be check
3383 * @param bool $complete Should it be a complete check or a simple check?
3385 * @return array|bool Reshare details or "false" if no reshare
3386 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3387 * @throws \ImagickException
3389 public static function isReshare($body, $complete = true)
3391 $body = trim($body);
3393 $reshared = Item::getShareArray(['body' => $body]);
3394 if (empty($reshared)) {
3398 // Skip if it isn't a pure repeated messages
3399 // Does it start with a share?
3400 if (!empty($reshared['comment']) && $complete) {
3404 if (!empty($reshared['guid']) && $complete) {
3405 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3406 $item = Item::selectFirst(['contact-id'], $condition);
3407 if (DBA::isResult($item)) {
3409 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3410 $ret["root_guid"] = $reshared['guid'];
3412 } elseif ($complete) {
3413 // We are resharing something that isn't a DFRN or Diaspora post.
3414 // So we have to return "false" on "$complete" to not trigger a reshare.
3417 } elseif (empty($reshared['guid']) && $complete) {
3423 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3424 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3425 if (!empty($contact['addr'])) {
3426 $ret['root_handle'] = $contact['addr'];
3430 if (empty($ret) && !$complete) {
3438 * Create an event array
3440 * @param integer $event_id The id of the event
3442 * @return array with event data
3443 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3445 private static function buildEvent($event_id)
3447 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3448 if (!DBA::isResult($r)) {
3456 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3457 if (!DBA::isResult($r)) {
3463 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3464 if (!DBA::isResult($r)) {
3470 $eventdata['author'] = self::myHandle($owner);
3472 if ($event['guid']) {
3473 $eventdata['guid'] = $event['guid'];
3476 $mask = DateTimeFormat::ATOM;
3478 /// @todo - establish "all day" events in Friendica
3479 $eventdata["all_day"] = "false";
3481 $eventdata['timezone'] = 'UTC';
3482 if (!$event['adjust'] && $user['timezone']) {
3483 $eventdata['timezone'] = $user['timezone'];
3486 if ($event['start']) {
3487 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3489 if ($event['finish'] && !$event['nofinish']) {
3490 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3492 if ($event['summary']) {
3493 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3495 if ($event['desc']) {
3496 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3498 if ($event['location']) {
3499 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3500 $coord = Map::getCoordinates($event['location']);
3503 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3504 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3505 $location["lat"] = $coord['lat'];
3506 $location["lng"] = $coord['lon'];
3508 $location["lat"] = 0;
3509 $location["lng"] = 0;
3511 $eventdata['location'] = $location;
3518 * Create a post (status message or reshare)
3520 * @param array $item The item that will be exported
3521 * @param array $owner the array of the item owner
3524 * 'type' -> Message type ("status_message" or "reshare")
3525 * 'message' -> Array of XML elements of the status
3526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3527 * @throws \ImagickException
3529 public static function buildStatus(array $item, array $owner)
3531 $cachekey = "diaspora:buildStatus:".$item['guid'];
3533 $result = DI::cache()->get($cachekey);
3534 if (!is_null($result)) {
3538 $myaddr = self::myHandle($owner);
3540 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3541 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3542 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3544 // Detect a share element and do a reshare
3545 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3546 $message = ["author" => $myaddr,
3547 "guid" => $item["guid"],
3548 "created_at" => $created,
3549 "root_author" => $ret["root_handle"],
3550 "root_guid" => $ret["root_guid"],
3551 "provider_display_name" => $item["app"],
3552 "public" => $public];
3556 $title = $item["title"];
3557 $body = $item["body"];
3559 // Fetch the title from an attached link - if there is one
3560 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3561 $page_data = BBCode::getAttachmentData($item['body']);
3562 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3563 $title = $page_data['title'];
3567 if ($item['author-link'] != $item['owner-link']) {
3568 require_once 'mod/share.php';
3569 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3570 $item['plink'], $item['created']) . $body . '[/share]';
3573 // convert to markdown
3574 $body = html_entity_decode(BBCode::toMarkdown($body));
3577 if (strlen($title)) {
3578 $body = "### ".html_entity_decode($title)."\n\n".$body;
3581 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
3582 if (!empty($attachments)) {
3583 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3584 foreach ($attachments as $attachment) {
3585 $body .= "[" . $attachment['description'] . "](" . $attachment['url'] . ")\n";
3591 if ($item["location"] != "")
3592 $location["address"] = $item["location"];
3594 if ($item["coord"] != "") {
3595 $coord = explode(" ", $item["coord"]);
3596 $location["lat"] = $coord[0];
3597 $location["lng"] = $coord[1];
3600 $message = ["author" => $myaddr,
3601 "guid" => $item["guid"],
3602 "created_at" => $created,
3603 "edited_at" => $edited,
3604 "public" => $public,
3606 "provider_display_name" => $item["app"],
3607 "location" => $location];
3609 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3610 if (!isset($location["lat"]) || !isset($location["lng"])) {
3611 unset($message["location"]);
3614 if ($item['event-id'] > 0) {
3615 $event = self::buildEvent($item['event-id']);
3616 if (count($event)) {
3617 $message['event'] = $event;
3619 if (!empty($event['location']['address']) &&
3620 !empty($event['location']['lat']) &&
3621 !empty($event['location']['lng'])) {
3622 $message['location'] = $event['location'];
3625 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3626 // $message['text'] = '';
3630 $type = "status_message";
3633 $msg = ["type" => $type, "message" => $message];
3635 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3640 private static function prependParentAuthorMention($body, $profile_url)
3642 $profile = Contact::getByURL($profile_url, false, ['addr', 'name', 'contact-type']);
3643 if (!empty($profile['addr'])
3644 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3645 && !strstr($body, $profile['addr'])
3646 && !strstr($body, $profile_url)
3648 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3657 * @param array $item The item that will be exported
3658 * @param array $owner the array of the item owner
3659 * @param array $contact Target of the communication
3660 * @param bool $public_batch Is it a public post?
3662 * @return int The result of the transmission
3663 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3664 * @throws \ImagickException
3666 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3668 $status = self::buildStatus($item, $owner);
3670 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3674 * Creates a "like" object
3676 * @param array $item The item that will be exported
3677 * @param array $owner the array of the item owner
3679 * @return array The data for a "like"
3680 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3682 private static function constructLike(array $item, array $owner)
3684 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3685 if (!DBA::isResult($parent)) {
3689 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3691 if ($item['verb'] === Activity::LIKE) {
3693 } elseif ($item['verb'] === Activity::DISLIKE) {
3694 $positive = "false";
3697 return(["author" => self::myHandle($owner),
3698 "guid" => $item["guid"],
3699 "parent_guid" => $parent["guid"],
3700 "parent_type" => $target_type,
3701 "positive" => $positive,
3702 "author_signature" => ""]);
3706 * Creates an "EventParticipation" object
3708 * @param array $item The item that will be exported
3709 * @param array $owner the array of the item owner
3711 * @return array The data for an "EventParticipation"
3712 * @throws \Exception
3714 private static function constructAttend(array $item, array $owner)
3716 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3717 if (!DBA::isResult($parent)) {
3721 switch ($item['verb']) {
3722 case Activity::ATTEND:
3723 $attend_answer = 'accepted';
3725 case Activity::ATTENDNO:
3726 $attend_answer = 'declined';
3728 case Activity::ATTENDMAYBE:
3729 $attend_answer = 'tentative';
3732 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3736 return(["author" => self::myHandle($owner),
3737 "guid" => $item["guid"],
3738 "parent_guid" => $parent["guid"],
3739 "status" => $attend_answer,
3740 "author_signature" => ""]);
3744 * Creates the object for a comment
3746 * @param array $item The item that will be exported
3747 * @param array $owner the array of the item owner
3749 * @return array|false The data for a comment
3750 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3752 private static function constructComment(array $item, array $owner)
3754 $cachekey = "diaspora:constructComment:".$item['guid'];
3756 $result = DI::cache()->get($cachekey);
3757 if (!is_null($result)) {
3761 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3762 if (!DBA::isResult($toplevel_item)) {
3763 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3767 $thread_parent_item = $toplevel_item;
3768 if ($item['thr-parent'] != $item['parent-uri']) {
3769 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3772 $body = $item["body"];
3774 // The replied to autor mention is prepended for clarity if:
3775 // - Item replied isn't yours
3776 // - Item is public or explicit mentions are disabled
3777 // - Implicit mentions are enabled
3779 $item['author-id'] != $thread_parent_item['author-id']
3780 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3781 && !DI::config()->get('system', 'disable_implicit_mentions')
3783 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3786 $text = html_entity_decode(BBCode::toMarkdown($body));
3787 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3788 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3791 "author" => self::myHandle($owner),
3792 "guid" => $item["guid"],
3793 "created_at" => $created,
3794 "edited_at" => $edited,
3795 "parent_guid" => $toplevel_item["guid"],
3797 "author_signature" => ""
3800 // Send the thread parent guid only if it is a threaded comment
3801 if ($item['thr-parent'] != $item['parent-uri']) {
3802 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3805 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3811 * Send a like or a comment
3813 * @param array $item The item that will be exported
3814 * @param array $owner the array of the item owner
3815 * @param array $contact Target of the communication
3816 * @param bool $public_batch Is it a public post?
3818 * @return int The result of the transmission
3819 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3820 * @throws \ImagickException
3822 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3824 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3825 $message = self::constructAttend($item, $owner);
3826 $type = "event_participation";
3827 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3828 $message = self::constructLike($item, $owner);
3830 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3831 $message = self::constructComment($item, $owner);
3835 if (empty($message)) {
3839 $message["author_signature"] = self::signature($owner, $message);
3841 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3845 * Creates a message from a signature record entry
3847 * @param array $item The item that will be exported
3848 * @return array The message
3850 private static function messageFromSignature(array $item)
3852 // Split the signed text
3853 $signed_parts = explode(";", $item['signed_text']);
3855 if ($item["deleted"]) {
3856 $message = ["author" => $item['signer'],
3857 "target_guid" => $signed_parts[0],
3858 "target_type" => $signed_parts[1]];
3859 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3860 $message = ["author" => $signed_parts[4],
3861 "guid" => $signed_parts[1],
3862 "parent_guid" => $signed_parts[3],
3863 "parent_type" => $signed_parts[2],
3864 "positive" => $signed_parts[0],
3865 "author_signature" => $item['signature'],
3866 "parent_author_signature" => ""];
3868 // Remove the comment guid
3869 $guid = array_shift($signed_parts);
3871 // Remove the parent guid
3872 $parent_guid = array_shift($signed_parts);
3874 // Remove the handle
3875 $handle = array_pop($signed_parts);
3878 "author" => $handle,
3880 "parent_guid" => $parent_guid,
3881 "text" => implode(";", $signed_parts),
3882 "author_signature" => $item['signature'],
3883 "parent_author_signature" => ""
3890 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3892 * @param array $item The item that will be exported
3893 * @param array $owner the array of the item owner
3894 * @param array $contact Target of the communication
3895 * @param bool $public_batch Is it a public post?
3897 * @return int The result of the transmission
3898 * @throws \Exception
3900 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3902 if ($item["deleted"]) {
3903 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3904 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3910 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3912 $msg = json_decode($item['signed_text'], true);
3915 if (is_array($msg)) {
3916 foreach ($msg as $field => $data) {
3917 if (!$item["deleted"]) {
3918 if ($field == "diaspora_handle") {
3921 if ($field == "target_type") {
3922 $field = "parent_type";
3926 $message[$field] = $data;
3929 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3932 $message["parent_author_signature"] = self::signature($owner, $message);
3934 Logger::info('Relayed data', ['msg' => $message]);
3936 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3940 * Sends a retraction (deletion) of a message, like or comment
3942 * @param array $item The item that will be exported
3943 * @param array $owner the array of the item owner
3944 * @param array $contact Target of the communication
3945 * @param bool $public_batch Is it a public post?
3946 * @param bool $relay Is the retraction transmitted from a relay?
3948 * @return int The result of the transmission
3949 * @throws \Exception
3951 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3953 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3955 $msg_type = "retraction";
3957 if ($item['gravity'] == GRAVITY_PARENT) {
3958 $target_type = "Post";
3959 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3960 $target_type = "Like";
3962 $target_type = "Comment";
3965 $message = ["author" => $itemaddr,
3966 "target_guid" => $item['guid'],
3967 "target_type" => $target_type];
3969 Logger::info('Got message', ['msg' => $message]);
3971 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3977 * @param array $item The item that will be exported
3978 * @param array $owner The owner
3979 * @param array $contact Target of the communication
3981 * @return int The result of the transmission
3982 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3983 * @throws \ImagickException
3985 public static function sendMail(array $item, array $owner, array $contact)
3987 $myaddr = self::myHandle($owner);
3989 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3990 if (!DBA::isResult($cnv)) {
3991 Logger::log("conversation not found.");
3995 $body = BBCode::toMarkdown($item["body"]);
3996 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3999 "author" => $myaddr,
4000 "guid" => $item["guid"],
4001 "conversation_guid" => $cnv["guid"],
4003 "created_at" => $created,
4006 if ($item["reply"]) {
4011 "author" => $cnv["creator"],
4012 "guid" => $cnv["guid"],
4013 "subject" => $cnv["subject"],
4014 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4015 "participants" => $cnv["recips"],
4019 $type = "conversation";
4022 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4026 * Split a name into first name and last name
4028 * @param string $name The name
4030 * @return array The array with "first" and "last"
4032 public static function splitName($name) {
4033 $name = trim($name);
4035 // Is the name longer than 64 characters? Then cut the rest of it.
4036 if (strlen($name) > 64) {
4037 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4038 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4040 $name = substr($name, 0, 64);
4044 // Take the first word as first name
4045 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4046 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4047 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4048 return ['first' => $first, 'last' => $last];
4051 // Take the last word as last name
4052 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4053 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4055 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4056 return ['first' => $first, 'last' => $last];
4059 // Take the first 32 characters if there is no space in the first 32 characters
4060 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4061 $first = substr($name, 0, 32);
4062 $last = substr($name, 32);
4063 return ['first' => $first, 'last' => $last];
4066 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4067 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4069 // Check if the last name is longer than 32 characters
4070 if (strlen($last) > 32) {
4071 if (strpos($last, ' ') <= 32) {
4072 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4074 $last = substr($last, 0, 32);
4078 return ['first' => $first, 'last' => $last];
4082 * Create profile data
4084 * @param int $uid The user id
4086 * @return array The profile data
4087 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4089 private static function createProfileData($uid)
4091 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4092 if (!DBA::isResult($profile)) {
4096 $handle = $profile["addr"];
4098 $split_name = self::splitName($profile['name']);
4099 $first = $split_name['first'];
4100 $last = $split_name['last'];
4102 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4103 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4104 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4105 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4111 if ($searchable === 'true') {
4114 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4115 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4119 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4122 $about = BBCode::toMarkdown($profile['about']);
4124 $location = $profile['location'];
4126 if ($profile['pub_keywords']) {
4127 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4128 $kw = str_replace(' ', ' ', $kw);
4129 $arr = explode(' ', $kw);
4131 for ($x = 0; $x < 5; $x ++) {
4132 if (!empty($arr[$x])) {
4133 $tags .= '#'. trim($arr[$x]) .' ';
4138 $tags = trim($tags);
4141 return ["author" => $handle,
4142 "first_name" => $first,
4143 "last_name" => $last,
4144 "image_url" => $large,
4145 "image_url_medium" => $medium,
4146 "image_url_small" => $small,
4149 "location" => $location,
4150 "searchable" => $searchable,
4152 "tag_string" => $tags];
4156 * Sends profile data
4158 * @param int $uid The user id
4159 * @param bool $recips optional, default false
4161 * @throws \Exception
4163 public static function sendProfile($uid, $recips = false)
4169 $owner = User::getOwnerDataById($uid);
4176 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4177 AND `uid` = %d AND `rel` != %d",
4178 DBA::escape(Protocol::DIASPORA),
4180 intval(Contact::SHARING)
4188 $message = self::createProfileData($uid);
4190 // @ToDo Split this into single worker jobs
4191 foreach ($recips as $recip) {
4192 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4193 self::buildAndTransmit($owner, $recip, "profile", $message);
4198 * Creates the signature for likes that are created on our system
4200 * @param integer $uid The user of that comment
4201 * @param array $item Item array
4203 * @return array Signed content
4204 * @throws \Exception
4206 public static function createLikeSignature($uid, array $item)
4208 $owner = User::getOwnerDataById($uid);
4209 if (empty($owner)) {
4210 Logger::info('No owner post, so not storing signature');
4214 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4218 $message = self::constructLike($item, $owner);
4219 if ($message === false) {
4223 $message["author_signature"] = self::signature($owner, $message);
4229 * Creates the signature for Comments that are created on our system
4231 * @param integer $uid The user of that comment
4232 * @param array $item Item array
4234 * @return array Signed content
4235 * @throws \Exception
4237 public static function createCommentSignature($uid, array $item)
4239 $owner = User::getOwnerDataById($uid);
4240 if (empty($owner)) {
4241 Logger::info('No owner post, so not storing signature');
4245 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4246 $item['thr-parent'] = $item['parent-uri'];
4248 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4249 if (!DBA::isResult($parent)) {
4253 $item['parent-uri'] = $parent['parent-uri'];
4255 $message = self::constructComment($item, $owner);
4256 if ($message === false) {
4260 $message["author_signature"] = self::signature($owner, $message);