3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GContact;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\Probe;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Map;
47 use Friendica\Util\Network;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
50 use Friendica\Worker\Delivery;
54 * This class contain functions to create and send Diaspora XML files
59 * Mark the relay contact of the given contact for archival
60 * This is called whenever there is a communication issue with the server.
61 * It avoids sending stuff to servers who don't exist anymore.
62 * The relay contact is a technical contact entry that exists once per server.
64 * @param array $contact of the relay contact
66 public static function markRelayForArchival(array $contact)
68 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
69 // This is already the relay contact, we don't need to fetch it
70 $relay_contact = $contact;
71 } elseif (empty($contact['baseurl'])) {
72 if (!empty($contact['batch'])) {
73 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
74 $relay_contact = DBA::selectFirst('contact', [], $condition);
79 $relay_contact = self::getRelayContact($contact['baseurl'], []);
82 if (!empty($relay_contact)) {
83 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
84 Contact::markForArchival($relay_contact);
89 * Return a list of relay servers
91 * The list contains not only the official relays but also servers that we serve directly
93 * @param integer $item_id The id of the item that is sent
94 * @param array $contacts The previously fetched contacts
96 * @return array of relay servers
97 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
99 public static function relayList($item_id, array $contacts = [])
103 // Fetching relay servers
104 $serverdata = DI::config()->get("system", "relay_server");
106 if (!empty($serverdata)) {
107 $servers = explode(",", $serverdata);
108 foreach ($servers as $server) {
109 $serverlist[$server] = trim($server);
113 if (DI::config()->get("system", "relay_directly", false)) {
114 // We distribute our stuff based on the parent to ensure that the thread will be complete
115 $parent = Item::selectFirst(['uri-id'], ['id' => $item_id]);
116 if (!DBA::isResult($parent)) {
120 // Servers that want to get all content
121 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
122 while ($server = DBA::fetch($servers)) {
123 $serverlist[$server['url']] = $server['url'];
125 DBA::close($servers);
127 // All tags of the current post
128 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
130 while ($tag = DBA::fetch($tags)) {
131 $taglist[] = $tag['name'];
135 // All servers who wants content with this tag
137 if (!empty($taglist)) {
138 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
139 while ($server = DBA::fetch($tagserver)) {
140 $tagserverlist[] = $server['gserver-id'];
142 DBA::close($tagserver);
145 // All adresses with the given id
146 if (!empty($tagserverlist)) {
147 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
148 while ($server = DBA::fetch($servers)) {
149 $serverlist[$server['url']] = $server['url'];
151 DBA::close($servers);
155 // Now we are collecting all relay contacts
156 foreach ($serverlist as $server_url) {
157 // We don't send messages to ourselves
158 if (Strings::compareLink($server_url, DI::baseUrl())) {
161 $contact = self::getRelayContact($server_url);
162 if (is_bool($contact)) {
167 foreach ($contacts as $entry) {
168 if ($entry['batch'] == $contact['batch']) {
174 $contacts[] = $contact;
182 * Return a contact for a given server address or creates a dummy entry
184 * @param string $server_url The url of the server
185 * @param array $fields Fieldlist
186 * @return array with the contact
189 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
191 // Fetch the relay contact
192 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
193 'contact-type' => Contact::TYPE_RELAY];
194 $contact = DBA::selectFirst('contact', $fields, $condition);
196 if (DBA::isResult($contact)) {
197 if ($contact['archive'] || $contact['blocked']) {
202 self::setRelayContact($server_url);
204 $contact = DBA::selectFirst('contact', $fields, $condition);
205 if (DBA::isResult($contact)) {
210 // It should never happen that we arrive here
215 * Update or insert a relay contact
217 * @param string $server_url The url of the server
218 * @param array $network_fields Optional network specific fields
221 public static function setRelayContact($server_url, array $network_fields = [])
223 $fields = ['created' => DateTimeFormat::utcNow(),
224 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
225 'nurl' => Strings::normaliseLink($server_url),
226 'network' => Protocol::DIASPORA, 'uid' => 0,
227 'batch' => $server_url . '/receive/public',
228 'rel' => Contact::FOLLOWER, 'blocked' => false,
229 'pending' => false, 'writable' => true,
230 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
232 $fields = array_merge($fields, $network_fields);
234 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
235 $old = DBA::selectFirst('contact', [], $condition);
236 if (DBA::isResult($old)) {
237 unset($fields['created']);
238 $condition = ['id' => $old['id']];
240 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
241 DBA::update('contact', $fields, $condition, $old);
243 Logger::info('Create relay contact', ['fields' => $fields]);
244 Contact::insert($fields);
249 * Return a list of participating contacts for a thread
251 * This is used for the participation feature.
252 * One of the parameters is a contact array.
253 * This is done to avoid duplicates.
255 * @param array $item Item that is about to be delivered
256 * @param array $contacts The previously fetched contacts
258 * @return array of relay servers
261 public static function participantsForThread(array $item, array $contacts)
263 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
267 $items = Item::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid'],
268 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
269 while ($item = DBA::fetch($items)) {
270 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
271 ['id' => $item['author-id']]);
272 if (!DBA::isResult($contact) || empty($contact['batch']) ||
273 ($contact['network'] != Protocol::DIASPORA) ||
274 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
279 foreach ($contacts as $entry) {
280 if ($entry['batch'] == $contact['batch']) {
286 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
287 $contacts[] = $contact;
296 * repairs a signature that was double encoded
298 * The function is unused at the moment. It was copied from the old implementation.
300 * @param string $signature The signature
301 * @param string $handle The handle of the signature owner
302 * @param integer $level This value is only set inside this function to avoid endless loops
304 * @return string the repaired signature
307 private static function repairSignature($signature, $handle = "", $level = 1)
309 if ($signature == "") {
313 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
314 $signature = base64_decode($signature);
315 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
317 // Do a recursive call to be able to fix even multiple levels
319 $signature = self::repairSignature($signature, $handle, ++$level);
327 * verify the envelope and return the verified data
329 * @param string $envelope The magic envelope
331 * @return string verified data
332 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
333 * @throws \ImagickException
335 private static function verifyMagicEnvelope($envelope)
337 $basedom = XML::parseString($envelope, true);
339 if (!is_object($basedom)) {
340 Logger::log("Envelope is no XML file");
344 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
346 if (sizeof($children) == 0) {
347 Logger::log("XML has no children");
353 $data = Strings::base64UrlDecode($children->data);
354 $type = $children->data->attributes()->type[0];
356 $encoding = $children->encoding;
358 $alg = $children->alg;
360 $sig = Strings::base64UrlDecode($children->sig);
361 $key_id = $children->sig->attributes()->key_id[0];
363 $handle = Strings::base64UrlDecode($key_id);
366 $b64url_data = Strings::base64UrlEncode($data);
367 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
369 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
372 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
376 $key = self::key($handle);
378 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
382 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
384 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
392 * encrypts data via AES
394 * @param string $key The AES key
395 * @param string $iv The IV (is used for CBC encoding)
396 * @param string $data The data that is to be encrypted
398 * @return string encrypted data
400 private static function aesEncrypt($key, $iv, $data)
402 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
406 * decrypts data via AES
408 * @param string $key The AES key
409 * @param string $iv The IV (is used for CBC encoding)
410 * @param string $encrypted The encrypted data
412 * @return string decrypted data
414 private static function aesDecrypt($key, $iv, $encrypted)
416 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
420 * Decodes incoming Diaspora message in the new format
422 * @param string $raw raw post message
423 * @param string $privKey The private key of the importer
424 * @param boolean $no_exit Don't do an http exit on error
427 * 'message' -> decoded Diaspora XML message
428 * 'author' -> author diaspora handle
429 * 'key' -> author public key (converted to pkcs#8)
430 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
431 * @throws \ImagickException
433 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
435 $data = json_decode($raw);
437 // Is it a private post? Then decrypt the outer Salmon
438 if (is_object($data)) {
439 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
440 $ciphertext = base64_decode($data->encrypted_magic_envelope);
442 $outer_key_bundle = '';
443 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
444 $j_outer_key_bundle = json_decode($outer_key_bundle);
446 if (!is_object($j_outer_key_bundle)) {
447 Logger::log('Outer Salmon did not verify. Discarding.');
451 throw new \Friendica\Network\HTTPException\BadRequestException();
455 $outer_iv = base64_decode($j_outer_key_bundle->iv);
456 $outer_key = base64_decode($j_outer_key_bundle->key);
458 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
463 $basedom = XML::parseString($xml, true);
465 if (!is_object($basedom)) {
466 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
470 throw new \Friendica\Network\HTTPException\BadRequestException();
474 $base = $basedom->children(ActivityNamespace::SALMON_ME);
476 // Not sure if this cleaning is needed
477 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
479 // Build the signed data
480 $type = $base->data[0]->attributes()->type[0];
481 $encoding = $base->encoding;
483 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
485 // This is the signature
486 $signature = Strings::base64UrlDecode($base->sig);
488 // Get the senders' public key
489 $key_id = $base->sig[0]->attributes()->key_id[0];
490 $author_addr = base64_decode($key_id);
491 if ($author_addr == '') {
492 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
496 throw new \Friendica\Network\HTTPException\BadRequestException();
500 $key = self::key($author_addr);
502 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
506 throw new \Friendica\Network\HTTPException\BadRequestException();
510 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
512 Logger::log('Message did not verify. Discarding.');
516 throw new \Friendica\Network\HTTPException\BadRequestException();
520 return ['message' => (string)Strings::base64UrlDecode($base->data),
521 'author' => XML::unescape($author_addr),
522 'key' => (string)$key];
526 * Decodes incoming Diaspora message in the deprecated format
528 * @param string $xml urldecoded Diaspora salmon
529 * @param string $privKey The private key of the importer
532 * 'message' -> decoded Diaspora XML message
533 * 'author' -> author diaspora handle
534 * 'key' -> author public key (converted to pkcs#8)
535 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
536 * @throws \ImagickException
538 public static function decode(string $xml, string $privKey = '')
541 $basedom = XML::parseString($xml);
543 if (!is_object($basedom)) {
544 Logger::log("XML is not parseable.");
547 $children = $basedom->children('https://joindiaspora.com/protocol');
549 $inner_aes_key = null;
552 if ($children->header) {
554 $author_link = str_replace('acct:', '', $children->header->author_id);
556 // This happens with posts from a relais
557 if (empty($privKey)) {
558 Logger::log("This is no private post in the old format", Logger::DEBUG);
562 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
564 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
565 $ciphertext = base64_decode($encrypted_header->ciphertext);
567 $outer_key_bundle = '';
568 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
570 $j_outer_key_bundle = json_decode($outer_key_bundle);
572 $outer_iv = base64_decode($j_outer_key_bundle->iv);
573 $outer_key = base64_decode($j_outer_key_bundle->key);
575 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
577 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
578 $idom = XML::parseString($decrypted);
580 $inner_iv = base64_decode($idom->iv);
581 $inner_aes_key = base64_decode($idom->aes_key);
583 $author_link = str_replace('acct:', '', $idom->author_id);
586 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
588 // figure out where in the DOM tree our data is hiding
591 if ($dom->provenance->data) {
592 $base = $dom->provenance;
593 } elseif ($dom->env->data) {
595 } elseif ($dom->data) {
600 Logger::log('unable to locate salmon data in xml');
601 throw new \Friendica\Network\HTTPException\BadRequestException();
605 // Stash the signature away for now. We have to find their key or it won't be good for anything.
606 $signature = Strings::base64UrlDecode($base->sig);
610 // strip whitespace so our data element will return to one big base64 blob
611 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
614 // stash away some other stuff for later
616 $type = $base->data[0]->attributes()->type[0];
617 $keyhash = $base->sig[0]->attributes()->keyhash[0];
618 $encoding = $base->encoding;
622 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
626 $data = Strings::base64UrlDecode($data);
630 $inner_decrypted = $data;
632 // Decode the encrypted blob
633 $inner_encrypted = base64_decode($data);
634 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
638 Logger::log('Could not retrieve author URI.');
639 throw new \Friendica\Network\HTTPException\BadRequestException();
641 // Once we have the author URI, go to the web and try to find their public key
642 // (first this will look it up locally if it is in the fcontact cache)
643 // This will also convert diaspora public key from pkcs#1 to pkcs#8
645 Logger::log('Fetching key for '.$author_link);
646 $key = self::key($author_link);
649 Logger::log('Could not retrieve author key.');
650 throw new \Friendica\Network\HTTPException\BadRequestException();
653 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
656 Logger::log('Message did not verify. Discarding.');
657 throw new \Friendica\Network\HTTPException\BadRequestException();
660 Logger::log('Message verified.');
662 return ['message' => (string)$inner_decrypted,
663 'author' => XML::unescape($author_link),
664 'key' => (string)$key];
669 * Dispatches public messages and find the fitting receivers
671 * @param array $msg The post that will be dispatched
673 * @return int The message id of the generated message, "true" or "false" if there was an error
674 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
675 * @throws \ImagickException
677 public static function dispatchPublic($msg)
679 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
681 Logger::log("diaspora is disabled");
685 if (!($fields = self::validPosting($msg))) {
686 Logger::log("Invalid posting");
690 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
691 $success = self::dispatch($importer, $msg, $fields);
697 * Dispatches the different message types to the different functions
699 * @param array $importer Array of the importer user
700 * @param array $msg The post that will be dispatched
701 * @param SimpleXMLElement $fields SimpleXML object that contains the message
703 * @return int The message id of the generated message, "true" or "false" if there was an error
704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
705 * @throws \ImagickException
707 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
709 // The sender is the handle of the contact that sent the message.
710 // This will often be different with relayed messages (for example "like" and "comment")
711 $sender = $msg["author"];
713 // This is only needed for private postings since this is already done for public ones before
714 if (is_null($fields)) {
716 if (!($fields = self::validPosting($msg))) {
717 Logger::log("Invalid posting");
724 $type = $fields->getName();
726 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
729 case "account_migration":
731 Logger::log('Message with type ' . $type . ' is not private, quitting.');
734 return self::receiveAccountMigration($importer, $fields);
736 case "account_deletion":
737 return self::receiveAccountDeletion($fields);
740 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
744 Logger::log('Message with type ' . $type . ' is not private, quitting.');
747 return self::receiveContactRequest($importer, $fields);
751 Logger::log('Message with type ' . $type . ' is not private, quitting.');
754 return self::receiveConversation($importer, $msg, $fields);
757 return self::receiveLike($importer, $sender, $fields);
761 Logger::log('Message with type ' . $type . ' is not private, quitting.');
764 return self::receiveMessage($importer, $fields);
766 case "participation":
768 Logger::log('Message with type ' . $type . ' is not private, quitting.');
771 return self::receiveParticipation($importer, $fields);
773 case "photo": // Not implemented
774 return self::receivePhoto($importer, $fields);
776 case "poll_participation": // Not implemented
777 return self::receivePollParticipation($importer, $fields);
781 Logger::log('Message with type ' . $type . ' is not private, quitting.');
784 return self::receiveProfile($importer, $fields);
787 return self::receiveReshare($importer, $fields, $msg["message"]);
790 return self::receiveRetraction($importer, $sender, $fields);
792 case "status_message":
793 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
796 Logger::log("Unknown message type ".$type);
802 * Checks if a posting is valid and fetches the data fields.
804 * This function does not only check the signature.
805 * It also does the conversion between the old and the new diaspora format.
807 * @param array $msg Array with the XML, the sender handle and the sender signature
809 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
811 * @throws \ImagickException
813 private static function validPosting($msg)
815 $data = XML::parseString($msg["message"]);
817 if (!is_object($data)) {
818 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
822 // Is this the new or the old version?
823 if ($data->getName() == "XML") {
825 foreach ($data->post->children() as $child) {
833 $type = $element->getName();
836 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
838 // All retractions are handled identically from now on.
839 // In the new version there will only be "retraction".
840 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
841 $type = "retraction";
843 if ($type == "request") {
847 $fields = new SimpleXMLElement("<".$type."/>");
850 $author_signature = null;
851 $parent_author_signature = null;
853 foreach ($element->children() as $fieldname => $entry) {
855 // Translation for the old XML structure
856 if ($fieldname == "diaspora_handle") {
857 $fieldname = "author";
859 if ($fieldname == "participant_handles") {
860 $fieldname = "participants";
862 if (in_array($type, ["like", "participation"])) {
863 if ($fieldname == "target_type") {
864 $fieldname = "parent_type";
867 if ($fieldname == "sender_handle") {
868 $fieldname = "author";
870 if ($fieldname == "recipient_handle") {
871 $fieldname = "recipient";
873 if ($fieldname == "root_diaspora_id") {
874 $fieldname = "root_author";
876 if ($type == "status_message") {
877 if ($fieldname == "raw_message") {
881 if ($type == "retraction") {
882 if ($fieldname == "post_guid") {
883 $fieldname = "target_guid";
885 if ($fieldname == "type") {
886 $fieldname = "target_type";
891 if (($fieldname == "author_signature") && ($entry != "")) {
892 $author_signature = base64_decode($entry);
893 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
894 $parent_author_signature = base64_decode($entry);
895 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
896 if ($signed_data != "") {
900 $signed_data .= $entry;
902 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
903 || ($orig_type == "relayable_retraction")
905 XML::copy($entry, $fields, $fieldname);
909 // This is something that shouldn't happen at all.
910 if (in_array($type, ["status_message", "reshare", "profile"])) {
911 if ($msg["author"] != $fields->author) {
912 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
917 // Only some message types have signatures. So we quit here for the other types.
918 if (!in_array($type, ["comment", "like"])) {
921 // No author_signature? This is a must, so we quit.
922 if (!isset($author_signature)) {
923 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
927 if (isset($parent_author_signature)) {
928 $key = self::key($msg["author"]);
930 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
934 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
935 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);
940 $key = self::key($fields->author);
942 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
946 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
947 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);
955 * Fetches the public key for a given handle
957 * @param string $handle The handle
959 * @return string The public key
960 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
961 * @throws \ImagickException
963 private static function key($handle)
965 $handle = strval($handle);
967 Logger::log("Fetching diaspora key for: ".$handle);
969 $r = self::personByHandle($handle);
978 * Fetches data for a given handle
980 * @param string $handle The handle
981 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
983 * @return array the queried data
984 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
985 * @throws \ImagickException
987 public static function personByHandle($handle, $update = null)
989 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
990 if (!DBA::isResult($person)) {
991 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
992 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
995 if (DBA::isResult($person)) {
996 Logger::debug("In cache " . print_r($person, true));
998 if (is_null($update)) {
999 // update record occasionally so it doesn't get stale
1000 $d = strtotime($person["updated"]." +00:00");
1001 if ($d < strtotime("now - 14 days")) {
1005 if ($person["guid"] == "") {
1009 } elseif (is_null($update)) {
1010 $update = !DBA::isResult($person);
1016 Logger::log("create or refresh", Logger::DEBUG);
1017 $r = Probe::uri($handle, Protocol::DIASPORA);
1019 // Note that Friendica contacts will return a "Diaspora person"
1020 // if Diaspora connectivity is enabled on their server
1021 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1022 self::updateFContact($r);
1024 $person = self::personByHandle($handle, false);
1032 * Updates the fcontact table
1034 * @param array $arr The fcontact data
1035 * @throws \Exception
1037 private static function updateFContact($arr)
1039 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1040 'request' => $arr["request"], 'nick' => $arr["nick"],
1041 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1042 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1043 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1044 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1045 'updated' => DateTimeFormat::utcNow()];
1047 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1049 DBA::update('fcontact', $fields, $condition, true);
1053 * get a handle (user@domain.tld) from a given contact id
1055 * @param int $contact_id The id in the contact table
1056 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1058 * @return string the handle
1059 * @throws \Exception
1061 private static function handleFromContact($contact_id, $pcontact_id = 0)
1065 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1067 if ($pcontact_id != 0) {
1068 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1070 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1071 return strtolower($contact["addr"]);
1076 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1080 if (DBA::isResult($r)) {
1083 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1085 if ($contact['addr'] != "") {
1086 $handle = $contact['addr'];
1088 $baseurl_start = strpos($contact['url'], '://') + 3;
1089 // allows installations in a subdirectory--not sure how Diaspora will handle
1090 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1091 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1092 $handle = $contact['nick'].'@'.$baseurl;
1096 return strtolower($handle);
1100 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1103 * @param mixed $fcontact_guid Hexadecimal string guid
1105 * @return string the contact url or null
1106 * @throws \Exception
1108 public static function urlFromContactGuid($fcontact_guid)
1110 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1113 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1114 DBA::escape(Protocol::DIASPORA),
1115 DBA::escape($fcontact_guid)
1118 if (DBA::isResult($r)) {
1119 return $r[0]['url'];
1126 * Get a contact id for a given handle
1128 * @todo Move to Friendica\Model\Contact
1130 * @param int $uid The user id
1131 * @param string $handle The handle in the format user@domain.tld
1133 * @return array Contact data
1134 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1135 * @throws \ImagickException
1137 private static function contactByHandle($uid, $handle)
1139 $cid = Contact::getIdForURL($handle, $uid);
1141 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1145 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1146 if (!DBA::isResult($contact)) {
1147 // This here shouldn't happen at all
1148 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1156 * Checks if the given contact url does support ActivityPub
1158 * @param string $url profile url
1159 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1161 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1162 * @throws \ImagickException
1164 public static function isSupportedByContactUrl($url, $update = null)
1166 return !empty(self::personByHandle($url, $update));
1170 * Check if posting is allowed for this contact
1172 * @param array $importer Array of the importer user
1173 * @param array $contact The contact that is checked
1174 * @param bool $is_comment Is the check for a comment?
1176 * @return bool is the contact allowed to post?
1178 private static function postAllow(array $importer, array $contact, $is_comment = false)
1181 * Perhaps we were already sharing with this person. Now they're sharing with us.
1182 * That makes us friends.
1183 * Normally this should have handled by getting a request - but this could get lost
1185 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1186 // It is not removed by now. Possibly the code is needed?
1187 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1190 // array('rel' => Contact::FRIEND, 'writable' => true),
1191 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1194 // $contact["rel"] = Contact::FRIEND;
1195 // Logger::log("defining user ".$contact["nick"]." as friend");
1198 // Contact server is blocked
1199 if (Network::isUrlBlocked($contact['url'])) {
1201 // We don't seem to like that person
1202 } elseif ($contact["blocked"]) {
1203 // Maybe blocked, don't accept.
1205 // We are following this person?
1206 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1207 // Yes, then it is fine.
1209 // Is it a post to a community?
1210 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1213 // Is the message a global user or a comment?
1214 } elseif (($importer["uid"] == 0) || $is_comment) {
1215 // Messages for the global users and comments are always accepted
1223 * Fetches the contact id for a handle and checks if posting is allowed
1225 * @param array $importer Array of the importer user
1226 * @param string $handle The checked handle in the format user@domain.tld
1227 * @param bool $is_comment Is the check for a comment?
1229 * @return array The contact data
1230 * @throws \Exception
1232 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1234 $contact = self::contactByHandle($importer["uid"], $handle);
1236 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1237 // If a contact isn't found, we accept it anyway if it is a comment
1238 if ($is_comment && ($importer["uid"] != 0)) {
1239 return self::contactByHandle(0, $handle);
1240 } elseif ($is_comment) {
1247 if (!self::postAllow($importer, $contact, $is_comment)) {
1248 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1255 * Does the message already exists on the system?
1257 * @param int $uid The user id
1258 * @param string $guid The guid of the message
1260 * @return int|bool message id if the message already was stored into the system - or false.
1261 * @throws \Exception
1263 private static function messageExists($uid, $guid)
1265 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1266 if (DBA::isResult($item)) {
1267 Logger::log("message ".$guid." already exists for user ".$uid);
1275 * Checks for links to posts in a message
1277 * @param array $item The item array
1280 private static function fetchGuid(array $item)
1282 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1283 preg_replace_callback(
1285 function ($match) use ($item) {
1286 self::fetchGuidSub($match, $item);
1291 preg_replace_callback(
1292 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1293 function ($match) use ($item) {
1294 self::fetchGuidSub($match, $item);
1301 * Checks for relative /people/* links in an item body to match local
1302 * contacts or prepends the remote host taken from the author link.
1304 * @param string $body The item body to replace links from
1305 * @param string $author_link The author link for missing local contact fallback
1307 * @return string the replaced string
1309 public static function replacePeopleGuid($body, $author_link)
1311 $return = preg_replace_callback(
1312 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1313 function ($match) use ($author_link) {
1315 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1316 // 1 => '0123456789abcdef'
1318 $handle = self::urlFromContactGuid($match[1]);
1321 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1323 // No local match, restoring absolute remote URL from author scheme and host
1324 $author_url = parse_url($author_link);
1325 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1337 * sub function of "fetchGuid" which checks for links in messages
1339 * @param array $match array containing a link that has to be checked for a message link
1340 * @param array $item The item array
1342 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1343 * @throws \ImagickException
1345 private static function fetchGuidSub($match, $item)
1347 if (!self::storeByGuid($match[1], $item["author-link"])) {
1348 self::storeByGuid($match[1], $item["owner-link"]);
1353 * Fetches an item with a given guid from a given server
1355 * @param string $guid the message guid
1356 * @param string $server The server address
1357 * @param int $uid The user id of the user
1359 * @return int the message id of the stored message or false
1360 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1361 * @throws \ImagickException
1363 private static function storeByGuid($guid, $server, $uid = 0)
1365 $serverparts = parse_url($server);
1367 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1371 $server = $serverparts["scheme"]."://".$serverparts["host"];
1373 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1375 $msg = self::message($guid, $server);
1381 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1383 // Now call the dispatcher
1384 return self::dispatchPublic($msg);
1388 * Fetches a message from a server
1390 * @param string $guid message guid
1391 * @param string $server The url of the server
1392 * @param int $level Endless loop prevention
1395 * 'message' => The message XML
1396 * 'author' => The author handle
1397 * 'key' => The public key of the author
1398 * @throws \Exception
1400 private static function message($guid, $server, $level = 0)
1406 // This will work for new Diaspora servers and Friendica servers from 3.5
1407 $source_url = $server."/fetch/post/".urlencode($guid);
1409 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1411 $envelope = Network::fetchUrl($source_url);
1413 Logger::log("Envelope was fetched.", Logger::DEBUG);
1414 $x = self::verifyMagicEnvelope($envelope);
1416 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1418 Logger::log("Envelope was verified.", Logger::DEBUG);
1428 $source_xml = XML::parseString($x);
1430 if (!is_object($source_xml)) {
1434 if ($source_xml->post->reshare) {
1435 // Reshare of a reshare - old Diaspora version
1436 Logger::log("Message is a reshare", Logger::DEBUG);
1437 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1438 } elseif ($source_xml->getName() == "reshare") {
1439 // Reshare of a reshare - new Diaspora version
1440 Logger::log("Message is a new reshare", Logger::DEBUG);
1441 return self::message($source_xml->root_guid, $server, ++$level);
1446 // Fetch the author - for the old and the new Diaspora version
1447 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1448 $author = (string)$source_xml->post->status_message->diaspora_handle;
1449 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1450 $author = (string)$source_xml->author;
1453 // If this isn't a "status_message" then quit
1455 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1459 $msg = ["message" => $x, "author" => $author];
1461 $msg["key"] = self::key($msg["author"]);
1467 * Fetches an item with a given URL
1469 * @param string $url the message url
1471 * @return int the message id of the stored message or false
1472 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1473 * @throws \ImagickException
1475 public static function fetchByURL($url, $uid = 0)
1477 // Check for Diaspora (and Friendica) typical paths
1478 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1479 Logger::info('Invalid url', ['url' => $url]);
1483 $guid = urldecode($matches[2]);
1485 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1486 if (DBA::isResult($item)) {
1487 Logger::info('Found', ['id' => $item['id']]);
1491 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1492 $ret = self::storeByGuid($guid, $matches[1], $uid);
1493 Logger::info('Result', ['ret' => $ret]);
1495 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1496 if (DBA::isResult($item)) {
1497 Logger::info('Found', ['id' => $item['id']]);
1500 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1506 * Fetches the item record of a given guid
1508 * @param int $uid The user id
1509 * @param string $guid message guid
1510 * @param string $author The handle of the item
1511 * @param array $contact The contact of the item owner
1513 * @return array the item record
1514 * @throws \Exception
1516 private static function parentItem($uid, $guid, $author, array $contact)
1518 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1519 'author-name', 'author-link', 'author-avatar',
1520 'owner-name', 'owner-link', 'owner-avatar'];
1521 $condition = ['uid' => $uid, 'guid' => $guid];
1522 $item = Item::selectFirst($fields, $condition);
1524 if (!DBA::isResult($item)) {
1525 $person = self::personByHandle($author);
1526 $result = self::storeByGuid($guid, $person["url"], $uid);
1528 // We don't have an url for items that arrived at the public dispatcher
1529 if (!$result && !empty($contact["url"])) {
1530 $result = self::storeByGuid($guid, $contact["url"], $uid);
1534 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1536 $item = Item::selectFirst($fields, $condition);
1540 if (!DBA::isResult($item)) {
1541 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1544 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1550 * returns contact details
1552 * @param array $def_contact The default contact if the person isn't found
1553 * @param array $person The record of the person
1554 * @param int $uid The user id
1557 * 'cid' => contact id
1558 * 'network' => network type
1559 * @throws \Exception
1561 private static function authorContactByUrl($def_contact, $person, $uid)
1563 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1564 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1565 if (DBA::isResult($contact)) {
1566 $cid = $contact["id"];
1567 $network = $contact["network"];
1569 $cid = $def_contact["id"];
1570 $network = Protocol::DIASPORA;
1573 return ["cid" => $cid, "network" => $network];
1577 * Is the profile a hubzilla profile?
1579 * @param string $url The profile link
1581 * @return bool is it a hubzilla server?
1583 private static function isHubzilla($url)
1585 return(strstr($url, '/channel/'));
1589 * Generate a post link with a given handle and message guid
1591 * @param string $addr The user handle
1592 * @param string $guid message guid
1593 * @param string $parent_guid optional parent guid
1595 * @return string the post link
1596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1597 * @throws \ImagickException
1599 private static function plink($addr, $guid, $parent_guid = '')
1601 $contact = Contact::getDetailsByAddr($addr);
1602 if (empty($contact)) {
1603 Logger::info('No contact data for address', ['addr' => $addr]);
1607 if (empty($contact['baseurl'])) {
1608 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1609 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1613 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1614 if (!empty($gserver['platform'])) {
1615 $platform = strtolower($gserver['platform']);
1616 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1619 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1620 if (self::isHubzilla($contact['url'])) {
1621 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1622 $platform = 'hubzilla';
1623 } elseif ($contact['network'] == Protocol::DFRN) {
1624 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1625 $platform = 'friendica';
1629 if ($platform == 'friendica') {
1630 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1633 if ($platform == 'hubzilla') {
1634 return $contact['baseurl'] . '/item/' . $guid;
1637 if ($platform == 'socialhome') {
1638 return $contact['baseurl'] . '/content/' . $guid;
1641 if ($platform != 'diaspora') {
1642 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1646 if ($parent_guid != '') {
1647 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1649 return $contact['baseurl'] . '/posts/' . $guid;
1654 * Receives account migration
1656 * @param array $importer Array of the importer user
1657 * @param object $data The message object
1659 * @return bool Success
1660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1661 * @throws \ImagickException
1663 private static function receiveAccountMigration(array $importer, $data)
1665 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1666 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1667 $signature = Strings::escapeTags(XML::unescape($data->signature));
1669 $contact = self::contactByHandle($importer["uid"], $old_handle);
1671 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1675 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1678 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1679 $key = self::key($old_handle);
1680 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1681 Logger::log('No valid signature for migration.');
1685 // Update the profile
1686 self::receiveProfile($importer, $data->profile);
1688 // change the technical stuff in contact and gcontact
1689 $data = Probe::uri($new_handle);
1690 if ($data['network'] == Protocol::PHANTOM) {
1691 Logger::log('Account for '.$new_handle." couldn't be probed.");
1695 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1696 'name' => $data['name'], 'nick' => $data['nick'],
1697 'addr' => $data['addr'], 'batch' => $data['batch'],
1698 'notify' => $data['notify'], 'poll' => $data['poll'],
1699 'network' => $data['network']];
1701 DBA::update('contact', $fields, ['addr' => $old_handle]);
1703 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1704 'name' => $data['name'], 'nick' => $data['nick'],
1705 'addr' => $data['addr'], 'connect' => $data['addr'],
1706 'notify' => $data['notify'], 'photo' => $data['photo'],
1707 'server_url' => $data['baseurl'], 'network' => $data['network']];
1709 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1711 Logger::log('Contacts are updated.');
1717 * Processes an account deletion
1719 * @param object $data The message object
1721 * @return bool Success
1722 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1724 private static function receiveAccountDeletion($data)
1726 $author = Strings::escapeTags(XML::unescape($data->author));
1728 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1729 while ($contact = DBA::fetch($contacts)) {
1730 Contact::remove($contact["id"]);
1732 DBA::close($contacts);
1734 DBA::delete('gcontact', ['addr' => $author]);
1736 Logger::log('Removed contacts for ' . $author);
1742 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1744 * @param string $author Author handle
1745 * @param string $guid Message guid
1746 * @param boolean $onlyfound Only return uri when found in the database
1748 * @return string The constructed uri or the one from our database
1749 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1750 * @throws \ImagickException
1752 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1754 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1755 if (DBA::isResult($item)) {
1756 return $item["uri"];
1757 } elseif (!$onlyfound) {
1758 $person = self::personByHandle($author);
1760 $parts = parse_url($person['url']);
1761 unset($parts['path']);
1762 $host_url = Network::unparseURL($parts);
1764 return $host_url . '/objects/' . $guid;
1771 * Fetch the guid from our database with a given uri
1773 * @param string $uri Message uri
1774 * @param string $uid Author handle
1776 * @return string The post guid
1777 * @throws \Exception
1779 private static function getGuidFromUri($uri, $uid)
1781 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1782 if (DBA::isResult($item)) {
1783 return $item["guid"];
1790 * Find the best importer for a comment, like, ...
1792 * @param string $guid The guid of the item
1794 * @return array|boolean the origin owner of that post - or false
1795 * @throws \Exception
1797 private static function importerForGuid($guid)
1799 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1800 if (DBA::isResult($item)) {
1801 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1802 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1803 if (DBA::isResult($contact)) {
1811 * Store the mentions in the tag table
1813 * @param integer $uriid
1814 * @param string $text
1816 private static function storeMentions(int $uriid, string $text)
1818 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1819 if (empty($matches)) {
1824 * Matching values for the preg match
1825 * [1] = mention type (@ or !)
1826 * [2] = name (optional)
1830 foreach ($matches as $match) {
1831 if (empty($match)) {
1835 $person = self::personByHandle($match[3]);
1836 if (empty($person)) {
1840 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1845 * Processes an incoming comment
1847 * @param array $importer Array of the importer user
1848 * @param string $sender The sender of the message
1849 * @param object $data The message object
1850 * @param string $xml The original XML of the message
1852 * @return int The message id of the generated comment or "false" if there was an error
1853 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1854 * @throws \ImagickException
1856 private static function receiveComment(array $importer, $sender, $data, $xml)
1858 $author = Strings::escapeTags(XML::unescape($data->author));
1859 $guid = Strings::escapeTags(XML::unescape($data->guid));
1860 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1861 $text = XML::unescape($data->text);
1863 if (isset($data->created_at)) {
1864 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1866 $created_at = DateTimeFormat::utcNow();
1869 if (isset($data->thread_parent_guid)) {
1870 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1871 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1876 $contact = self::allowedContactByHandle($importer, $sender, true);
1881 $message_id = self::messageExists($importer["uid"], $guid);
1886 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1887 if (!$parent_item) {
1891 $person = self::personByHandle($author);
1892 if (!is_array($person)) {
1893 Logger::log("unable to find author details");
1897 // Fetch the contact id - if we know this contact
1898 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1902 $datarray["uid"] = $importer["uid"];
1903 $datarray["contact-id"] = $author_contact["cid"];
1904 $datarray["network"] = $author_contact["network"];
1906 $datarray["author-link"] = $person["url"];
1907 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1909 $datarray["owner-link"] = $contact["url"];
1910 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1912 $datarray["guid"] = $guid;
1913 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1914 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1916 $datarray["verb"] = Activity::POST;
1917 $datarray["gravity"] = GRAVITY_COMMENT;
1919 if ($thr_uri != "") {
1920 $datarray["parent-uri"] = $thr_uri;
1922 $datarray["parent-uri"] = $parent_item["uri"];
1925 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1927 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1928 $datarray["source"] = $xml;
1930 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1932 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1933 $body = Markdown::toBBCode($text);
1935 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1937 self::storeMentions($datarray['uri-id'], $text);
1938 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1940 self::fetchGuid($datarray);
1942 // If we are the origin of the parent we store the original data.
1943 // We notify our followers during the item storage.
1944 if ($parent_item["origin"]) {
1945 $datarray['diaspora_signed_text'] = json_encode($data);
1948 $message_id = Item::insert($datarray);
1950 if ($message_id <= 0) {
1955 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1956 if ($datarray['uid'] == 0) {
1957 Item::distribute($message_id, json_encode($data));
1965 * processes and stores private messages
1967 * @param array $importer Array of the importer user
1968 * @param array $contact The contact of the message
1969 * @param object $data The message object
1970 * @param array $msg Array of the processed message, author handle and key
1971 * @param object $mesg The private message
1972 * @param array $conversation The conversation record to which this message belongs
1974 * @return bool "true" if it was successful
1975 * @throws \Exception
1977 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1979 $author = Strings::escapeTags(XML::unescape($data->author));
1980 $guid = Strings::escapeTags(XML::unescape($data->guid));
1981 $subject = Strings::escapeTags(XML::unescape($data->subject));
1983 // "diaspora_handle" is the element name from the old version
1984 // "author" is the element name from the new version
1985 if ($mesg->author) {
1986 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1987 } elseif ($mesg->diaspora_handle) {
1988 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1993 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1994 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1995 $msg_text = XML::unescape($mesg->text);
1996 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1998 if ($msg_conversation_guid != $guid) {
1999 Logger::log("message conversation guid does not belong to the current conversation.");
2003 $body = Markdown::toBBCode($msg_text);
2004 $message_uri = $msg_author.":".$msg_guid;
2006 $person = self::personByHandle($msg_author);
2008 return Mail::insert([
2009 'uid' => $importer['uid'],
2010 'guid' => $msg_guid,
2011 'convid' => $conversation['id'],
2012 'from-name' => $person['name'],
2013 'from-photo' => $person['photo'],
2014 'from-url' => $person['url'],
2015 'contact-id' => $contact['id'],
2016 'title' => $subject,
2018 'uri' => $message_uri,
2019 'parent-uri' => $author . ':' . $guid,
2020 'created' => $msg_created_at
2025 * Processes new private messages (answers to private messages are processed elsewhere)
2027 * @param array $importer Array of the importer user
2028 * @param array $msg Array of the processed message, author handle and key
2029 * @param object $data The message object
2031 * @return bool Success
2032 * @throws \Exception
2034 private static function receiveConversation(array $importer, $msg, $data)
2036 $author = Strings::escapeTags(XML::unescape($data->author));
2037 $guid = Strings::escapeTags(XML::unescape($data->guid));
2038 $subject = Strings::escapeTags(XML::unescape($data->subject));
2039 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2040 $participants = Strings::escapeTags(XML::unescape($data->participants));
2042 $messages = $data->message;
2044 if (!count($messages)) {
2045 Logger::log("empty conversation");
2049 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2054 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2055 if (!DBA::isResult($conversation)) {
2057 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2058 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2059 intval($importer["uid"]),
2061 DBA::escape($author),
2062 DBA::escape($created_at),
2063 DBA::escape(DateTimeFormat::utcNow()),
2064 DBA::escape($subject),
2065 DBA::escape($participants)
2068 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2071 if (!$conversation) {
2072 Logger::log("unable to create conversation.");
2076 foreach ($messages as $mesg) {
2077 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2084 * Processes "like" messages
2086 * @param array $importer Array of the importer user
2087 * @param string $sender The sender of the message
2088 * @param object $data The message object
2090 * @return int The message id of the generated like or "false" if there was an error
2091 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2092 * @throws \ImagickException
2094 private static function receiveLike(array $importer, $sender, $data)
2096 $author = Strings::escapeTags(XML::unescape($data->author));
2097 $guid = Strings::escapeTags(XML::unescape($data->guid));
2098 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2099 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2100 $positive = Strings::escapeTags(XML::unescape($data->positive));
2102 // likes on comments aren't supported by Diaspora - only on posts
2103 // But maybe this will be supported in the future, so we will accept it.
2104 if (!in_array($parent_type, ["Post", "Comment"])) {
2108 $contact = self::allowedContactByHandle($importer, $sender, true);
2113 $message_id = self::messageExists($importer["uid"], $guid);
2118 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2119 if (!$parent_item) {
2123 $person = self::personByHandle($author);
2124 if (!is_array($person)) {
2125 Logger::log("unable to find author details");
2129 // Fetch the contact id - if we know this contact
2130 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2132 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2133 // We would accept this anyhow.
2134 if ($positive == "true") {
2135 $verb = Activity::LIKE;
2137 $verb = Activity::DISLIKE;
2142 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2144 $datarray["uid"] = $importer["uid"];
2145 $datarray["contact-id"] = $author_contact["cid"];
2146 $datarray["network"] = $author_contact["network"];
2148 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2149 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2151 $datarray["guid"] = $guid;
2152 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2154 $datarray["verb"] = $verb;
2155 $datarray["gravity"] = GRAVITY_ACTIVITY;
2156 $datarray["parent-uri"] = $parent_item["uri"];
2158 $datarray["object-type"] = Activity\ObjectType::NOTE;
2160 $datarray["body"] = $verb;
2162 // Diaspora doesn't provide a date for likes
2163 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2165 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2166 if ($parent_item["id"] != $parent_item["parent"]) {
2167 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2168 $origin = $toplevel["origin"];
2170 $origin = $parent_item["origin"];
2173 // If we are the origin of the parent we store the original data.
2174 // We notify our followers during the item storage.
2176 $datarray['diaspora_signed_text'] = json_encode($data);
2179 $message_id = Item::insert($datarray);
2181 if ($message_id <= 0) {
2186 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2187 if ($datarray['uid'] == 0) {
2188 Item::distribute($message_id, json_encode($data));
2196 * Processes private messages
2198 * @param array $importer Array of the importer user
2199 * @param object $data The message object
2201 * @return bool Success?
2202 * @throws \Exception
2204 private static function receiveMessage(array $importer, $data)
2206 $author = Strings::escapeTags(XML::unescape($data->author));
2207 $guid = Strings::escapeTags(XML::unescape($data->guid));
2208 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2209 $text = XML::unescape($data->text);
2210 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2212 $contact = self::allowedContactByHandle($importer, $author, true);
2217 $conversation = null;
2219 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2220 $conversation = DBA::selectFirst('conv', [], $condition);
2222 if (!DBA::isResult($conversation)) {
2223 Logger::log("conversation not available.");
2227 $message_uri = $author.":".$guid;
2229 $person = self::personByHandle($author);
2231 Logger::log("unable to find author details");
2235 $body = Markdown::toBBCode($text);
2237 $body = self::replacePeopleGuid($body, $person["url"]);
2239 return Mail::insert([
2240 'uid' => $importer['uid'],
2242 'convid' => $conversation['id'],
2243 'from-name' => $person['name'],
2244 'from-photo' => $person['photo'],
2245 'from-url' => $person['url'],
2246 'contact-id' => $contact['id'],
2247 'title' => $conversation['subject'],
2250 'uri' => $message_uri,
2251 'parent-uri' => $author.":".$conversation['guid'],
2252 'created' => $created_at
2257 * Processes participations - unsupported by now
2259 * @param array $importer Array of the importer user
2260 * @param object $data The message object
2262 * @return bool success
2263 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2264 * @throws \ImagickException
2266 private static function receiveParticipation(array $importer, $data)
2268 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2269 $guid = Strings::escapeTags(XML::unescape($data->guid));
2270 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2272 $contact = self::allowedContactByHandle($importer, $author, true);
2277 if (self::messageExists($importer["uid"], $guid)) {
2281 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2282 if (!$parent_item) {
2286 if (!in_array($parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
2287 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2291 $person = self::personByHandle($author);
2292 if (!is_array($person)) {
2293 Logger::log("Person not found: ".$author);
2297 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2299 // Store participation
2302 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2304 $datarray["uid"] = $importer["uid"];
2305 $datarray["contact-id"] = $author_contact["cid"];
2306 $datarray["network"] = $author_contact["network"];
2308 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2309 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2311 $datarray["guid"] = $guid;
2312 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2314 $datarray["verb"] = Activity::FOLLOW;
2315 $datarray["gravity"] = GRAVITY_ACTIVITY;
2316 $datarray["parent-uri"] = $parent_item["uri"];
2318 $datarray["object-type"] = Activity\ObjectType::NOTE;
2320 $datarray["body"] = Activity::FOLLOW;
2322 // Diaspora doesn't provide a date for a participation
2323 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2325 $message_id = Item::insert($datarray);
2327 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2329 // Send all existing comments and likes to the requesting server
2330 $comments = Item::select(['id', 'uri-id', 'parent'], ['parent' => $parent_item['id']]);
2331 while ($comment = Item::fetch($comments)) {
2332 if ($comment['id'] == $comment['parent']) {
2336 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2337 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2338 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2341 DBA::close($comments);
2347 * Processes photos - unneeded
2349 * @param array $importer Array of the importer user
2350 * @param object $data The message object
2352 * @return bool always true
2354 private static function receivePhoto(array $importer, $data)
2356 // There doesn't seem to be a reason for this function,
2357 // since the photo data is transmitted in the status message as well
2362 * Processes poll participations - unssupported
2364 * @param array $importer Array of the importer user
2365 * @param object $data The message object
2367 * @return bool always true
2369 private static function receivePollParticipation(array $importer, $data)
2371 // We don't support polls by now
2376 * Processes incoming profile updates
2378 * @param array $importer Array of the importer user
2379 * @param object $data The message object
2381 * @return bool Success
2382 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2383 * @throws \ImagickException
2385 private static function receiveProfile(array $importer, $data)
2387 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2389 $contact = self::contactByHandle($importer["uid"], $author);
2394 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2395 $image_url = XML::unescape($data->image_url);
2396 $birthday = XML::unescape($data->birthday);
2397 $about = Markdown::toBBCode(XML::unescape($data->bio));
2398 $location = Markdown::toBBCode(XML::unescape($data->location));
2399 $searchable = (XML::unescape($data->searchable) == "true");
2400 $nsfw = (XML::unescape($data->nsfw) == "true");
2401 $tags = XML::unescape($data->tag_string);
2403 $tags = explode("#", $tags);
2406 foreach ($tags as $tag) {
2407 $tag = trim(strtolower($tag));
2413 $keywords = implode(", ", $keywords);
2415 $handle_parts = explode("@", $author);
2416 $nick = $handle_parts[0];
2419 $name = $handle_parts[0];
2422 if (preg_match("|^https?://|", $image_url) === 0) {
2423 $image_url = "http://".$handle_parts[1].$image_url;
2426 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2428 // Generic birthday. We don't know the timezone. The year is irrelevant.
2430 $birthday = str_replace("1000", "1901", $birthday);
2432 if ($birthday != "") {
2433 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2436 // this is to prevent multiple birthday notifications in a single year
2437 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2439 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2440 $birthday = $contact["bd"];
2443 $fields = ['name' => $name, 'location' => $location,
2444 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2445 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2446 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2448 if (!empty($birthday)) {
2449 $fields['bd'] = $birthday;
2452 DBA::update('contact', $fields, ['id' => $contact['id']]);
2454 // @todo Update the public contact, then update the gcontact from that
2456 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2457 "photo" => $image_url, "name" => $name, "location" => $location,
2458 "about" => $about, "birthday" => $birthday,
2459 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2460 "hide" => !$searchable, "nsfw" => $nsfw];
2462 $gcid = GContact::update($gcontact);
2464 GContact::link($gcid, $importer["uid"], $contact["id"]);
2466 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2472 * Processes incoming friend requests
2474 * @param array $importer Array of the importer user
2475 * @param array $contact The contact that send the request
2477 * @throws \Exception
2479 private static function receiveRequestMakeFriend(array $importer, array $contact)
2481 if ($contact["rel"] == Contact::SHARING) {
2484 ['rel' => Contact::FRIEND, 'writable' => true],
2485 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2491 * Processes incoming sharing notification
2493 * @param array $importer Array of the importer user
2494 * @param object $data The message object
2496 * @return bool Success
2497 * @throws \Exception
2499 private static function receiveContactRequest(array $importer, $data)
2501 $author = XML::unescape($data->author);
2502 $recipient = XML::unescape($data->recipient);
2504 if (!$author || !$recipient) {
2508 // the current protocol version doesn't know these fields
2509 // That means that we will assume their existance
2510 if (isset($data->following)) {
2511 $following = (XML::unescape($data->following) == "true");
2516 if (isset($data->sharing)) {
2517 $sharing = (XML::unescape($data->sharing) == "true");
2522 $contact = self::contactByHandle($importer["uid"], $author);
2524 // perhaps we were already sharing with this person. Now they're sharing with us.
2525 // That makes us friends.
2528 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2529 self::receiveRequestMakeFriend($importer, $contact);
2531 // refetch the contact array
2532 $contact = self::contactByHandle($importer["uid"], $author);
2534 // If we are now friends, we are sending a share message.
2535 // Normally we needn't to do so, but the first message could have been vanished.
2536 if (in_array($contact["rel"], [Contact::FRIEND])) {
2537 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2538 if (DBA::isResult($user)) {
2539 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2540 self::sendShare($user, $contact);
2545 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2546 Contact::removeFollower($importer, $contact);
2551 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2552 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2554 } elseif (!$following && !$sharing) {
2555 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2557 } elseif (!$following && $sharing) {
2558 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2559 } elseif ($following && $sharing) {
2560 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2561 } elseif ($following && !$sharing) {
2562 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2565 $ret = self::personByHandle($author);
2567 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2568 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2572 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2574 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2579 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2580 'author-link' => $ret['url']];
2582 $result = Contact::addRelationship($importer, $contact, $item, false);
2583 if ($result === true) {
2584 $contact_record = self::contactByHandle($importer['uid'], $author);
2585 if (!$contact_record) {
2586 Logger::info('unable to locate newly created contact record.');
2590 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2591 if (DBA::isResult($user)) {
2592 self::sendShare($user, $contact_record);
2594 // Send the profile data, maybe it weren't transmitted before
2595 self::sendProfile($importer['uid'], [$contact_record]);
2603 * Fetches a message with a given guid
2605 * @param string $guid message guid
2606 * @param string $orig_author handle of the original post
2607 * @return array The fetched item
2608 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2609 * @throws \ImagickException
2611 public static function originalItem($guid, $orig_author)
2614 Logger::log('Empty guid. Quitting.');
2618 // Do we already have this item?
2619 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2620 'author-name', 'author-link', 'author-avatar'];
2621 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2622 $item = Item::selectFirst($fields, $condition);
2624 if (DBA::isResult($item)) {
2625 Logger::log("reshared message ".$guid." already exists on system.");
2627 // Maybe it is already a reshared item?
2628 // Then refetch the content, if it is a reshare from a reshare.
2629 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2630 if (self::isReshare($item["body"], true)) {
2632 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2633 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2635 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2637 // Add OEmbed and other information to the body
2638 $item["body"] = add_page_info_to_body($item["body"], false, true);
2646 if (!DBA::isResult($item)) {
2647 if (empty($orig_author)) {
2648 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2652 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2653 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2654 $stored = self::storeByGuid($guid, $server);
2657 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2658 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2659 $stored = self::storeByGuid($guid, $server);
2663 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2664 'author-name', 'author-link', 'author-avatar'];
2665 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2666 $item = Item::selectFirst($fields, $condition);
2668 if (DBA::isResult($item)) {
2669 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2670 if (self::isReshare($item["body"], false)) {
2671 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2672 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2683 * Stores a reshare activity
2685 * @param array $item Array of reshare post
2686 * @param integer $parent_message_id Id of the parent post
2687 * @param string $guid GUID string of reshare action
2688 * @param string $author Author handle
2690 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2692 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2696 $datarray['uid'] = $item['uid'];
2697 $datarray['contact-id'] = $item['contact-id'];
2698 $datarray['network'] = $item['network'];
2700 $datarray['author-link'] = $item['author-link'];
2701 $datarray['author-id'] = $item['author-id'];
2703 $datarray['owner-link'] = $datarray['author-link'];
2704 $datarray['owner-id'] = $datarray['author-id'];
2706 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2707 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2708 $datarray['parent-uri'] = $parent['uri'];
2710 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2711 $datarray['gravity'] = GRAVITY_ACTIVITY;
2712 $datarray['object-type'] = Activity\ObjectType::NOTE;
2714 $datarray['protocol'] = $item['protocol'];
2716 $datarray['plink'] = self::plink($author, $datarray['guid']);
2717 $datarray['private'] = $item['private'];
2718 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2720 $message_id = Item::insert($datarray);
2723 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2724 if ($datarray['uid'] == 0) {
2725 Item::distribute($message_id);
2731 * Processes a reshare message
2733 * @param array $importer Array of the importer user
2734 * @param object $data The message object
2735 * @param string $xml The original XML of the message
2737 * @return int the message id
2738 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2739 * @throws \ImagickException
2741 private static function receiveReshare(array $importer, $data, $xml)
2743 $author = Strings::escapeTags(XML::unescape($data->author));
2744 $guid = Strings::escapeTags(XML::unescape($data->guid));
2745 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2746 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2747 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2748 /// @todo handle unprocessed property "provider_display_name"
2749 $public = Strings::escapeTags(XML::unescape($data->public));
2751 $contact = self::allowedContactByHandle($importer, $author, false);
2756 $message_id = self::messageExists($importer["uid"], $guid);
2761 $original_item = self::originalItem($root_guid, $root_author);
2762 if (!$original_item) {
2766 $orig_url = DI::baseUrl()."/display/".$original_item["guid"];
2770 $datarray["uid"] = $importer["uid"];
2771 $datarray["contact-id"] = $contact["id"];
2772 $datarray["network"] = Protocol::DIASPORA;
2774 $datarray["author-link"] = $contact["url"];
2775 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2777 $datarray["owner-link"] = $datarray["author-link"];
2778 $datarray["owner-id"] = $datarray["author-id"];
2780 $datarray["guid"] = $guid;
2781 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2782 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2784 $datarray["verb"] = Activity::POST;
2785 $datarray["gravity"] = GRAVITY_PARENT;
2787 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2788 $datarray["source"] = $xml;
2790 /// @todo Copy tag data from original post
2792 $prefix = share_header(
2793 $original_item["author-name"],
2794 $original_item["author-link"],
2795 $original_item["author-avatar"],
2796 $original_item["guid"],
2797 $original_item["created"],
2801 if (!empty($original_item['title'])) {
2802 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2805 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2807 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2809 $datarray["attach"] = $original_item["attach"];
2810 $datarray["app"] = $original_item["app"];
2812 $datarray["plink"] = self::plink($author, $guid);
2813 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2814 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2816 $datarray["object-type"] = $original_item["object-type"];
2818 self::fetchGuid($datarray);
2819 $message_id = Item::insert($datarray);
2821 self::sendParticipation($contact, $datarray);
2823 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2824 if ($root_message_id) {
2825 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2829 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2830 if ($datarray['uid'] == 0) {
2831 Item::distribute($message_id);
2840 * Processes retractions
2842 * @param array $importer Array of the importer user
2843 * @param array $contact The contact of the item owner
2844 * @param object $data The message object
2846 * @return bool success
2847 * @throws \Exception
2849 private static function itemRetraction(array $importer, array $contact, $data)
2851 $author = Strings::escapeTags(XML::unescape($data->author));
2852 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2853 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2855 $person = self::personByHandle($author);
2856 if (!is_array($person)) {
2857 Logger::log("unable to find author detail for ".$author);
2861 if (empty($contact["url"])) {
2862 $contact["url"] = $person["url"];
2865 // Fetch items that are about to be deleted
2866 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2868 // When we receive a public retraction, we delete every item that we find.
2869 if ($importer['uid'] == 0) {
2870 $condition = ['guid' => $target_guid, 'deleted' => false];
2872 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2875 $r = Item::select($fields, $condition);
2876 if (!DBA::isResult($r)) {
2877 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2881 while ($item = Item::fetch($r)) {
2882 if (strstr($item['file'], '[')) {
2883 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2887 // Fetch the parent item
2888 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2890 // Only delete it if the parent author really fits
2891 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2892 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2896 Item::markForDeletion(['id' => $item['id']]);
2898 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2905 * Receives retraction messages
2907 * @param array $importer Array of the importer user
2908 * @param string $sender The sender of the message
2909 * @param object $data The message object
2911 * @return bool Success
2912 * @throws \Exception
2914 private static function receiveRetraction(array $importer, $sender, $data)
2916 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2918 $contact = self::contactByHandle($importer["uid"], $sender);
2919 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2920 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2928 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2930 switch ($target_type) {
2935 case "StatusMessage":
2936 return self::itemRetraction($importer, $contact, $data);
2938 case "PollParticipation":
2940 // Currently unsupported
2944 Logger::log("Unknown target type ".$target_type);
2951 * Receives status messages
2953 * @param array $importer Array of the importer user
2954 * @param SimpleXMLElement $data The message object
2955 * @param string $xml The original XML of the message
2957 * @return int The message id of the newly created item
2958 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2959 * @throws \ImagickException
2961 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2963 $author = Strings::escapeTags(XML::unescape($data->author));
2964 $guid = Strings::escapeTags(XML::unescape($data->guid));
2965 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2966 $public = Strings::escapeTags(XML::unescape($data->public));
2967 $text = XML::unescape($data->text);
2968 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2970 $contact = self::allowedContactByHandle($importer, $author, false);
2975 $message_id = self::messageExists($importer["uid"], $guid);
2981 if ($data->location) {
2982 foreach ($data->location->children() as $fieldname => $data) {
2983 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2987 $body = Markdown::toBBCode($text);
2991 // Attach embedded pictures to the body
2993 foreach ($data->photo as $photo) {
2994 $body = "[img]".XML::unescape($photo->remote_photo_path).
2995 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2998 $datarray["object-type"] = Activity\ObjectType::IMAGE;
3000 $datarray["object-type"] = Activity\ObjectType::NOTE;
3002 // Add OEmbed and other information to the body
3003 if (!self::isHubzilla($contact["url"])) {
3004 $body = add_page_info_to_body($body, false, true);
3008 /// @todo enable support for polls
3009 //if ($data->poll) {
3010 // foreach ($data->poll AS $poll)
3015 /// @todo enable support for events
3017 $datarray["uid"] = $importer["uid"];
3018 $datarray["contact-id"] = $contact["id"];
3019 $datarray["network"] = Protocol::DIASPORA;
3021 $datarray["author-link"] = $contact["url"];
3022 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
3024 $datarray["owner-link"] = $datarray["author-link"];
3025 $datarray["owner-id"] = $datarray["author-id"];
3027 $datarray["guid"] = $guid;
3028 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3029 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
3031 $datarray["verb"] = Activity::POST;
3032 $datarray["gravity"] = GRAVITY_PARENT;
3034 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3035 $datarray["source"] = $xml;
3037 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3039 self::storeMentions($datarray['uri-id'], $text);
3040 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
3042 if ($provider_display_name != "") {
3043 $datarray["app"] = $provider_display_name;
3046 $datarray["plink"] = self::plink($author, $guid);
3047 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3048 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3050 if (isset($address["address"])) {
3051 $datarray["location"] = $address["address"];
3054 if (isset($address["lat"]) && isset($address["lng"])) {
3055 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3058 self::fetchGuid($datarray);
3059 $message_id = Item::insert($datarray);
3061 self::sendParticipation($contact, $datarray);
3064 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3065 if ($datarray['uid'] == 0) {
3066 Item::distribute($message_id);
3074 /* ************************************************************************************** *
3075 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3076 * ************************************************************************************** */
3079 * returnes the handle of a contact
3081 * @param array $contact contact array
3083 * @return string the handle in the format user@domain.tld
3084 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3086 private static function myHandle(array $contact)
3088 if (!empty($contact["addr"])) {
3089 return $contact["addr"];
3092 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3093 // So - just in case - we build the the address here.
3094 if ($contact["nickname"] != "") {
3095 $nick = $contact["nickname"];
3097 $nick = $contact["nick"];
3100 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3105 * Creates the data for a private message in the new format
3107 * @param string $msg The message that is to be transmitted
3108 * @param array $user The record of the sender
3109 * @param array $contact Target of the communication
3110 * @param string $prvkey The private key of the sender
3111 * @param string $pubkey The public key of the receiver
3113 * @return string The encrypted data
3114 * @throws \Exception
3116 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3118 Logger::log("Message: ".$msg, Logger::DATA);
3120 // without a public key nothing will work
3122 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3126 $aes_key = openssl_random_pseudo_bytes(32);
3127 $b_aes_key = base64_encode($aes_key);
3128 $iv = openssl_random_pseudo_bytes(16);
3129 $b_iv = base64_encode($iv);
3131 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3133 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3135 $encrypted_key_bundle = "";
3136 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3138 $json_object = json_encode(
3139 ["aes_key" => base64_encode($encrypted_key_bundle),
3140 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3143 return $json_object;
3147 * Creates the envelope for the "fetch" endpoint and for the new format
3149 * @param string $msg The message that is to be transmitted
3150 * @param array $user The record of the sender
3152 * @return string The envelope
3153 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3155 public static function buildMagicEnvelope($msg, array $user)
3157 $b64url_data = Strings::base64UrlEncode($msg);
3158 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3160 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3161 $type = "application/xml";
3162 $encoding = "base64url";
3163 $alg = "RSA-SHA256";
3164 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3166 // Fallback if the private key wasn't transmitted in the expected field
3167 if ($user['uprvkey'] == "") {
3168 $user['uprvkey'] = $user['prvkey'];
3171 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3172 $sig = Strings::base64UrlEncode($signature);
3174 $xmldata = ["me:env" => ["me:data" => $data,
3175 "@attributes" => ["type" => $type],
3176 "me:encoding" => $encoding,
3179 "@attributes2" => ["key_id" => $key_id]]];
3181 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3183 return XML::fromArray($xmldata, $xml, false, $namespaces);
3187 * Create the envelope for a message
3189 * @param string $msg The message that is to be transmitted
3190 * @param array $user The record of the sender
3191 * @param array $contact Target of the communication
3192 * @param string $prvkey The private key of the sender
3193 * @param string $pubkey The public key of the receiver
3194 * @param bool $public Is the message public?
3196 * @return string The message that will be transmitted to other servers
3197 * @throws \Exception
3199 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3201 // The message is put into an envelope with the sender's signature
3202 $envelope = self::buildMagicEnvelope($msg, $user);
3204 // Private messages are put into a second envelope, encrypted with the receivers public key
3206 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3213 * Creates a signature for a message
3215 * @param array $owner the array of the owner of the message
3216 * @param array $message The message that is to be signed
3218 * @return string The signature
3220 private static function signature($owner, $message)
3223 unset($sigmsg["author_signature"]);
3224 unset($sigmsg["parent_author_signature"]);
3226 $signed_text = implode(";", $sigmsg);
3228 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3232 * Transmit a message to a target server
3234 * @param array $owner the array of the item owner
3235 * @param array $contact Target of the communication
3236 * @param string $envelope The message that is to be transmitted
3237 * @param bool $public_batch Is it a public post?
3238 * @param string $guid message guid
3240 * @return int Result of the transmission
3241 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3242 * @throws \ImagickException
3244 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3246 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3251 $logid = Strings::getRandomHex(4);
3253 // We always try to use the data from the fcontact table.
3254 // This is important for transmitting data to Friendica servers.
3255 if (!empty($contact['addr'])) {
3256 $fcontact = self::personByHandle($contact['addr']);
3257 if (!empty($fcontact)) {
3258 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3262 if (empty($dest_url)) {
3263 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3267 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3271 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3273 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3274 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3276 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3277 $return_code = $postResult->getReturnCode();
3279 Logger::log("test_mode");
3283 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3285 return $return_code ? $return_code : -1;
3290 * Build the post xml
3292 * @param string $type The message type
3293 * @param array $message The message data
3295 * @return string The post XML
3297 public static function buildPostXml($type, $message)
3299 $data = [$type => $message];
3301 return XML::fromArray($data, $xml);
3305 * Builds and transmit messages
3307 * @param array $owner the array of the item owner
3308 * @param array $contact Target of the communication
3309 * @param string $type The message type
3310 * @param array $message The message data
3311 * @param bool $public_batch Is it a public post?
3312 * @param string $guid message guid
3314 * @return int Result of the transmission
3315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3316 * @throws \ImagickException
3318 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3320 $msg = self::buildPostXml($type, $message);
3322 Logger::log('message: '.$msg, Logger::DATA);
3323 Logger::log('send guid '.$guid, Logger::DEBUG);
3325 // Fallback if the private key wasn't transmitted in the expected field
3326 if (empty($owner['uprvkey'])) {
3327 $owner['uprvkey'] = $owner['prvkey'];
3330 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3332 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3334 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3336 return $return_code;
3340 * sends a participation (Used to get all further updates)
3342 * @param array $contact Target of the communication
3343 * @param array $item Item array
3345 * @return int The result of the transmission
3346 * @throws \Exception
3348 private static function sendParticipation(array $contact, array $item)
3350 // Don't send notifications for private postings
3351 if ($item['private'] == Item::PRIVATE) {
3355 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3357 $result = DI::cache()->get($cachekey);
3358 if (!is_null($result)) {
3362 // Fetch some user id to have a valid handle to transmit the participation.
3363 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3364 // If the item belongs to a user, we take this user id.
3365 if ($item['uid'] == 0) {
3366 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3367 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3368 $owner = User::getOwnerDataById($first_user['uid']);
3370 $owner = User::getOwnerDataById($item['uid']);
3373 $author = self::myHandle($owner);
3375 $message = ["author" => $author,
3376 "guid" => System::createUUID(),
3377 "parent_type" => "Post",
3378 "parent_guid" => $item["guid"]];
3380 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3382 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3383 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3385 return self::buildAndTransmit($owner, $contact, "participation", $message);
3389 * sends an account migration
3391 * @param array $owner the array of the item owner
3392 * @param array $contact Target of the communication
3393 * @param int $uid User ID
3395 * @return int The result of the transmission
3396 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3397 * @throws \ImagickException
3399 public static function sendAccountMigration(array $owner, array $contact, $uid)
3401 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3402 $profile = self::createProfileData($uid);
3404 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3405 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3407 $message = ["author" => $old_handle,
3408 "profile" => $profile,
3409 "signature" => $signature];
3411 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3413 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3417 * Sends a "share" message
3419 * @param array $owner the array of the item owner
3420 * @param array $contact Target of the communication
3422 * @return int The result of the transmission
3423 * @throws \Exception
3425 public static function sendShare(array $owner, array $contact)
3428 * @todo support the different possible combinations of "following" and "sharing"
3429 * Currently, Diaspora only interprets the "sharing" field
3431 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3435 switch ($contact["rel"]) {
3436 case Contact::FRIEND:
3440 case Contact::SHARING:
3444 case Contact::FOLLOWER:
3450 $message = ["author" => self::myHandle($owner),
3451 "recipient" => $contact["addr"],
3452 "following" => "true",
3453 "sharing" => "true"];
3455 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3457 return self::buildAndTransmit($owner, $contact, "contact", $message);
3461 * sends an "unshare"
3463 * @param array $owner the array of the item owner
3464 * @param array $contact Target of the communication
3466 * @return int The result of the transmission
3467 * @throws \Exception
3469 public static function sendUnshare(array $owner, array $contact)
3471 $message = ["author" => self::myHandle($owner),
3472 "recipient" => $contact["addr"],
3473 "following" => "false",
3474 "sharing" => "false"];
3476 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3478 return self::buildAndTransmit($owner, $contact, "contact", $message);
3482 * Checks a message body if it is a reshare
3484 * @param string $body The message body that is to be check
3485 * @param bool $complete Should it be a complete check or a simple check?
3487 * @return array|bool Reshare details or "false" if no reshare
3488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3489 * @throws \ImagickException
3491 public static function isReshare($body, $complete = true)
3493 $body = trim($body);
3495 $reshared = Item::getShareArray(['body' => $body]);
3496 if (empty($reshared)) {
3500 // Skip if it isn't a pure repeated messages
3501 // Does it start with a share?
3502 if (!empty($reshared['comment']) && $complete) {
3506 if (!empty($reshared['guid']) && $complete) {
3507 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3508 $item = Item::selectFirst(['contact-id'], $condition);
3509 if (DBA::isResult($item)) {
3511 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3512 $ret["root_guid"] = $reshared['guid'];
3514 } elseif ($complete) {
3515 // We are resharing something that isn't a DFRN or Diaspora post.
3516 // So we have to return "false" on "$complete" to not trigger a reshare.
3519 } elseif (empty($reshared['guid']) && $complete) {
3525 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3526 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3527 if (!empty($contact['addr'])) {
3528 $ret['root_handle'] = $contact['addr'];
3532 if (empty($ret) && !$complete) {
3540 * Create an event array
3542 * @param integer $event_id The id of the event
3544 * @return array with event data
3545 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3547 private static function buildEvent($event_id)
3549 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3550 if (!DBA::isResult($r)) {
3558 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3559 if (!DBA::isResult($r)) {
3565 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3566 if (!DBA::isResult($r)) {
3572 $eventdata['author'] = self::myHandle($owner);
3574 if ($event['guid']) {
3575 $eventdata['guid'] = $event['guid'];
3578 $mask = DateTimeFormat::ATOM;
3580 /// @todo - establish "all day" events in Friendica
3581 $eventdata["all_day"] = "false";
3583 $eventdata['timezone'] = 'UTC';
3584 if (!$event['adjust'] && $user['timezone']) {
3585 $eventdata['timezone'] = $user['timezone'];
3588 if ($event['start']) {
3589 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3591 if ($event['finish'] && !$event['nofinish']) {
3592 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3594 if ($event['summary']) {
3595 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3597 if ($event['desc']) {
3598 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3600 if ($event['location']) {
3601 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3602 $coord = Map::getCoordinates($event['location']);
3605 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3606 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3607 $location["lat"] = $coord['lat'];
3608 $location["lng"] = $coord['lon'];
3610 $location["lat"] = 0;
3611 $location["lng"] = 0;
3613 $eventdata['location'] = $location;
3620 * Create a post (status message or reshare)
3622 * @param array $item The item that will be exported
3623 * @param array $owner the array of the item owner
3626 * 'type' -> Message type ("status_message" or "reshare")
3627 * 'message' -> Array of XML elements of the status
3628 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3629 * @throws \ImagickException
3631 public static function buildStatus(array $item, array $owner)
3633 $cachekey = "diaspora:buildStatus:".$item['guid'];
3635 $result = DI::cache()->get($cachekey);
3636 if (!is_null($result)) {
3640 $myaddr = self::myHandle($owner);
3642 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3643 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3644 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3646 // Detect a share element and do a reshare
3647 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3648 $message = ["author" => $myaddr,
3649 "guid" => $item["guid"],
3650 "created_at" => $created,
3651 "root_author" => $ret["root_handle"],
3652 "root_guid" => $ret["root_guid"],
3653 "provider_display_name" => $item["app"],
3654 "public" => $public];
3658 $title = $item["title"];
3659 $body = $item["body"];
3661 // Fetch the title from an attached link - if there is one
3662 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3663 $page_data = BBCode::getAttachmentData($item['body']);
3664 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3665 $title = $page_data['title'];
3669 if ($item['author-link'] != $item['owner-link']) {
3670 require_once 'mod/share.php';
3671 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3672 "", $item['created'], $item['plink']) . $body . '[/share]';
3675 // convert to markdown
3676 $body = html_entity_decode(BBCode::toMarkdown($body));
3679 if (strlen($title)) {
3680 $body = "### ".html_entity_decode($title)."\n\n".$body;
3683 if ($item["attach"]) {
3684 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3686 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3687 foreach ($matches as $mtch) {
3688 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3695 if ($item["location"] != "")
3696 $location["address"] = $item["location"];
3698 if ($item["coord"] != "") {
3699 $coord = explode(" ", $item["coord"]);
3700 $location["lat"] = $coord[0];
3701 $location["lng"] = $coord[1];
3704 $message = ["author" => $myaddr,
3705 "guid" => $item["guid"],
3706 "created_at" => $created,
3707 "edited_at" => $edited,
3708 "public" => $public,
3710 "provider_display_name" => $item["app"],
3711 "location" => $location];
3713 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3714 if (!isset($location["lat"]) || !isset($location["lng"])) {
3715 unset($message["location"]);
3718 if ($item['event-id'] > 0) {
3719 $event = self::buildEvent($item['event-id']);
3720 if (count($event)) {
3721 $message['event'] = $event;
3723 if (!empty($event['location']['address']) &&
3724 !empty($event['location']['lat']) &&
3725 !empty($event['location']['lng'])) {
3726 $message['location'] = $event['location'];
3729 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3730 // $message['text'] = '';
3734 $type = "status_message";
3737 $msg = ["type" => $type, "message" => $message];
3739 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3744 private static function prependParentAuthorMention($body, $profile_url)
3746 $profile = Contact::getDetailsByURL($profile_url);
3747 if (!empty($profile['addr'])
3748 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3749 && !strstr($body, $profile['addr'])
3750 && !strstr($body, $profile_url)
3752 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3761 * @param array $item The item that will be exported
3762 * @param array $owner the array of the item owner
3763 * @param array $contact Target of the communication
3764 * @param bool $public_batch Is it a public post?
3766 * @return int The result of the transmission
3767 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3768 * @throws \ImagickException
3770 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3772 $status = self::buildStatus($item, $owner);
3774 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3778 * Creates a "like" object
3780 * @param array $item The item that will be exported
3781 * @param array $owner the array of the item owner
3783 * @return array The data for a "like"
3784 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3786 private static function constructLike(array $item, array $owner)
3788 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3789 if (!DBA::isResult($parent)) {
3793 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3795 if ($item['verb'] === Activity::LIKE) {
3797 } elseif ($item['verb'] === Activity::DISLIKE) {
3798 $positive = "false";
3801 return(["author" => self::myHandle($owner),
3802 "guid" => $item["guid"],
3803 "parent_guid" => $parent["guid"],
3804 "parent_type" => $target_type,
3805 "positive" => $positive,
3806 "author_signature" => ""]);
3810 * Creates an "EventParticipation" object
3812 * @param array $item The item that will be exported
3813 * @param array $owner the array of the item owner
3815 * @return array The data for an "EventParticipation"
3816 * @throws \Exception
3818 private static function constructAttend(array $item, array $owner)
3820 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3821 if (!DBA::isResult($parent)) {
3825 switch ($item['verb']) {
3826 case Activity::ATTEND:
3827 $attend_answer = 'accepted';
3829 case Activity::ATTENDNO:
3830 $attend_answer = 'declined';
3832 case Activity::ATTENDMAYBE:
3833 $attend_answer = 'tentative';
3836 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3840 return(["author" => self::myHandle($owner),
3841 "guid" => $item["guid"],
3842 "parent_guid" => $parent["guid"],
3843 "status" => $attend_answer,
3844 "author_signature" => ""]);
3848 * Creates the object for a comment
3850 * @param array $item The item that will be exported
3851 * @param array $owner the array of the item owner
3853 * @return array|false The data for a comment
3854 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3856 private static function constructComment(array $item, array $owner)
3858 $cachekey = "diaspora:constructComment:".$item['guid'];
3860 $result = DI::cache()->get($cachekey);
3861 if (!is_null($result)) {
3865 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3866 if (!DBA::isResult($toplevel_item)) {
3867 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3871 $thread_parent_item = $toplevel_item;
3872 if ($item['thr-parent'] != $item['parent-uri']) {
3873 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3876 $body = $item["body"];
3878 // The replied to autor mention is prepended for clarity if:
3879 // - Item replied isn't yours
3880 // - Item is public or explicit mentions are disabled
3881 // - Implicit mentions are enabled
3883 $item['author-id'] != $thread_parent_item['author-id']
3884 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3885 && !DI::config()->get('system', 'disable_implicit_mentions')
3887 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3890 $text = html_entity_decode(BBCode::toMarkdown($body));
3891 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3892 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3895 "author" => self::myHandle($owner),
3896 "guid" => $item["guid"],
3897 "created_at" => $created,
3898 "edited_at" => $edited,
3899 "parent_guid" => $toplevel_item["guid"],
3901 "author_signature" => ""
3904 // Send the thread parent guid only if it is a threaded comment
3905 if ($item['thr-parent'] != $item['parent-uri']) {
3906 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3909 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3915 * Send a like or a comment
3917 * @param array $item The item that will be exported
3918 * @param array $owner the array of the item owner
3919 * @param array $contact Target of the communication
3920 * @param bool $public_batch Is it a public post?
3922 * @return int The result of the transmission
3923 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3924 * @throws \ImagickException
3926 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3928 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3929 $message = self::constructAttend($item, $owner);
3930 $type = "event_participation";
3931 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3932 $message = self::constructLike($item, $owner);
3934 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3935 $message = self::constructComment($item, $owner);
3939 if (empty($message)) {
3943 $message["author_signature"] = self::signature($owner, $message);
3945 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3949 * Creates a message from a signature record entry
3951 * @param array $item The item that will be exported
3952 * @return array The message
3954 private static function messageFromSignature(array $item)
3956 // Split the signed text
3957 $signed_parts = explode(";", $item['signed_text']);
3959 if ($item["deleted"]) {
3960 $message = ["author" => $item['signer'],
3961 "target_guid" => $signed_parts[0],
3962 "target_type" => $signed_parts[1]];
3963 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3964 $message = ["author" => $signed_parts[4],
3965 "guid" => $signed_parts[1],
3966 "parent_guid" => $signed_parts[3],
3967 "parent_type" => $signed_parts[2],
3968 "positive" => $signed_parts[0],
3969 "author_signature" => $item['signature'],
3970 "parent_author_signature" => ""];
3972 // Remove the comment guid
3973 $guid = array_shift($signed_parts);
3975 // Remove the parent guid
3976 $parent_guid = array_shift($signed_parts);
3978 // Remove the handle
3979 $handle = array_pop($signed_parts);
3982 "author" => $handle,
3984 "parent_guid" => $parent_guid,
3985 "text" => implode(";", $signed_parts),
3986 "author_signature" => $item['signature'],
3987 "parent_author_signature" => ""
3994 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3996 * @param array $item The item that will be exported
3997 * @param array $owner the array of the item owner
3998 * @param array $contact Target of the communication
3999 * @param bool $public_batch Is it a public post?
4001 * @return int The result of the transmission
4002 * @throws \Exception
4004 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
4006 if ($item["deleted"]) {
4007 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
4008 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4014 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
4016 $msg = json_decode($item['signed_text'], true);
4019 if (is_array($msg)) {
4020 foreach ($msg as $field => $data) {
4021 if (!$item["deleted"]) {
4022 if ($field == "diaspora_handle") {
4025 if ($field == "target_type") {
4026 $field = "parent_type";
4030 $message[$field] = $data;
4033 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4036 $message["parent_author_signature"] = self::signature($owner, $message);
4038 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4040 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4044 * Sends a retraction (deletion) of a message, like or comment
4046 * @param array $item The item that will be exported
4047 * @param array $owner the array of the item owner
4048 * @param array $contact Target of the communication
4049 * @param bool $public_batch Is it a public post?
4050 * @param bool $relay Is the retraction transmitted from a relay?
4052 * @return int The result of the transmission
4053 * @throws \Exception
4055 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4057 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4059 $msg_type = "retraction";
4061 if ($item['id'] == $item['parent']) {
4062 $target_type = "Post";
4063 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4064 $target_type = "Like";
4066 $target_type = "Comment";
4069 $message = ["author" => $itemaddr,
4070 "target_guid" => $item['guid'],
4071 "target_type" => $target_type];
4073 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4075 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4081 * @param array $item The item that will be exported
4082 * @param array $owner The owner
4083 * @param array $contact Target of the communication
4085 * @return int The result of the transmission
4086 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4087 * @throws \ImagickException
4089 public static function sendMail(array $item, array $owner, array $contact)
4091 $myaddr = self::myHandle($owner);
4093 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4094 if (!DBA::isResult($cnv)) {
4095 Logger::log("conversation not found.");
4099 $body = BBCode::toMarkdown($item["body"]);
4100 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4103 "author" => $myaddr,
4104 "guid" => $item["guid"],
4105 "conversation_guid" => $cnv["guid"],
4107 "created_at" => $created,
4110 if ($item["reply"]) {
4115 "author" => $cnv["creator"],
4116 "guid" => $cnv["guid"],
4117 "subject" => $cnv["subject"],
4118 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4119 "participants" => $cnv["recips"],
4123 $type = "conversation";
4126 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4130 * Split a name into first name and last name
4132 * @param string $name The name
4134 * @return array The array with "first" and "last"
4136 public static function splitName($name) {
4137 $name = trim($name);
4139 // Is the name longer than 64 characters? Then cut the rest of it.
4140 if (strlen($name) > 64) {
4141 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4142 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4144 $name = substr($name, 0, 64);
4148 // Take the first word as first name
4149 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4150 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4151 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4152 return ['first' => $first, 'last' => $last];
4155 // Take the last word as last name
4156 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4157 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4159 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4160 return ['first' => $first, 'last' => $last];
4163 // Take the first 32 characters if there is no space in the first 32 characters
4164 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4165 $first = substr($name, 0, 32);
4166 $last = substr($name, 32);
4167 return ['first' => $first, 'last' => $last];
4170 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4171 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4173 // Check if the last name is longer than 32 characters
4174 if (strlen($last) > 32) {
4175 if (strpos($last, ' ') <= 32) {
4176 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4178 $last = substr($last, 0, 32);
4182 return ['first' => $first, 'last' => $last];
4186 * Create profile data
4188 * @param int $uid The user id
4190 * @return array The profile data
4191 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4193 private static function createProfileData($uid)
4195 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4196 if (!DBA::isResult($profile)) {
4200 $handle = $profile["addr"];
4202 $split_name = self::splitName($profile['name']);
4203 $first = $split_name['first'];
4204 $last = $split_name['last'];
4206 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4207 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4208 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4209 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4215 if ($searchable === 'true') {
4218 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4219 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4223 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4226 $about = BBCode::toMarkdown($profile['about']);
4228 $location = $profile['location'];
4230 if ($profile['pub_keywords']) {
4231 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4232 $kw = str_replace(' ', ' ', $kw);
4233 $arr = explode(' ', $kw);
4235 for ($x = 0; $x < 5; $x ++) {
4236 if (!empty($arr[$x])) {
4237 $tags .= '#'. trim($arr[$x]) .' ';
4242 $tags = trim($tags);
4245 return ["author" => $handle,
4246 "first_name" => $first,
4247 "last_name" => $last,
4248 "image_url" => $large,
4249 "image_url_medium" => $medium,
4250 "image_url_small" => $small,
4253 "location" => $location,
4254 "searchable" => $searchable,
4256 "tag_string" => $tags];
4260 * Sends profile data
4262 * @param int $uid The user id
4263 * @param bool $recips optional, default false
4265 * @throws \Exception
4267 public static function sendProfile($uid, $recips = false)
4273 $owner = User::getOwnerDataById($uid);
4280 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4281 AND `uid` = %d AND `rel` != %d",
4282 DBA::escape(Protocol::DIASPORA),
4284 intval(Contact::SHARING)
4292 $message = self::createProfileData($uid);
4294 // @ToDo Split this into single worker jobs
4295 foreach ($recips as $recip) {
4296 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4297 self::buildAndTransmit($owner, $recip, "profile", $message);
4302 * Creates the signature for likes that are created on our system
4304 * @param integer $uid The user of that comment
4305 * @param array $item Item array
4307 * @return array Signed content
4308 * @throws \Exception
4310 public static function createLikeSignature($uid, array $item)
4312 $owner = User::getOwnerDataById($uid);
4313 if (empty($owner)) {
4314 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4318 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4322 $message = self::constructLike($item, $owner);
4323 if ($message === false) {
4327 $message["author_signature"] = self::signature($owner, $message);
4333 * Creates the signature for Comments that are created on our system
4335 * @param integer $uid The user of that comment
4336 * @param array $item Item array
4338 * @return array Signed content
4339 * @throws \Exception
4341 public static function createCommentSignature($uid, array $item)
4343 $owner = User::getOwnerDataById($uid);
4344 if (empty($owner)) {
4345 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4349 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4350 $item['thr-parent'] = $item['parent-uri'];
4352 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4353 if (!DBA::isResult($parent)) {
4357 $item['parent-uri'] = $parent['parent-uri'];
4359 $message = self::constructComment($item, $owner);
4360 if ($message === false) {
4364 $message["author_signature"] = self::signature($owner, $message);