3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\PageInfo;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Cache\Duration;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\Probe;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Map;
47 use Friendica\Util\Network;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
50 use Friendica\Worker\Delivery;
54 * This class contain functions to create and send Diaspora XML files
59 * Mark the relay contact of the given contact for archival
60 * This is called whenever there is a communication issue with the server.
61 * It avoids sending stuff to servers who don't exist anymore.
62 * The relay contact is a technical contact entry that exists once per server.
64 * @param array $contact of the relay contact
66 public static function markRelayForArchival(array $contact)
68 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
69 // This is already the relay contact, we don't need to fetch it
70 $relay_contact = $contact;
71 } elseif (empty($contact['baseurl'])) {
72 if (!empty($contact['batch'])) {
73 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
74 $relay_contact = DBA::selectFirst('contact', [], $condition);
79 $relay_contact = self::getRelayContact($contact['baseurl'], []);
82 if (!empty($relay_contact)) {
83 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
84 Contact::markForArchival($relay_contact);
89 * Return a list of relay servers
91 * The list contains not only the official relays but also servers that we serve directly
93 * @param integer $item_id The id of the item that is sent
94 * @param array $contacts The previously fetched contacts
96 * @return array of relay servers
97 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
99 public static function relayList($item_id, array $contacts = [])
103 // Fetching relay servers
104 $serverdata = DI::config()->get("system", "relay_server");
106 if (!empty($serverdata)) {
107 $servers = explode(",", $serverdata);
108 foreach ($servers as $server) {
109 $serverlist[$server] = trim($server);
113 if (DI::config()->get("system", "relay_directly", false)) {
114 // We distribute our stuff based on the parent to ensure that the thread will be complete
115 $parent = Item::selectFirst(['uri-id'], ['id' => $item_id]);
116 if (!DBA::isResult($parent)) {
120 // Servers that want to get all content
121 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
122 while ($server = DBA::fetch($servers)) {
123 $serverlist[$server['url']] = $server['url'];
125 DBA::close($servers);
127 // All tags of the current post
128 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
130 while ($tag = DBA::fetch($tags)) {
131 $taglist[] = $tag['name'];
135 // All servers who wants content with this tag
137 if (!empty($taglist)) {
138 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
139 while ($server = DBA::fetch($tagserver)) {
140 $tagserverlist[] = $server['gserver-id'];
142 DBA::close($tagserver);
145 // All adresses with the given id
146 if (!empty($tagserverlist)) {
147 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
148 while ($server = DBA::fetch($servers)) {
149 $serverlist[$server['url']] = $server['url'];
151 DBA::close($servers);
155 // Now we are collecting all relay contacts
156 foreach ($serverlist as $server_url) {
157 // We don't send messages to ourselves
158 if (Strings::compareLink($server_url, DI::baseUrl())) {
161 $contact = self::getRelayContact($server_url);
162 if (is_bool($contact)) {
167 foreach ($contacts as $entry) {
168 if ($entry['batch'] == $contact['batch']) {
174 $contacts[] = $contact;
182 * Return a contact for a given server address or creates a dummy entry
184 * @param string $server_url The url of the server
185 * @param array $fields Fieldlist
186 * @return array with the contact
189 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
191 // Fetch the relay contact
192 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
193 'contact-type' => Contact::TYPE_RELAY];
194 $contact = DBA::selectFirst('contact', $fields, $condition);
196 if (DBA::isResult($contact)) {
197 if ($contact['archive'] || $contact['blocked']) {
202 self::setRelayContact($server_url);
204 $contact = DBA::selectFirst('contact', $fields, $condition);
205 if (DBA::isResult($contact)) {
210 // It should never happen that we arrive here
215 * Update or insert a relay contact
217 * @param string $server_url The url of the server
218 * @param array $network_fields Optional network specific fields
221 public static function setRelayContact($server_url, array $network_fields = [])
223 $fields = ['created' => DateTimeFormat::utcNow(),
224 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
225 'nurl' => Strings::normaliseLink($server_url),
226 'network' => Protocol::DIASPORA, 'uid' => 0,
227 'batch' => $server_url . '/receive/public',
228 'rel' => Contact::FOLLOWER, 'blocked' => false,
229 'pending' => false, 'writable' => true,
230 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
232 $fields = array_merge($fields, $network_fields);
234 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
235 $old = DBA::selectFirst('contact', [], $condition);
236 if (DBA::isResult($old)) {
237 unset($fields['created']);
238 $condition = ['id' => $old['id']];
240 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
241 DBA::update('contact', $fields, $condition, $old);
243 Logger::info('Create relay contact', ['fields' => $fields]);
244 Contact::insert($fields);
249 * Return a list of participating contacts for a thread
251 * This is used for the participation feature.
252 * One of the parameters is a contact array.
253 * This is done to avoid duplicates.
255 * @param array $item Item that is about to be delivered
256 * @param array $contacts The previously fetched contacts
258 * @return array of relay servers
261 public static function participantsForThread(array $item, array $contacts)
263 if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
264 Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
268 $items = Item::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
269 ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
270 while ($item = DBA::fetch($items)) {
271 $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
272 ['id' => $item['author-id']]);
273 if (!DBA::isResult($contact) || empty($contact['batch']) ||
274 ($contact['network'] != Protocol::DIASPORA) ||
275 Strings::compareLink($item['parent-author-link'], $item['author-link'])) {
280 foreach ($contacts as $entry) {
281 if ($entry['batch'] == $contact['batch']) {
287 Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]);
288 $contacts[] = $contact;
297 * verify the envelope and return the verified data
299 * @param string $envelope The magic envelope
301 * @return string verified data
302 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
303 * @throws \ImagickException
305 private static function verifyMagicEnvelope($envelope)
307 $basedom = XML::parseString($envelope, true);
309 if (!is_object($basedom)) {
310 Logger::log("Envelope is no XML file");
314 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
316 if (sizeof($children) == 0) {
317 Logger::log("XML has no children");
323 $data = Strings::base64UrlDecode($children->data);
324 $type = $children->data->attributes()->type[0];
326 $encoding = $children->encoding;
328 $alg = $children->alg;
330 $sig = Strings::base64UrlDecode($children->sig);
331 $key_id = $children->sig->attributes()->key_id[0];
333 $handle = Strings::base64UrlDecode($key_id);
336 $b64url_data = Strings::base64UrlEncode($data);
337 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
339 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
342 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
346 $key = self::key($handle);
348 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
352 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
354 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
362 * encrypts data via AES
364 * @param string $key The AES key
365 * @param string $iv The IV (is used for CBC encoding)
366 * @param string $data The data that is to be encrypted
368 * @return string encrypted data
370 private static function aesEncrypt($key, $iv, $data)
372 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
376 * decrypts data via AES
378 * @param string $key The AES key
379 * @param string $iv The IV (is used for CBC encoding)
380 * @param string $encrypted The encrypted data
382 * @return string decrypted data
384 private static function aesDecrypt($key, $iv, $encrypted)
386 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
390 * Decodes incoming Diaspora message in the new format
392 * @param string $raw raw post message
393 * @param string $privKey The private key of the importer
394 * @param boolean $no_exit Don't do an http exit on error
397 * 'message' -> decoded Diaspora XML message
398 * 'author' -> author diaspora handle
399 * 'key' -> author public key (converted to pkcs#8)
400 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
401 * @throws \ImagickException
403 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
405 $data = json_decode($raw);
407 // Is it a private post? Then decrypt the outer Salmon
408 if (is_object($data)) {
409 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
410 $ciphertext = base64_decode($data->encrypted_magic_envelope);
412 $outer_key_bundle = '';
413 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
414 $j_outer_key_bundle = json_decode($outer_key_bundle);
416 if (!is_object($j_outer_key_bundle)) {
417 Logger::log('Outer Salmon did not verify. Discarding.');
421 throw new \Friendica\Network\HTTPException\BadRequestException();
425 $outer_iv = base64_decode($j_outer_key_bundle->iv);
426 $outer_key = base64_decode($j_outer_key_bundle->key);
428 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
433 $basedom = XML::parseString($xml, true);
435 if (!is_object($basedom)) {
436 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
440 throw new \Friendica\Network\HTTPException\BadRequestException();
444 $base = $basedom->children(ActivityNamespace::SALMON_ME);
446 // Not sure if this cleaning is needed
447 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
449 // Build the signed data
450 $type = $base->data[0]->attributes()->type[0];
451 $encoding = $base->encoding;
453 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
455 // This is the signature
456 $signature = Strings::base64UrlDecode($base->sig);
458 // Get the senders' public key
459 $key_id = $base->sig[0]->attributes()->key_id[0];
460 $author_addr = base64_decode($key_id);
461 if ($author_addr == '') {
462 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
466 throw new \Friendica\Network\HTTPException\BadRequestException();
470 $key = self::key($author_addr);
472 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
476 throw new \Friendica\Network\HTTPException\BadRequestException();
480 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
482 Logger::log('Message did not verify. Discarding.');
486 throw new \Friendica\Network\HTTPException\BadRequestException();
490 return ['message' => (string)Strings::base64UrlDecode($base->data),
491 'author' => XML::unescape($author_addr),
492 'key' => (string)$key];
496 * Decodes incoming Diaspora message in the deprecated format
498 * @param string $xml urldecoded Diaspora salmon
499 * @param string $privKey The private key of the importer
502 * 'message' -> decoded Diaspora XML message
503 * 'author' -> author diaspora handle
504 * 'key' -> author public key (converted to pkcs#8)
505 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
506 * @throws \ImagickException
508 public static function decode(string $xml, string $privKey = '')
511 $basedom = XML::parseString($xml);
513 if (!is_object($basedom)) {
514 Logger::notice('XML is not parseable.');
517 $children = $basedom->children('https://joindiaspora.com/protocol');
519 $inner_aes_key = null;
522 if ($children->header) {
524 $author_link = str_replace('acct:', '', $children->header->author_id);
526 // This happens with posts from a relais
527 if (empty($privKey)) {
528 Logger::info('This is no private post in the old format');
532 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
534 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
535 $ciphertext = base64_decode($encrypted_header->ciphertext);
537 $outer_key_bundle = '';
538 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
540 $j_outer_key_bundle = json_decode($outer_key_bundle);
542 $outer_iv = base64_decode($j_outer_key_bundle->iv);
543 $outer_key = base64_decode($j_outer_key_bundle->key);
545 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
547 Logger::info('decrypted', ['data' => $decrypted]);
548 $idom = XML::parseString($decrypted);
550 $inner_iv = base64_decode($idom->iv);
551 $inner_aes_key = base64_decode($idom->aes_key);
553 $author_link = str_replace('acct:', '', $idom->author_id);
556 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
558 // figure out where in the DOM tree our data is hiding
561 if ($dom->provenance->data) {
562 $base = $dom->provenance;
563 } elseif ($dom->env->data) {
565 } elseif ($dom->data) {
570 Logger::log('unable to locate salmon data in xml');
571 throw new \Friendica\Network\HTTPException\BadRequestException();
575 // Stash the signature away for now. We have to find their key or it won't be good for anything.
576 $signature = Strings::base64UrlDecode($base->sig);
580 // strip whitespace so our data element will return to one big base64 blob
581 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
584 // stash away some other stuff for later
586 $type = $base->data[0]->attributes()->type[0];
587 $keyhash = $base->sig[0]->attributes()->keyhash[0];
588 $encoding = $base->encoding;
592 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
596 $data = Strings::base64UrlDecode($data);
600 $inner_decrypted = $data;
602 // Decode the encrypted blob
603 $inner_encrypted = base64_decode($data);
604 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
608 Logger::log('Could not retrieve author URI.');
609 throw new \Friendica\Network\HTTPException\BadRequestException();
611 // Once we have the author URI, go to the web and try to find their public key
612 // (first this will look it up locally if it is in the fcontact cache)
613 // This will also convert diaspora public key from pkcs#1 to pkcs#8
615 Logger::log('Fetching key for '.$author_link);
616 $key = self::key($author_link);
619 Logger::log('Could not retrieve author key.');
620 throw new \Friendica\Network\HTTPException\BadRequestException();
623 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
626 Logger::log('Message did not verify. Discarding.');
627 throw new \Friendica\Network\HTTPException\BadRequestException();
630 Logger::log('Message verified.');
632 return ['message' => (string)$inner_decrypted,
633 'author' => XML::unescape($author_link),
634 'key' => (string)$key];
639 * Dispatches public messages and find the fitting receivers
641 * @param array $msg The post that will be dispatched
643 * @return int The message id of the generated message, "true" or "false" if there was an error
644 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
645 * @throws \ImagickException
647 public static function dispatchPublic($msg)
649 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
651 Logger::log("diaspora is disabled");
655 if (!($fields = self::validPosting($msg))) {
656 Logger::log("Invalid posting");
660 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
661 $success = self::dispatch($importer, $msg, $fields);
667 * Dispatches the different message types to the different functions
669 * @param array $importer Array of the importer user
670 * @param array $msg The post that will be dispatched
671 * @param SimpleXMLElement $fields SimpleXML object that contains the message
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 dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
679 // The sender is the handle of the contact that sent the message.
680 // This will often be different with relayed messages (for example "like" and "comment")
681 $sender = $msg["author"];
683 // This is only needed for private postings since this is already done for public ones before
684 if (is_null($fields)) {
686 if (!($fields = self::validPosting($msg))) {
687 Logger::log("Invalid posting");
694 $type = $fields->getName();
696 Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]);
699 case "account_migration":
701 Logger::log('Message with type ' . $type . ' is not private, quitting.');
704 return self::receiveAccountMigration($importer, $fields);
706 case "account_deletion":
707 return self::receiveAccountDeletion($fields);
710 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
714 Logger::log('Message with type ' . $type . ' is not private, quitting.');
717 return self::receiveContactRequest($importer, $fields);
721 Logger::log('Message with type ' . $type . ' is not private, quitting.');
724 return self::receiveConversation($importer, $msg, $fields);
727 return self::receiveLike($importer, $sender, $fields);
731 Logger::log('Message with type ' . $type . ' is not private, quitting.');
734 return self::receiveMessage($importer, $fields);
736 case "participation":
738 Logger::log('Message with type ' . $type . ' is not private, quitting.');
741 return self::receiveParticipation($importer, $fields);
743 case "photo": // Not implemented
744 return self::receivePhoto($importer, $fields);
746 case "poll_participation": // Not implemented
747 return self::receivePollParticipation($importer, $fields);
751 Logger::log('Message with type ' . $type . ' is not private, quitting.');
754 return self::receiveProfile($importer, $fields);
757 return self::receiveReshare($importer, $fields, $msg["message"]);
760 return self::receiveRetraction($importer, $sender, $fields);
762 case "status_message":
763 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
766 Logger::log("Unknown message type ".$type);
772 * Checks if a posting is valid and fetches the data fields.
774 * This function does not only check the signature.
775 * It also does the conversion between the old and the new diaspora format.
777 * @param array $msg Array with the XML, the sender handle and the sender signature
779 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
780 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
781 * @throws \ImagickException
783 private static function validPosting($msg)
785 $data = XML::parseString($msg["message"]);
787 if (!is_object($data)) {
788 Logger::info('No valid XML', ['message' => $msg['message']]);
792 // Is this the new or the old version?
793 if ($data->getName() == "XML") {
795 foreach ($data->post->children() as $child) {
803 $type = $element->getName();
806 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
808 // All retractions are handled identically from now on.
809 // In the new version there will only be "retraction".
810 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
811 $type = "retraction";
813 if ($type == "request") {
817 $fields = new SimpleXMLElement("<".$type."/>");
820 $author_signature = null;
821 $parent_author_signature = null;
823 foreach ($element->children() as $fieldname => $entry) {
825 // Translation for the old XML structure
826 if ($fieldname == "diaspora_handle") {
827 $fieldname = "author";
829 if ($fieldname == "participant_handles") {
830 $fieldname = "participants";
832 if (in_array($type, ["like", "participation"])) {
833 if ($fieldname == "target_type") {
834 $fieldname = "parent_type";
837 if ($fieldname == "sender_handle") {
838 $fieldname = "author";
840 if ($fieldname == "recipient_handle") {
841 $fieldname = "recipient";
843 if ($fieldname == "root_diaspora_id") {
844 $fieldname = "root_author";
846 if ($type == "status_message") {
847 if ($fieldname == "raw_message") {
851 if ($type == "retraction") {
852 if ($fieldname == "post_guid") {
853 $fieldname = "target_guid";
855 if ($fieldname == "type") {
856 $fieldname = "target_type";
861 if (($fieldname == "author_signature") && ($entry != "")) {
862 $author_signature = base64_decode($entry);
863 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
864 $parent_author_signature = base64_decode($entry);
865 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
866 if ($signed_data != "") {
870 $signed_data .= $entry;
872 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
873 || ($orig_type == "relayable_retraction")
875 XML::copy($entry, $fields, $fieldname);
879 // This is something that shouldn't happen at all.
880 if (in_array($type, ["status_message", "reshare", "profile"])) {
881 if ($msg["author"] != $fields->author) {
882 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
887 // Only some message types have signatures. So we quit here for the other types.
888 if (!in_array($type, ["comment", "like"])) {
891 // No author_signature? This is a must, so we quit.
892 if (!isset($author_signature)) {
893 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
897 if (isset($parent_author_signature)) {
898 $key = self::key($msg["author"]);
900 Logger::info('No key found for parent', ['author' => $msg["author"]]);
904 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
905 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);
910 $key = self::key($fields->author);
912 Logger::info('No key found', ['author' => $fields->author]);
916 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
917 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);
925 * Fetches the public key for a given handle
927 * @param string $handle The handle
929 * @return string The public key
930 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
931 * @throws \ImagickException
933 private static function key($handle)
935 $handle = strval($handle);
937 Logger::log("Fetching diaspora key for: ".$handle);
939 $r = self::personByHandle($handle);
948 * Fetches data for a given handle
950 * @param string $handle The handle
951 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
953 * @return array the queried data
954 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
955 * @throws \ImagickException
957 public static function personByHandle($handle, $update = null)
959 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
960 if (!DBA::isResult($person)) {
961 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
962 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
965 if (DBA::isResult($person)) {
966 Logger::debug('In cache', ['person' => $person]);
968 if (is_null($update)) {
969 // update record occasionally so it doesn't get stale
970 $d = strtotime($person["updated"]." +00:00");
971 if ($d < strtotime("now - 14 days")) {
975 if ($person["guid"] == "") {
979 } elseif (is_null($update)) {
980 $update = !DBA::isResult($person);
986 Logger::log("create or refresh", Logger::DEBUG);
987 $r = Probe::uri($handle, Protocol::DIASPORA);
989 // Note that Friendica contacts will return a "Diaspora person"
990 // if Diaspora connectivity is enabled on their server
991 if ($r && ($r["network"] === Protocol::DIASPORA)) {
992 self::updateFContact($r);
994 $person = self::personByHandle($handle, false);
1002 * Updates the fcontact table
1004 * @param array $arr The fcontact data
1005 * @throws \Exception
1007 private static function updateFContact($arr)
1009 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1010 'request' => $arr["request"], 'nick' => $arr["nick"],
1011 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1012 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1013 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1014 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1015 'updated' => DateTimeFormat::utcNow()];
1017 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1019 DBA::update('fcontact', $fields, $condition, true);
1023 * get a handle (user@domain.tld) from a given contact id
1025 * @param int $contact_id The id in the contact table
1026 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1028 * @return string the handle
1029 * @throws \Exception
1031 private static function handleFromContact($contact_id, $pcontact_id = 0)
1035 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1037 if ($pcontact_id != 0) {
1038 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1040 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1041 return strtolower($contact["addr"]);
1046 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1050 if (DBA::isResult($r)) {
1053 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1055 if ($contact['addr'] != "") {
1056 $handle = $contact['addr'];
1058 $baseurl_start = strpos($contact['url'], '://') + 3;
1059 // allows installations in a subdirectory--not sure how Diaspora will handle
1060 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1061 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1062 $handle = $contact['nick'].'@'.$baseurl;
1066 return strtolower($handle);
1070 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1073 * @param mixed $fcontact_guid Hexadecimal string guid
1075 * @return string the contact url or null
1076 * @throws \Exception
1078 public static function urlFromContactGuid($fcontact_guid)
1080 Logger::info('fcontact', ['guid' => $fcontact_guid]);
1083 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1084 DBA::escape(Protocol::DIASPORA),
1085 DBA::escape($fcontact_guid)
1088 if (DBA::isResult($r)) {
1089 return $r[0]['url'];
1096 * Get a contact id for a given handle
1098 * @todo Move to Friendica\Model\Contact
1100 * @param int $uid The user id
1101 * @param string $handle The handle in the format user@domain.tld
1103 * @return array Contact data
1104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1105 * @throws \ImagickException
1107 private static function contactByHandle($uid, $handle)
1109 $cid = Contact::getIdForURL($handle, $uid);
1111 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1115 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1116 if (!DBA::isResult($contact)) {
1117 // This here shouldn't happen at all
1118 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1126 * Checks if the given contact url does support ActivityPub
1128 * @param string $url profile url
1129 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1131 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1132 * @throws \ImagickException
1134 public static function isSupportedByContactUrl($url, $update = null)
1136 return !empty(self::personByHandle($url, $update));
1140 * Check if posting is allowed for this contact
1142 * @param array $importer Array of the importer user
1143 * @param array $contact The contact that is checked
1144 * @param bool $is_comment Is the check for a comment?
1146 * @return bool is the contact allowed to post?
1148 private static function postAllow(array $importer, array $contact, $is_comment = false)
1151 * Perhaps we were already sharing with this person. Now they're sharing with us.
1152 * That makes us friends.
1153 * Normally this should have handled by getting a request - but this could get lost
1155 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1156 // It is not removed by now. Possibly the code is needed?
1157 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1160 // array('rel' => Contact::FRIEND, 'writable' => true),
1161 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1164 // $contact["rel"] = Contact::FRIEND;
1165 // Logger::log("defining user ".$contact["nick"]." as friend");
1168 // Contact server is blocked
1169 if (Network::isUrlBlocked($contact['url'])) {
1171 // We don't seem to like that person
1172 } elseif ($contact["blocked"]) {
1173 // Maybe blocked, don't accept.
1175 // We are following this person?
1176 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1177 // Yes, then it is fine.
1179 // Is it a post to a community?
1180 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1183 // Is the message a global user or a comment?
1184 } elseif (($importer["uid"] == 0) || $is_comment) {
1185 // Messages for the global users and comments are always accepted
1193 * Fetches the contact id for a handle and checks if posting is allowed
1195 * @param array $importer Array of the importer user
1196 * @param string $handle The checked handle in the format user@domain.tld
1197 * @param bool $is_comment Is the check for a comment?
1199 * @return array The contact data
1200 * @throws \Exception
1202 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1204 $contact = self::contactByHandle($importer["uid"], $handle);
1206 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1207 // If a contact isn't found, we accept it anyway if it is a comment
1208 if ($is_comment && ($importer["uid"] != 0)) {
1209 return self::contactByHandle(0, $handle);
1210 } elseif ($is_comment) {
1217 if (!self::postAllow($importer, $contact, $is_comment)) {
1218 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1225 * Does the message already exists on the system?
1227 * @param int $uid The user id
1228 * @param string $guid The guid of the message
1230 * @return int|bool message id if the message already was stored into the system - or false.
1231 * @throws \Exception
1233 private static function messageExists($uid, $guid)
1235 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1236 if (DBA::isResult($item)) {
1237 Logger::log("message ".$guid." already exists for user ".$uid);
1245 * Checks for links to posts in a message
1247 * @param array $item The item array
1250 private static function fetchGuid(array $item)
1252 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1253 preg_replace_callback(
1255 function ($match) use ($item) {
1256 self::fetchGuidSub($match, $item);
1261 preg_replace_callback(
1262 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1263 function ($match) use ($item) {
1264 self::fetchGuidSub($match, $item);
1271 * Checks for relative /people/* links in an item body to match local
1272 * contacts or prepends the remote host taken from the author link.
1274 * @param string $body The item body to replace links from
1275 * @param string $author_link The author link for missing local contact fallback
1277 * @return string the replaced string
1279 public static function replacePeopleGuid($body, $author_link)
1281 $return = preg_replace_callback(
1282 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1283 function ($match) use ($author_link) {
1285 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1286 // 1 => '0123456789abcdef'
1288 $handle = self::urlFromContactGuid($match[1]);
1291 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1293 // No local match, restoring absolute remote URL from author scheme and host
1294 $author_url = parse_url($author_link);
1295 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1307 * sub function of "fetchGuid" which checks for links in messages
1309 * @param array $match array containing a link that has to be checked for a message link
1310 * @param array $item The item array
1312 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1313 * @throws \ImagickException
1315 private static function fetchGuidSub($match, $item)
1317 if (!self::storeByGuid($match[1], $item["author-link"])) {
1318 self::storeByGuid($match[1], $item["owner-link"]);
1323 * Fetches an item with a given guid from a given server
1325 * @param string $guid the message guid
1326 * @param string $server The server address
1327 * @param int $uid The user id of the user
1329 * @return int the message id of the stored message or false
1330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1331 * @throws \ImagickException
1333 private static function storeByGuid($guid, $server, $uid = 0)
1335 $serverparts = parse_url($server);
1337 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1341 $server = $serverparts["scheme"]."://".$serverparts["host"];
1343 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1345 $msg = self::message($guid, $server);
1351 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1353 // Now call the dispatcher
1354 return self::dispatchPublic($msg);
1358 * Fetches a message from a server
1360 * @param string $guid message guid
1361 * @param string $server The url of the server
1362 * @param int $level Endless loop prevention
1365 * 'message' => The message XML
1366 * 'author' => The author handle
1367 * 'key' => The public key of the author
1368 * @throws \Exception
1370 private static function message($guid, $server, $level = 0)
1376 // This will work for new Diaspora servers and Friendica servers from 3.5
1377 $source_url = $server."/fetch/post/".urlencode($guid);
1379 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1381 $envelope = DI::httpRequest()->fetch($source_url);
1383 Logger::log("Envelope was fetched.", Logger::DEBUG);
1384 $x = self::verifyMagicEnvelope($envelope);
1386 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1388 Logger::log("Envelope was verified.", Logger::DEBUG);
1398 $source_xml = XML::parseString($x);
1400 if (!is_object($source_xml)) {
1404 if ($source_xml->post->reshare) {
1405 // Reshare of a reshare - old Diaspora version
1406 Logger::log("Message is a reshare", Logger::DEBUG);
1407 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1408 } elseif ($source_xml->getName() == "reshare") {
1409 // Reshare of a reshare - new Diaspora version
1410 Logger::log("Message is a new reshare", Logger::DEBUG);
1411 return self::message($source_xml->root_guid, $server, ++$level);
1416 // Fetch the author - for the old and the new Diaspora version
1417 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1418 $author = (string)$source_xml->post->status_message->diaspora_handle;
1419 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1420 $author = (string)$source_xml->author;
1423 // If this isn't a "status_message" then quit
1425 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1429 $msg = ["message" => $x, "author" => $author];
1431 $msg["key"] = self::key($msg["author"]);
1437 * Fetches an item with a given URL
1439 * @param string $url the message url
1441 * @return int the message id of the stored message or false
1442 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1443 * @throws \ImagickException
1445 public static function fetchByURL($url, $uid = 0)
1447 // Check for Diaspora (and Friendica) typical paths
1448 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1449 Logger::info('Invalid url', ['url' => $url]);
1453 $guid = urldecode($matches[2]);
1455 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1456 if (DBA::isResult($item)) {
1457 Logger::info('Found', ['id' => $item['id']]);
1461 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1462 $ret = self::storeByGuid($guid, $matches[1], $uid);
1463 Logger::info('Result', ['ret' => $ret]);
1465 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1466 if (DBA::isResult($item)) {
1467 Logger::info('Found', ['id' => $item['id']]);
1470 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1476 * Fetches the item record of a given guid
1478 * @param int $uid The user id
1479 * @param string $guid message guid
1480 * @param string $author The handle of the item
1481 * @param array $contact The contact of the item owner
1483 * @return array the item record
1484 * @throws \Exception
1486 private static function parentItem($uid, $guid, $author, array $contact)
1488 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1489 'author-name', 'author-link', 'author-avatar', 'gravity',
1490 'owner-name', 'owner-link', 'owner-avatar'];
1491 $condition = ['uid' => $uid, 'guid' => $guid];
1492 $item = Item::selectFirst($fields, $condition);
1494 if (!DBA::isResult($item)) {
1495 $person = self::personByHandle($author);
1496 $result = self::storeByGuid($guid, $person["url"], $uid);
1498 // We don't have an url for items that arrived at the public dispatcher
1499 if (!$result && !empty($contact["url"])) {
1500 $result = self::storeByGuid($guid, $contact["url"], $uid);
1504 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1506 $item = Item::selectFirst($fields, $condition);
1510 if (!DBA::isResult($item)) {
1511 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1514 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1520 * returns contact details
1522 * @param array $def_contact The default contact if the person isn't found
1523 * @param array $person The record of the person
1524 * @param int $uid The user id
1527 * 'cid' => contact id
1528 * 'network' => network type
1529 * @throws \Exception
1531 private static function authorContactByUrl($def_contact, $person, $uid)
1533 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1534 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1535 if (DBA::isResult($contact)) {
1536 $cid = $contact["id"];
1537 $network = $contact["network"];
1539 $cid = $def_contact["id"];
1540 $network = Protocol::DIASPORA;
1543 return ["cid" => $cid, "network" => $network];
1547 * Is the profile a hubzilla profile?
1549 * @param string $url The profile link
1551 * @return bool is it a hubzilla server?
1553 private static function isHubzilla($url)
1555 return(strstr($url, '/channel/'));
1559 * Generate a post link with a given handle and message guid
1561 * @param string $addr The user handle
1562 * @param string $guid message guid
1563 * @param string $parent_guid optional parent guid
1565 * @return string the post link
1566 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1567 * @throws \ImagickException
1569 private static function plink($addr, $guid, $parent_guid = '')
1571 $contact = Contact::getByURL($addr);
1572 if (empty($contact)) {
1573 Logger::info('No contact data for address', ['addr' => $addr]);
1577 if (empty($contact['baseurl'])) {
1578 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1579 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1583 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1584 if (!empty($gserver['platform'])) {
1585 $platform = strtolower($gserver['platform']);
1586 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1589 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1590 if (self::isHubzilla($contact['url'])) {
1591 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1592 $platform = 'hubzilla';
1593 } elseif ($contact['network'] == Protocol::DFRN) {
1594 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1595 $platform = 'friendica';
1599 if ($platform == 'friendica') {
1600 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1603 if ($platform == 'hubzilla') {
1604 return $contact['baseurl'] . '/item/' . $guid;
1607 if ($platform == 'socialhome') {
1608 return $contact['baseurl'] . '/content/' . $guid;
1611 if ($platform != 'diaspora') {
1612 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1616 if ($parent_guid != '') {
1617 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1619 return $contact['baseurl'] . '/posts/' . $guid;
1624 * Receives account migration
1626 * @param array $importer Array of the importer user
1627 * @param object $data The message object
1629 * @return bool Success
1630 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1631 * @throws \ImagickException
1633 private static function receiveAccountMigration(array $importer, $data)
1635 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1636 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1637 $signature = Strings::escapeTags(XML::unescape($data->signature));
1639 $contact = self::contactByHandle($importer["uid"], $old_handle);
1641 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1645 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1648 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1649 $key = self::key($old_handle);
1650 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1651 Logger::log('No valid signature for migration.');
1655 // Update the profile
1656 self::receiveProfile($importer, $data->profile);
1658 // change the technical stuff in contact
1659 $data = Probe::uri($new_handle);
1660 if ($data['network'] == Protocol::PHANTOM) {
1661 Logger::log('Account for '.$new_handle." couldn't be probed.");
1665 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1666 'name' => $data['name'], 'nick' => $data['nick'],
1667 'addr' => $data['addr'], 'batch' => $data['batch'],
1668 'notify' => $data['notify'], 'poll' => $data['poll'],
1669 'network' => $data['network']];
1671 DBA::update('contact', $fields, ['addr' => $old_handle]);
1673 Logger::log('Contacts are updated.');
1679 * Processes an account deletion
1681 * @param object $data The message object
1683 * @return bool Success
1684 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1686 private static function receiveAccountDeletion($data)
1688 $author = Strings::escapeTags(XML::unescape($data->author));
1690 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1691 while ($contact = DBA::fetch($contacts)) {
1692 Contact::remove($contact["id"]);
1694 DBA::close($contacts);
1696 Logger::log('Removed contacts for ' . $author);
1702 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1704 * @param string $author Author handle
1705 * @param string $guid Message guid
1706 * @param boolean $onlyfound Only return uri when found in the database
1708 * @return string The constructed uri or the one from our database
1709 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1710 * @throws \ImagickException
1712 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1714 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1715 if (DBA::isResult($item)) {
1716 return $item["uri"];
1717 } elseif (!$onlyfound) {
1718 $person = self::personByHandle($author);
1720 $parts = parse_url($person['url']);
1721 unset($parts['path']);
1722 $host_url = Network::unparseURL($parts);
1724 return $host_url . '/objects/' . $guid;
1731 * Fetch the guid from our database with a given uri
1733 * @param string $uri Message uri
1734 * @param string $uid Author handle
1736 * @return string The post guid
1737 * @throws \Exception
1739 private static function getGuidFromUri($uri, $uid)
1741 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1742 if (DBA::isResult($item)) {
1743 return $item["guid"];
1750 * Find the best importer for a comment, like, ...
1752 * @param string $guid The guid of the item
1754 * @return array|boolean the origin owner of that post - or false
1755 * @throws \Exception
1757 private static function importerForGuid($guid)
1759 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1760 if (DBA::isResult($item)) {
1761 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1762 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1763 if (DBA::isResult($contact)) {
1771 * Store the mentions in the tag table
1773 * @param integer $uriid
1774 * @param string $text
1776 private static function storeMentions(int $uriid, string $text)
1778 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1779 if (empty($matches)) {
1784 * Matching values for the preg match
1785 * [1] = mention type (@ or !)
1786 * [2] = name (optional)
1790 foreach ($matches as $match) {
1791 if (empty($match)) {
1795 $person = self::personByHandle($match[3]);
1796 if (empty($person)) {
1800 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1805 * Processes an incoming comment
1807 * @param array $importer Array of the importer user
1808 * @param string $sender The sender of the message
1809 * @param object $data The message object
1810 * @param string $xml The original XML of the message
1812 * @return int The message id of the generated comment or "false" if there was an error
1813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1814 * @throws \ImagickException
1816 private static function receiveComment(array $importer, $sender, $data, $xml)
1818 $author = Strings::escapeTags(XML::unescape($data->author));
1819 $guid = Strings::escapeTags(XML::unescape($data->guid));
1820 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1821 $text = XML::unescape($data->text);
1823 if (isset($data->created_at)) {
1824 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1826 $created_at = DateTimeFormat::utcNow();
1829 if (isset($data->thread_parent_guid)) {
1830 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1831 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1836 $contact = self::allowedContactByHandle($importer, $sender, true);
1841 $message_id = self::messageExists($importer["uid"], $guid);
1846 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1847 if (!$parent_item) {
1851 $person = self::personByHandle($author);
1852 if (!is_array($person)) {
1853 Logger::log("unable to find author details");
1857 // Fetch the contact id - if we know this contact
1858 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1862 $datarray["uid"] = $importer["uid"];
1863 $datarray["contact-id"] = $author_contact["cid"];
1864 $datarray["network"] = $author_contact["network"];
1866 $datarray["author-link"] = $person["url"];
1867 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1869 $datarray["owner-link"] = $contact["url"];
1870 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1872 $datarray["guid"] = $guid;
1873 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1874 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1876 $datarray["verb"] = Activity::POST;
1877 $datarray["gravity"] = GRAVITY_COMMENT;
1879 if ($thr_uri != "") {
1880 $datarray["parent-uri"] = $thr_uri;
1882 $datarray["parent-uri"] = $parent_item["uri"];
1885 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1887 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1888 $datarray["source"] = $xml;
1890 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1892 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1893 $body = Markdown::toBBCode($text);
1895 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1897 self::storeMentions($datarray['uri-id'], $text);
1898 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1900 self::fetchGuid($datarray);
1902 // If we are the origin of the parent we store the original data.
1903 // We notify our followers during the item storage.
1904 if ($parent_item["origin"]) {
1905 $datarray['diaspora_signed_text'] = json_encode($data);
1908 $message_id = Item::insert($datarray);
1910 if ($message_id <= 0) {
1915 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1916 if ($datarray['uid'] == 0) {
1917 Item::distribute($message_id, json_encode($data));
1925 * processes and stores private messages
1927 * @param array $importer Array of the importer user
1928 * @param array $contact The contact of the message
1929 * @param object $data The message object
1930 * @param array $msg Array of the processed message, author handle and key
1931 * @param object $mesg The private message
1932 * @param array $conversation The conversation record to which this message belongs
1934 * @return bool "true" if it was successful
1935 * @throws \Exception
1937 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1939 $author = Strings::escapeTags(XML::unescape($data->author));
1940 $guid = Strings::escapeTags(XML::unescape($data->guid));
1941 $subject = Strings::escapeTags(XML::unescape($data->subject));
1943 // "diaspora_handle" is the element name from the old version
1944 // "author" is the element name from the new version
1945 if ($mesg->author) {
1946 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1947 } elseif ($mesg->diaspora_handle) {
1948 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1953 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1954 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1955 $msg_text = XML::unescape($mesg->text);
1956 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1958 if ($msg_conversation_guid != $guid) {
1959 Logger::log("message conversation guid does not belong to the current conversation.");
1963 $body = Markdown::toBBCode($msg_text);
1964 $message_uri = $msg_author.":".$msg_guid;
1966 $person = self::personByHandle($msg_author);
1968 return Mail::insert([
1969 'uid' => $importer['uid'],
1970 'guid' => $msg_guid,
1971 'convid' => $conversation['id'],
1972 'from-name' => $person['name'],
1973 'from-photo' => $person['photo'],
1974 'from-url' => $person['url'],
1975 'contact-id' => $contact['id'],
1976 'title' => $subject,
1978 'uri' => $message_uri,
1979 'parent-uri' => $author . ':' . $guid,
1980 'created' => $msg_created_at
1985 * Processes new private messages (answers to private messages are processed elsewhere)
1987 * @param array $importer Array of the importer user
1988 * @param array $msg Array of the processed message, author handle and key
1989 * @param object $data The message object
1991 * @return bool Success
1992 * @throws \Exception
1994 private static function receiveConversation(array $importer, $msg, $data)
1996 $author = Strings::escapeTags(XML::unescape($data->author));
1997 $guid = Strings::escapeTags(XML::unescape($data->guid));
1998 $subject = Strings::escapeTags(XML::unescape($data->subject));
1999 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2000 $participants = Strings::escapeTags(XML::unescape($data->participants));
2002 $messages = $data->message;
2004 if (!count($messages)) {
2005 Logger::log("empty conversation");
2009 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2014 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2015 if (!DBA::isResult($conversation)) {
2017 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2018 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2019 intval($importer["uid"]),
2021 DBA::escape($author),
2022 DBA::escape($created_at),
2023 DBA::escape(DateTimeFormat::utcNow()),
2024 DBA::escape($subject),
2025 DBA::escape($participants)
2028 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2031 if (!$conversation) {
2032 Logger::log("unable to create conversation.");
2036 foreach ($messages as $mesg) {
2037 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2044 * Processes "like" messages
2046 * @param array $importer Array of the importer user
2047 * @param string $sender The sender of the message
2048 * @param object $data The message object
2050 * @return int The message id of the generated like or "false" if there was an error
2051 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2052 * @throws \ImagickException
2054 private static function receiveLike(array $importer, $sender, $data)
2056 $author = Strings::escapeTags(XML::unescape($data->author));
2057 $guid = Strings::escapeTags(XML::unescape($data->guid));
2058 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2059 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2060 $positive = Strings::escapeTags(XML::unescape($data->positive));
2062 // likes on comments aren't supported by Diaspora - only on posts
2063 // But maybe this will be supported in the future, so we will accept it.
2064 if (!in_array($parent_type, ["Post", "Comment"])) {
2068 $contact = self::allowedContactByHandle($importer, $sender, true);
2073 $message_id = self::messageExists($importer["uid"], $guid);
2078 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2079 if (!$parent_item) {
2083 $person = self::personByHandle($author);
2084 if (!is_array($person)) {
2085 Logger::log("unable to find author details");
2089 // Fetch the contact id - if we know this contact
2090 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2092 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2093 // We would accept this anyhow.
2094 if ($positive == "true") {
2095 $verb = Activity::LIKE;
2097 $verb = Activity::DISLIKE;
2102 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2104 $datarray["uid"] = $importer["uid"];
2105 $datarray["contact-id"] = $author_contact["cid"];
2106 $datarray["network"] = $author_contact["network"];
2108 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2109 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2111 $datarray["guid"] = $guid;
2112 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2114 $datarray["verb"] = $verb;
2115 $datarray["gravity"] = GRAVITY_ACTIVITY;
2116 $datarray["parent-uri"] = $parent_item["uri"];
2118 $datarray["object-type"] = Activity\ObjectType::NOTE;
2120 $datarray["body"] = $verb;
2122 // Diaspora doesn't provide a date for likes
2123 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2125 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2126 if ($parent_item['gravity'] != GRAVITY_PARENT) {
2127 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item['parent']]);
2128 $origin = $toplevel["origin"];
2130 $origin = $parent_item["origin"];
2133 // If we are the origin of the parent we store the original data.
2134 // We notify our followers during the item storage.
2136 $datarray['diaspora_signed_text'] = json_encode($data);
2139 $message_id = Item::insert($datarray);
2141 if ($message_id <= 0) {
2146 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2147 if ($datarray['uid'] == 0) {
2148 Item::distribute($message_id, json_encode($data));
2156 * Processes private messages
2158 * @param array $importer Array of the importer user
2159 * @param object $data The message object
2161 * @return bool Success?
2162 * @throws \Exception
2164 private static function receiveMessage(array $importer, $data)
2166 $author = Strings::escapeTags(XML::unescape($data->author));
2167 $guid = Strings::escapeTags(XML::unescape($data->guid));
2168 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2169 $text = XML::unescape($data->text);
2170 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2172 $contact = self::allowedContactByHandle($importer, $author, true);
2177 $conversation = null;
2179 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2180 $conversation = DBA::selectFirst('conv', [], $condition);
2182 if (!DBA::isResult($conversation)) {
2183 Logger::log("conversation not available.");
2187 $message_uri = $author.":".$guid;
2189 $person = self::personByHandle($author);
2191 Logger::log("unable to find author details");
2195 $body = Markdown::toBBCode($text);
2197 $body = self::replacePeopleGuid($body, $person["url"]);
2199 return Mail::insert([
2200 'uid' => $importer['uid'],
2202 'convid' => $conversation['id'],
2203 'from-name' => $person['name'],
2204 'from-photo' => $person['photo'],
2205 'from-url' => $person['url'],
2206 'contact-id' => $contact['id'],
2207 'title' => $conversation['subject'],
2210 'uri' => $message_uri,
2211 'parent-uri' => $author.":".$conversation['guid'],
2212 'created' => $created_at
2217 * Processes participations - unsupported by now
2219 * @param array $importer Array of the importer user
2220 * @param object $data The message object
2222 * @return bool success
2223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2224 * @throws \ImagickException
2226 private static function receiveParticipation(array $importer, $data)
2228 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2229 $guid = Strings::escapeTags(XML::unescape($data->guid));
2230 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2232 $contact = self::allowedContactByHandle($importer, $author, true);
2237 if (self::messageExists($importer["uid"], $guid)) {
2241 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2242 if (!$parent_item) {
2246 if (!$parent_item['origin']) {
2247 Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2250 if (!in_array($parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
2251 Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2255 $person = self::personByHandle($author);
2256 if (!is_array($person)) {
2257 Logger::log("Person not found: ".$author);
2261 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2263 // Store participation
2266 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2268 $datarray["uid"] = $importer["uid"];
2269 $datarray["contact-id"] = $author_contact["cid"];
2270 $datarray["network"] = $author_contact["network"];
2272 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2273 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2275 $datarray["guid"] = $guid;
2276 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2278 $datarray["verb"] = Activity::FOLLOW;
2279 $datarray["gravity"] = GRAVITY_ACTIVITY;
2280 $datarray["parent-uri"] = $parent_item["uri"];
2282 $datarray["object-type"] = Activity\ObjectType::NOTE;
2284 $datarray["body"] = Activity::FOLLOW;
2286 // Diaspora doesn't provide a date for a participation
2287 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2289 $message_id = Item::insert($datarray);
2291 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2293 // Send all existing comments and likes to the requesting server
2294 $comments = Item::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
2295 ['parent' => $parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
2296 while ($comment = Item::fetch($comments)) {
2297 if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2298 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2302 if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2303 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2307 if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2308 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2312 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2313 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2314 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2317 DBA::close($comments);
2323 * Processes photos - unneeded
2325 * @param array $importer Array of the importer user
2326 * @param object $data The message object
2328 * @return bool always true
2330 private static function receivePhoto(array $importer, $data)
2332 // There doesn't seem to be a reason for this function,
2333 // since the photo data is transmitted in the status message as well
2338 * Processes poll participations - unssupported
2340 * @param array $importer Array of the importer user
2341 * @param object $data The message object
2343 * @return bool always true
2345 private static function receivePollParticipation(array $importer, $data)
2347 // We don't support polls by now
2352 * Processes incoming profile updates
2354 * @param array $importer Array of the importer user
2355 * @param object $data The message object
2357 * @return bool Success
2358 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2359 * @throws \ImagickException
2361 private static function receiveProfile(array $importer, $data)
2363 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2365 $contact = self::contactByHandle($importer["uid"], $author);
2370 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2371 $image_url = XML::unescape($data->image_url);
2372 $birthday = XML::unescape($data->birthday);
2373 $about = Markdown::toBBCode(XML::unescape($data->bio));
2374 $location = Markdown::toBBCode(XML::unescape($data->location));
2375 $searchable = (XML::unescape($data->searchable) == "true");
2376 $nsfw = (XML::unescape($data->nsfw) == "true");
2377 $tags = XML::unescape($data->tag_string);
2379 $tags = explode("#", $tags);
2382 foreach ($tags as $tag) {
2383 $tag = trim(strtolower($tag));
2389 $keywords = implode(", ", $keywords);
2391 $handle_parts = explode("@", $author);
2392 $nick = $handle_parts[0];
2395 $name = $handle_parts[0];
2398 if (preg_match("|^https?://|", $image_url) === 0) {
2399 $image_url = "http://".$handle_parts[1].$image_url;
2402 Contact::updateAvatar($contact["id"], $image_url);
2404 // Generic birthday. We don't know the timezone. The year is irrelevant.
2406 $birthday = str_replace("1000", "1901", $birthday);
2408 if ($birthday != "") {
2409 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2412 // this is to prevent multiple birthday notifications in a single year
2413 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2415 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2416 $birthday = $contact["bd"];
2419 $fields = ['name' => $name, 'location' => $location,
2420 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2421 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2422 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2424 if (!empty($birthday)) {
2425 $fields['bd'] = $birthday;
2428 DBA::update('contact', $fields, ['id' => $contact['id']]);
2430 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2436 * Processes incoming friend requests
2438 * @param array $importer Array of the importer user
2439 * @param array $contact The contact that send the request
2441 * @throws \Exception
2443 private static function receiveRequestMakeFriend(array $importer, array $contact)
2445 if ($contact["rel"] == Contact::SHARING) {
2448 ['rel' => Contact::FRIEND, 'writable' => true],
2449 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2455 * Processes incoming sharing notification
2457 * @param array $importer Array of the importer user
2458 * @param object $data The message object
2460 * @return bool Success
2461 * @throws \Exception
2463 private static function receiveContactRequest(array $importer, $data)
2465 $author = XML::unescape($data->author);
2466 $recipient = XML::unescape($data->recipient);
2468 if (!$author || !$recipient) {
2472 // the current protocol version doesn't know these fields
2473 // That means that we will assume their existance
2474 if (isset($data->following)) {
2475 $following = (XML::unescape($data->following) == "true");
2480 if (isset($data->sharing)) {
2481 $sharing = (XML::unescape($data->sharing) == "true");
2486 $contact = self::contactByHandle($importer["uid"], $author);
2488 // perhaps we were already sharing with this person. Now they're sharing with us.
2489 // That makes us friends.
2492 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2493 self::receiveRequestMakeFriend($importer, $contact);
2495 // refetch the contact array
2496 $contact = self::contactByHandle($importer["uid"], $author);
2498 // If we are now friends, we are sending a share message.
2499 // Normally we needn't to do so, but the first message could have been vanished.
2500 if (in_array($contact["rel"], [Contact::FRIEND])) {
2501 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2502 if (DBA::isResult($user)) {
2503 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2504 self::sendShare($user, $contact);
2509 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2510 Contact::removeFollower($importer, $contact);
2515 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2516 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2518 } elseif (!$following && !$sharing) {
2519 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2521 } elseif (!$following && $sharing) {
2522 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2523 } elseif ($following && $sharing) {
2524 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2525 } elseif ($following && !$sharing) {
2526 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2529 $ret = self::personByHandle($author);
2531 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2532 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2536 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2538 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2543 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2544 'author-link' => $ret['url']];
2546 $result = Contact::addRelationship($importer, $contact, $item, false);
2547 if ($result === true) {
2548 $contact_record = self::contactByHandle($importer['uid'], $author);
2549 if (!$contact_record) {
2550 Logger::info('unable to locate newly created contact record.');
2554 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2555 if (DBA::isResult($user)) {
2556 self::sendShare($user, $contact_record);
2558 // Send the profile data, maybe it weren't transmitted before
2559 self::sendProfile($importer['uid'], [$contact_record]);
2567 * Fetches a message with a given guid
2569 * @param string $guid message guid
2570 * @param string $orig_author handle of the original post
2571 * @return array The fetched item
2572 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2573 * @throws \ImagickException
2575 public static function originalItem($guid, $orig_author)
2578 Logger::log('Empty guid. Quitting.');
2582 // Do we already have this item?
2583 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2584 'author-name', 'author-link', 'author-avatar', 'plink'];
2585 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2586 $item = Item::selectFirst($fields, $condition);
2588 if (DBA::isResult($item)) {
2589 Logger::log("reshared message ".$guid." already exists on system.");
2591 // Maybe it is already a reshared item?
2592 // Then refetch the content, if it is a reshare from a reshare.
2593 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2594 if (self::isReshare($item["body"], true)) {
2596 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2597 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2599 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2601 // Add OEmbed and other information to the body
2602 $item["body"] = PageInfo::searchAndAppendToBody($item["body"], false, true);
2610 if (!DBA::isResult($item)) {
2611 if (empty($orig_author)) {
2612 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2616 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2617 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2618 $stored = self::storeByGuid($guid, $server);
2621 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2622 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2623 $stored = self::storeByGuid($guid, $server);
2627 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2628 'author-name', 'author-link', 'author-avatar', 'plink'];
2629 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2630 $item = Item::selectFirst($fields, $condition);
2632 if (DBA::isResult($item)) {
2633 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2634 if (self::isReshare($item["body"], false)) {
2635 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2636 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2647 * Stores a reshare activity
2649 * @param array $item Array of reshare post
2650 * @param integer $parent_message_id Id of the parent post
2651 * @param string $guid GUID string of reshare action
2652 * @param string $author Author handle
2654 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2656 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2660 $datarray['uid'] = $item['uid'];
2661 $datarray['contact-id'] = $item['contact-id'];
2662 $datarray['network'] = $item['network'];
2664 $datarray['author-link'] = $item['author-link'];
2665 $datarray['author-id'] = $item['author-id'];
2667 $datarray['owner-link'] = $datarray['author-link'];
2668 $datarray['owner-id'] = $datarray['author-id'];
2670 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2671 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2672 $datarray['parent-uri'] = $parent['uri'];
2674 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2675 $datarray['gravity'] = GRAVITY_ACTIVITY;
2676 $datarray['object-type'] = Activity\ObjectType::NOTE;
2678 $datarray['protocol'] = $item['protocol'];
2680 $datarray['plink'] = self::plink($author, $datarray['guid']);
2681 $datarray['private'] = $item['private'];
2682 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2684 $message_id = Item::insert($datarray);
2687 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2688 if ($datarray['uid'] == 0) {
2689 Item::distribute($message_id);
2695 * Processes a reshare message
2697 * @param array $importer Array of the importer user
2698 * @param object $data The message object
2699 * @param string $xml The original XML of the message
2701 * @return int the message id
2702 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2703 * @throws \ImagickException
2705 private static function receiveReshare(array $importer, $data, $xml)
2707 $author = Strings::escapeTags(XML::unescape($data->author));
2708 $guid = Strings::escapeTags(XML::unescape($data->guid));
2709 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2710 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2711 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2712 /// @todo handle unprocessed property "provider_display_name"
2713 $public = Strings::escapeTags(XML::unescape($data->public));
2715 $contact = self::allowedContactByHandle($importer, $author, false);
2720 $message_id = self::messageExists($importer["uid"], $guid);
2725 $original_item = self::originalItem($root_guid, $root_author);
2726 if (!$original_item) {
2732 $datarray["uid"] = $importer["uid"];
2733 $datarray["contact-id"] = $contact["id"];
2734 $datarray["network"] = Protocol::DIASPORA;
2736 $datarray["author-link"] = $contact["url"];
2737 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2739 $datarray["owner-link"] = $datarray["author-link"];
2740 $datarray["owner-id"] = $datarray["author-id"];
2742 $datarray["guid"] = $guid;
2743 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2744 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2746 $datarray["verb"] = Activity::POST;
2747 $datarray["gravity"] = GRAVITY_PARENT;
2749 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2750 $datarray["source"] = $xml;
2752 /// @todo Copy tag data from original post
2754 $prefix = BBCode::getShareOpeningTag(
2755 $original_item["author-name"],
2756 $original_item["author-link"],
2757 $original_item["author-avatar"],
2758 $original_item["plink"],
2759 $original_item["created"],
2760 $original_item["guid"]
2763 if (!empty($original_item['title'])) {
2764 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2767 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2769 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2771 $datarray["attach"] = $original_item["attach"];
2772 $datarray["app"] = $original_item["app"];
2774 $datarray["plink"] = self::plink($author, $guid);
2775 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2776 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2778 $datarray["object-type"] = $original_item["object-type"];
2780 self::fetchGuid($datarray);
2781 $message_id = Item::insert($datarray);
2783 self::sendParticipation($contact, $datarray);
2785 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2786 if ($root_message_id) {
2787 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2791 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2792 if ($datarray['uid'] == 0) {
2793 Item::distribute($message_id);
2802 * Processes retractions
2804 * @param array $importer Array of the importer user
2805 * @param array $contact The contact of the item owner
2806 * @param object $data The message object
2808 * @return bool success
2809 * @throws \Exception
2811 private static function itemRetraction(array $importer, array $contact, $data)
2813 $author = Strings::escapeTags(XML::unescape($data->author));
2814 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2815 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2817 $person = self::personByHandle($author);
2818 if (!is_array($person)) {
2819 Logger::log("unable to find author detail for ".$author);
2823 if (empty($contact["url"])) {
2824 $contact["url"] = $person["url"];
2827 // Fetch items that are about to be deleted
2828 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2830 // When we receive a public retraction, we delete every item that we find.
2831 if ($importer['uid'] == 0) {
2832 $condition = ['guid' => $target_guid, 'deleted' => false];
2834 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2837 $r = Item::select($fields, $condition);
2838 if (!DBA::isResult($r)) {
2839 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2843 while ($item = Item::fetch($r)) {
2844 if (strstr($item['file'], '[')) {
2845 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2849 // Fetch the parent item
2850 $parent = Item::selectFirst(['author-link'], ['id' => $item['parent']]);
2852 // Only delete it if the parent author really fits
2853 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2854 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2858 Item::markForDeletion(['id' => $item['id']]);
2860 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent'], Logger::DEBUG);
2867 * Receives retraction messages
2869 * @param array $importer Array of the importer user
2870 * @param string $sender The sender of the message
2871 * @param object $data The message object
2873 * @return bool Success
2874 * @throws \Exception
2876 private static function receiveRetraction(array $importer, $sender, $data)
2878 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2880 $contact = self::contactByHandle($importer["uid"], $sender);
2881 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2882 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2890 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2892 switch ($target_type) {
2897 case "StatusMessage":
2898 return self::itemRetraction($importer, $contact, $data);
2900 case "PollParticipation":
2902 // Currently unsupported
2906 Logger::log("Unknown target type ".$target_type);
2913 * Receives status messages
2915 * @param array $importer Array of the importer user
2916 * @param SimpleXMLElement $data The message object
2917 * @param string $xml The original XML of the message
2919 * @return int The message id of the newly created item
2920 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2921 * @throws \ImagickException
2923 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2925 $author = Strings::escapeTags(XML::unescape($data->author));
2926 $guid = Strings::escapeTags(XML::unescape($data->guid));
2927 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2928 $public = Strings::escapeTags(XML::unescape($data->public));
2929 $text = XML::unescape($data->text);
2930 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2932 $contact = self::allowedContactByHandle($importer, $author, false);
2937 $message_id = self::messageExists($importer["uid"], $guid);
2943 if ($data->location) {
2944 foreach ($data->location->children() as $fieldname => $data) {
2945 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2949 $body = Markdown::toBBCode($text);
2953 // Attach embedded pictures to the body
2955 foreach ($data->photo as $photo) {
2956 $body = "[img]".XML::unescape($photo->remote_photo_path).
2957 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2960 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2962 $datarray["object-type"] = Activity\ObjectType::NOTE;
2964 // Add OEmbed and other information to the body
2965 if (!self::isHubzilla($contact["url"])) {
2966 $body = PageInfo::searchAndAppendToBody($body, false, true);
2970 /// @todo enable support for polls
2971 //if ($data->poll) {
2972 // foreach ($data->poll AS $poll)
2977 /// @todo enable support for events
2979 $datarray["uid"] = $importer["uid"];
2980 $datarray["contact-id"] = $contact["id"];
2981 $datarray["network"] = Protocol::DIASPORA;
2983 $datarray["author-link"] = $contact["url"];
2984 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2986 $datarray["owner-link"] = $datarray["author-link"];
2987 $datarray["owner-id"] = $datarray["author-id"];
2989 $datarray["guid"] = $guid;
2990 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2991 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2993 $datarray["verb"] = Activity::POST;
2994 $datarray["gravity"] = GRAVITY_PARENT;
2996 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2997 $datarray["source"] = $xml;
2999 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3001 self::storeMentions($datarray['uri-id'], $text);
3002 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
3004 if ($provider_display_name != "") {
3005 $datarray["app"] = $provider_display_name;
3008 $datarray["plink"] = self::plink($author, $guid);
3009 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3010 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3012 if (isset($address["address"])) {
3013 $datarray["location"] = $address["address"];
3016 if (isset($address["lat"]) && isset($address["lng"])) {
3017 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3020 self::fetchGuid($datarray);
3021 $message_id = Item::insert($datarray);
3023 self::sendParticipation($contact, $datarray);
3026 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3027 if ($datarray['uid'] == 0) {
3028 Item::distribute($message_id);
3036 /* ************************************************************************************** *
3037 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3038 * ************************************************************************************** */
3041 * returnes the handle of a contact
3043 * @param array $contact contact array
3045 * @return string the handle in the format user@domain.tld
3046 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3048 private static function myHandle(array $contact)
3050 if (!empty($contact["addr"])) {
3051 return $contact["addr"];
3054 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3055 // So - just in case - we build the the address here.
3056 if ($contact["nickname"] != "") {
3057 $nick = $contact["nickname"];
3059 $nick = $contact["nick"];
3062 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3067 * Creates the data for a private message in the new format
3069 * @param string $msg The message that is to be transmitted
3070 * @param array $user The record of the sender
3071 * @param array $contact Target of the communication
3072 * @param string $prvkey The private key of the sender
3073 * @param string $pubkey The public key of the receiver
3075 * @return string The encrypted data
3076 * @throws \Exception
3078 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3080 Logger::log("Message: ".$msg, Logger::DATA);
3082 // without a public key nothing will work
3084 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3088 $aes_key = openssl_random_pseudo_bytes(32);
3089 $b_aes_key = base64_encode($aes_key);
3090 $iv = openssl_random_pseudo_bytes(16);
3091 $b_iv = base64_encode($iv);
3093 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3095 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3097 $encrypted_key_bundle = "";
3098 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
3102 $json_object = json_encode(
3103 ["aes_key" => base64_encode($encrypted_key_bundle),
3104 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3107 return $json_object;
3111 * Creates the envelope for the "fetch" endpoint and for the new format
3113 * @param string $msg The message that is to be transmitted
3114 * @param array $user The record of the sender
3116 * @return string The envelope
3117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3119 public static function buildMagicEnvelope($msg, array $user)
3121 $b64url_data = Strings::base64UrlEncode($msg);
3122 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3124 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3125 $type = "application/xml";
3126 $encoding = "base64url";
3127 $alg = "RSA-SHA256";
3128 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3130 // Fallback if the private key wasn't transmitted in the expected field
3131 if ($user['uprvkey'] == "") {
3132 $user['uprvkey'] = $user['prvkey'];
3135 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3136 $sig = Strings::base64UrlEncode($signature);
3138 $xmldata = ["me:env" => ["me:data" => $data,
3139 "@attributes" => ["type" => $type],
3140 "me:encoding" => $encoding,
3143 "@attributes2" => ["key_id" => $key_id]]];
3145 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3147 return XML::fromArray($xmldata, $xml, false, $namespaces);
3151 * Create the envelope for a message
3153 * @param string $msg The message that is to be transmitted
3154 * @param array $user The record of the sender
3155 * @param array $contact Target of the communication
3156 * @param string $prvkey The private key of the sender
3157 * @param string $pubkey The public key of the receiver
3158 * @param bool $public Is the message public?
3160 * @return string The message that will be transmitted to other servers
3161 * @throws \Exception
3163 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3165 // The message is put into an envelope with the sender's signature
3166 $envelope = self::buildMagicEnvelope($msg, $user);
3168 // Private messages are put into a second envelope, encrypted with the receivers public key
3170 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3177 * Creates a signature for a message
3179 * @param array $owner the array of the owner of the message
3180 * @param array $message The message that is to be signed
3182 * @return string The signature
3184 private static function signature($owner, $message)
3187 unset($sigmsg["author_signature"]);
3188 unset($sigmsg["parent_author_signature"]);
3190 $signed_text = implode(";", $sigmsg);
3192 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3196 * Transmit a message to a target server
3198 * @param array $owner the array of the item owner
3199 * @param array $contact Target of the communication
3200 * @param string $envelope The message that is to be transmitted
3201 * @param bool $public_batch Is it a public post?
3202 * @param string $guid message guid
3204 * @return int Result of the transmission
3205 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3206 * @throws \ImagickException
3208 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3210 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3215 $logid = Strings::getRandomHex(4);
3217 // We always try to use the data from the fcontact table.
3218 // This is important for transmitting data to Friendica servers.
3219 if (!empty($contact['addr'])) {
3220 $fcontact = self::personByHandle($contact['addr']);
3221 if (!empty($fcontact)) {
3222 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3226 if (empty($dest_url)) {
3227 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3231 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3235 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3237 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3238 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3240 $postResult = DI::httpRequest()->post($dest_url . "/", $envelope, ["Content-Type: " . $content_type]);
3241 $return_code = $postResult->getReturnCode();
3243 Logger::log("test_mode");
3247 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3249 return $return_code ? $return_code : -1;
3254 * Build the post xml
3256 * @param string $type The message type
3257 * @param array $message The message data
3259 * @return string The post XML
3261 public static function buildPostXml($type, $message)
3263 $data = [$type => $message];
3265 return XML::fromArray($data, $xml);
3269 * Builds and transmit messages
3271 * @param array $owner the array of the item owner
3272 * @param array $contact Target of the communication
3273 * @param string $type The message type
3274 * @param array $message The message data
3275 * @param bool $public_batch Is it a public post?
3276 * @param string $guid message guid
3278 * @return int Result of the transmission
3279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3280 * @throws \ImagickException
3282 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3284 $msg = self::buildPostXml($type, $message);
3286 Logger::log('message: '.$msg, Logger::DATA);
3287 Logger::log('send guid '.$guid, Logger::DEBUG);
3289 // Fallback if the private key wasn't transmitted in the expected field
3290 if (empty($owner['uprvkey'])) {
3291 $owner['uprvkey'] = $owner['prvkey'];
3294 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3296 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3298 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3300 return $return_code;
3304 * sends a participation (Used to get all further updates)
3306 * @param array $contact Target of the communication
3307 * @param array $item Item array
3309 * @return int The result of the transmission
3310 * @throws \Exception
3312 private static function sendParticipation(array $contact, array $item)
3314 // Don't send notifications for private postings
3315 if ($item['private'] == Item::PRIVATE) {
3319 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3321 $result = DI::cache()->get($cachekey);
3322 if (!is_null($result)) {
3326 // Fetch some user id to have a valid handle to transmit the participation.
3327 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3328 // If the item belongs to a user, we take this user id.
3329 if ($item['uid'] == 0) {
3330 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3331 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3332 $owner = User::getOwnerDataById($first_user['uid']);
3334 $owner = User::getOwnerDataById($item['uid']);
3337 $author = self::myHandle($owner);
3339 $message = ["author" => $author,
3340 "guid" => System::createUUID(),
3341 "parent_type" => "Post",
3342 "parent_guid" => $item["guid"]];
3344 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3346 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3347 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3349 return self::buildAndTransmit($owner, $contact, "participation", $message);
3353 * sends an account migration
3355 * @param array $owner the array of the item owner
3356 * @param array $contact Target of the communication
3357 * @param int $uid User ID
3359 * @return int The result of the transmission
3360 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3361 * @throws \ImagickException
3363 public static function sendAccountMigration(array $owner, array $contact, $uid)
3365 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3366 $profile = self::createProfileData($uid);
3368 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3369 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3371 $message = ["author" => $old_handle,
3372 "profile" => $profile,
3373 "signature" => $signature];
3375 Logger::info('Send account migration', ['msg' => $message]);
3377 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3381 * Sends a "share" message
3383 * @param array $owner the array of the item owner
3384 * @param array $contact Target of the communication
3386 * @return int The result of the transmission
3387 * @throws \Exception
3389 public static function sendShare(array $owner, array $contact)
3392 * @todo support the different possible combinations of "following" and "sharing"
3393 * Currently, Diaspora only interprets the "sharing" field
3395 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3399 switch ($contact["rel"]) {
3400 case Contact::FRIEND:
3404 case Contact::SHARING:
3408 case Contact::FOLLOWER:
3414 $message = ["author" => self::myHandle($owner),
3415 "recipient" => $contact["addr"],
3416 "following" => "true",
3417 "sharing" => "true"];
3419 Logger::info('Send share', ['msg' => $message]);
3421 return self::buildAndTransmit($owner, $contact, "contact", $message);
3425 * sends an "unshare"
3427 * @param array $owner the array of the item owner
3428 * @param array $contact Target of the communication
3430 * @return int The result of the transmission
3431 * @throws \Exception
3433 public static function sendUnshare(array $owner, array $contact)
3435 $message = ["author" => self::myHandle($owner),
3436 "recipient" => $contact["addr"],
3437 "following" => "false",
3438 "sharing" => "false"];
3440 Logger::info('Send unshare', ['msg' => $message]);
3442 return self::buildAndTransmit($owner, $contact, "contact", $message);
3446 * Checks a message body if it is a reshare
3448 * @param string $body The message body that is to be check
3449 * @param bool $complete Should it be a complete check or a simple check?
3451 * @return array|bool Reshare details or "false" if no reshare
3452 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3453 * @throws \ImagickException
3455 public static function isReshare($body, $complete = true)
3457 $body = trim($body);
3459 $reshared = Item::getShareArray(['body' => $body]);
3460 if (empty($reshared)) {
3464 // Skip if it isn't a pure repeated messages
3465 // Does it start with a share?
3466 if (!empty($reshared['comment']) && $complete) {
3470 if (!empty($reshared['guid']) && $complete) {
3471 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3472 $item = Item::selectFirst(['contact-id'], $condition);
3473 if (DBA::isResult($item)) {
3475 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3476 $ret["root_guid"] = $reshared['guid'];
3478 } elseif ($complete) {
3479 // We are resharing something that isn't a DFRN or Diaspora post.
3480 // So we have to return "false" on "$complete" to not trigger a reshare.
3483 } elseif (empty($reshared['guid']) && $complete) {
3489 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3490 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3491 if (!empty($contact['addr'])) {
3492 $ret['root_handle'] = $contact['addr'];
3496 if (empty($ret) && !$complete) {
3504 * Create an event array
3506 * @param integer $event_id The id of the event
3508 * @return array with event data
3509 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3511 private static function buildEvent($event_id)
3513 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3514 if (!DBA::isResult($r)) {
3522 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3523 if (!DBA::isResult($r)) {
3529 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3530 if (!DBA::isResult($r)) {
3536 $eventdata['author'] = self::myHandle($owner);
3538 if ($event['guid']) {
3539 $eventdata['guid'] = $event['guid'];
3542 $mask = DateTimeFormat::ATOM;
3544 /// @todo - establish "all day" events in Friendica
3545 $eventdata["all_day"] = "false";
3547 $eventdata['timezone'] = 'UTC';
3548 if (!$event['adjust'] && $user['timezone']) {
3549 $eventdata['timezone'] = $user['timezone'];
3552 if ($event['start']) {
3553 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3555 if ($event['finish'] && !$event['nofinish']) {
3556 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3558 if ($event['summary']) {
3559 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3561 if ($event['desc']) {
3562 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3564 if ($event['location']) {
3565 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3566 $coord = Map::getCoordinates($event['location']);
3569 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3570 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3571 $location["lat"] = $coord['lat'];
3572 $location["lng"] = $coord['lon'];
3574 $location["lat"] = 0;
3575 $location["lng"] = 0;
3577 $eventdata['location'] = $location;
3584 * Create a post (status message or reshare)
3586 * @param array $item The item that will be exported
3587 * @param array $owner the array of the item owner
3590 * 'type' -> Message type ("status_message" or "reshare")
3591 * 'message' -> Array of XML elements of the status
3592 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3593 * @throws \ImagickException
3595 public static function buildStatus(array $item, array $owner)
3597 $cachekey = "diaspora:buildStatus:".$item['guid'];
3599 $result = DI::cache()->get($cachekey);
3600 if (!is_null($result)) {
3604 $myaddr = self::myHandle($owner);
3606 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3607 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3608 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3610 // Detect a share element and do a reshare
3611 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3612 $message = ["author" => $myaddr,
3613 "guid" => $item["guid"],
3614 "created_at" => $created,
3615 "root_author" => $ret["root_handle"],
3616 "root_guid" => $ret["root_guid"],
3617 "provider_display_name" => $item["app"],
3618 "public" => $public];
3622 $title = $item["title"];
3623 $body = $item["body"];
3625 // Fetch the title from an attached link - if there is one
3626 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3627 $page_data = BBCode::getAttachmentData($item['body']);
3628 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3629 $title = $page_data['title'];
3633 if ($item['author-link'] != $item['owner-link']) {
3634 require_once 'mod/share.php';
3635 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3636 $item['plink'], $item['created']) . $body . '[/share]';
3639 // convert to markdown
3640 $body = html_entity_decode(BBCode::toMarkdown($body));
3643 if (strlen($title)) {
3644 $body = "### ".html_entity_decode($title)."\n\n".$body;
3647 if ($item["attach"]) {
3648 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3650 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3651 foreach ($matches as $mtch) {
3652 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3659 if ($item["location"] != "")
3660 $location["address"] = $item["location"];
3662 if ($item["coord"] != "") {
3663 $coord = explode(" ", $item["coord"]);
3664 $location["lat"] = $coord[0];
3665 $location["lng"] = $coord[1];
3668 $message = ["author" => $myaddr,
3669 "guid" => $item["guid"],
3670 "created_at" => $created,
3671 "edited_at" => $edited,
3672 "public" => $public,
3674 "provider_display_name" => $item["app"],
3675 "location" => $location];
3677 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3678 if (!isset($location["lat"]) || !isset($location["lng"])) {
3679 unset($message["location"]);
3682 if ($item['event-id'] > 0) {
3683 $event = self::buildEvent($item['event-id']);
3684 if (count($event)) {
3685 $message['event'] = $event;
3687 if (!empty($event['location']['address']) &&
3688 !empty($event['location']['lat']) &&
3689 !empty($event['location']['lng'])) {
3690 $message['location'] = $event['location'];
3693 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3694 // $message['text'] = '';
3698 $type = "status_message";
3701 $msg = ["type" => $type, "message" => $message];
3703 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3708 private static function prependParentAuthorMention($body, $profile_url)
3710 $profile = Contact::getByURL($profile_url, false, ['addr', 'name', 'contact-type']);
3711 if (!empty($profile['addr'])
3712 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3713 && !strstr($body, $profile['addr'])
3714 && !strstr($body, $profile_url)
3716 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3725 * @param array $item The item that will be exported
3726 * @param array $owner the array of the item owner
3727 * @param array $contact Target of the communication
3728 * @param bool $public_batch Is it a public post?
3730 * @return int The result of the transmission
3731 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3732 * @throws \ImagickException
3734 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3736 $status = self::buildStatus($item, $owner);
3738 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3742 * Creates a "like" object
3744 * @param array $item The item that will be exported
3745 * @param array $owner the array of the item owner
3747 * @return array The data for a "like"
3748 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3750 private static function constructLike(array $item, array $owner)
3752 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3753 if (!DBA::isResult($parent)) {
3757 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3759 if ($item['verb'] === Activity::LIKE) {
3761 } elseif ($item['verb'] === Activity::DISLIKE) {
3762 $positive = "false";
3765 return(["author" => self::myHandle($owner),
3766 "guid" => $item["guid"],
3767 "parent_guid" => $parent["guid"],
3768 "parent_type" => $target_type,
3769 "positive" => $positive,
3770 "author_signature" => ""]);
3774 * Creates an "EventParticipation" object
3776 * @param array $item The item that will be exported
3777 * @param array $owner the array of the item owner
3779 * @return array The data for an "EventParticipation"
3780 * @throws \Exception
3782 private static function constructAttend(array $item, array $owner)
3784 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3785 if (!DBA::isResult($parent)) {
3789 switch ($item['verb']) {
3790 case Activity::ATTEND:
3791 $attend_answer = 'accepted';
3793 case Activity::ATTENDNO:
3794 $attend_answer = 'declined';
3796 case Activity::ATTENDMAYBE:
3797 $attend_answer = 'tentative';
3800 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3804 return(["author" => self::myHandle($owner),
3805 "guid" => $item["guid"],
3806 "parent_guid" => $parent["guid"],
3807 "status" => $attend_answer,
3808 "author_signature" => ""]);
3812 * Creates the object for a comment
3814 * @param array $item The item that will be exported
3815 * @param array $owner the array of the item owner
3817 * @return array|false The data for a comment
3818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3820 private static function constructComment(array $item, array $owner)
3822 $cachekey = "diaspora:constructComment:".$item['guid'];
3824 $result = DI::cache()->get($cachekey);
3825 if (!is_null($result)) {
3829 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3830 if (!DBA::isResult($toplevel_item)) {
3831 Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3835 $thread_parent_item = $toplevel_item;
3836 if ($item['thr-parent'] != $item['parent-uri']) {
3837 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3840 $body = $item["body"];
3842 // The replied to autor mention is prepended for clarity if:
3843 // - Item replied isn't yours
3844 // - Item is public or explicit mentions are disabled
3845 // - Implicit mentions are enabled
3847 $item['author-id'] != $thread_parent_item['author-id']
3848 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3849 && !DI::config()->get('system', 'disable_implicit_mentions')
3851 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3854 $text = html_entity_decode(BBCode::toMarkdown($body));
3855 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3856 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3859 "author" => self::myHandle($owner),
3860 "guid" => $item["guid"],
3861 "created_at" => $created,
3862 "edited_at" => $edited,
3863 "parent_guid" => $toplevel_item["guid"],
3865 "author_signature" => ""
3868 // Send the thread parent guid only if it is a threaded comment
3869 if ($item['thr-parent'] != $item['parent-uri']) {
3870 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3873 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3879 * Send a like or a comment
3881 * @param array $item The item that will be exported
3882 * @param array $owner the array of the item owner
3883 * @param array $contact Target of the communication
3884 * @param bool $public_batch Is it a public post?
3886 * @return int The result of the transmission
3887 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3888 * @throws \ImagickException
3890 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3892 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3893 $message = self::constructAttend($item, $owner);
3894 $type = "event_participation";
3895 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3896 $message = self::constructLike($item, $owner);
3898 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3899 $message = self::constructComment($item, $owner);
3903 if (empty($message)) {
3907 $message["author_signature"] = self::signature($owner, $message);
3909 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3913 * Creates a message from a signature record entry
3915 * @param array $item The item that will be exported
3916 * @return array The message
3918 private static function messageFromSignature(array $item)
3920 // Split the signed text
3921 $signed_parts = explode(";", $item['signed_text']);
3923 if ($item["deleted"]) {
3924 $message = ["author" => $item['signer'],
3925 "target_guid" => $signed_parts[0],
3926 "target_type" => $signed_parts[1]];
3927 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3928 $message = ["author" => $signed_parts[4],
3929 "guid" => $signed_parts[1],
3930 "parent_guid" => $signed_parts[3],
3931 "parent_type" => $signed_parts[2],
3932 "positive" => $signed_parts[0],
3933 "author_signature" => $item['signature'],
3934 "parent_author_signature" => ""];
3936 // Remove the comment guid
3937 $guid = array_shift($signed_parts);
3939 // Remove the parent guid
3940 $parent_guid = array_shift($signed_parts);
3942 // Remove the handle
3943 $handle = array_pop($signed_parts);
3946 "author" => $handle,
3948 "parent_guid" => $parent_guid,
3949 "text" => implode(";", $signed_parts),
3950 "author_signature" => $item['signature'],
3951 "parent_author_signature" => ""
3958 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3960 * @param array $item The item that will be exported
3961 * @param array $owner the array of the item owner
3962 * @param array $contact Target of the communication
3963 * @param bool $public_batch Is it a public post?
3965 * @return int The result of the transmission
3966 * @throws \Exception
3968 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3970 if ($item["deleted"]) {
3971 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3972 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3978 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3980 $msg = json_decode($item['signed_text'], true);
3983 if (is_array($msg)) {
3984 foreach ($msg as $field => $data) {
3985 if (!$item["deleted"]) {
3986 if ($field == "diaspora_handle") {
3989 if ($field == "target_type") {
3990 $field = "parent_type";
3994 $message[$field] = $data;
3997 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4000 $message["parent_author_signature"] = self::signature($owner, $message);
4002 Logger::info('Relayed data', ['msg' => $message]);
4004 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4008 * Sends a retraction (deletion) of a message, like or comment
4010 * @param array $item The item that will be exported
4011 * @param array $owner the array of the item owner
4012 * @param array $contact Target of the communication
4013 * @param bool $public_batch Is it a public post?
4014 * @param bool $relay Is the retraction transmitted from a relay?
4016 * @return int The result of the transmission
4017 * @throws \Exception
4019 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4021 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4023 $msg_type = "retraction";
4025 if ($item['gravity'] == GRAVITY_PARENT) {
4026 $target_type = "Post";
4027 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4028 $target_type = "Like";
4030 $target_type = "Comment";
4033 $message = ["author" => $itemaddr,
4034 "target_guid" => $item['guid'],
4035 "target_type" => $target_type];
4037 Logger::info('Got message', ['msg' => $message]);
4039 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4045 * @param array $item The item that will be exported
4046 * @param array $owner The owner
4047 * @param array $contact Target of the communication
4049 * @return int The result of the transmission
4050 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4051 * @throws \ImagickException
4053 public static function sendMail(array $item, array $owner, array $contact)
4055 $myaddr = self::myHandle($owner);
4057 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4058 if (!DBA::isResult($cnv)) {
4059 Logger::log("conversation not found.");
4063 $body = BBCode::toMarkdown($item["body"]);
4064 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4067 "author" => $myaddr,
4068 "guid" => $item["guid"],
4069 "conversation_guid" => $cnv["guid"],
4071 "created_at" => $created,
4074 if ($item["reply"]) {
4079 "author" => $cnv["creator"],
4080 "guid" => $cnv["guid"],
4081 "subject" => $cnv["subject"],
4082 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4083 "participants" => $cnv["recips"],
4087 $type = "conversation";
4090 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4094 * Split a name into first name and last name
4096 * @param string $name The name
4098 * @return array The array with "first" and "last"
4100 public static function splitName($name) {
4101 $name = trim($name);
4103 // Is the name longer than 64 characters? Then cut the rest of it.
4104 if (strlen($name) > 64) {
4105 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4106 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4108 $name = substr($name, 0, 64);
4112 // Take the first word as first name
4113 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4114 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4115 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4116 return ['first' => $first, 'last' => $last];
4119 // Take the last word as last name
4120 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4121 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4123 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4124 return ['first' => $first, 'last' => $last];
4127 // Take the first 32 characters if there is no space in the first 32 characters
4128 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4129 $first = substr($name, 0, 32);
4130 $last = substr($name, 32);
4131 return ['first' => $first, 'last' => $last];
4134 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4135 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4137 // Check if the last name is longer than 32 characters
4138 if (strlen($last) > 32) {
4139 if (strpos($last, ' ') <= 32) {
4140 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4142 $last = substr($last, 0, 32);
4146 return ['first' => $first, 'last' => $last];
4150 * Create profile data
4152 * @param int $uid The user id
4154 * @return array The profile data
4155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4157 private static function createProfileData($uid)
4159 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4160 if (!DBA::isResult($profile)) {
4164 $handle = $profile["addr"];
4166 $split_name = self::splitName($profile['name']);
4167 $first = $split_name['first'];
4168 $last = $split_name['last'];
4170 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4171 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4172 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4173 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4179 if ($searchable === 'true') {
4182 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4183 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4187 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4190 $about = BBCode::toMarkdown($profile['about']);
4192 $location = $profile['location'];
4194 if ($profile['pub_keywords']) {
4195 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4196 $kw = str_replace(' ', ' ', $kw);
4197 $arr = explode(' ', $kw);
4199 for ($x = 0; $x < 5; $x ++) {
4200 if (!empty($arr[$x])) {
4201 $tags .= '#'. trim($arr[$x]) .' ';
4206 $tags = trim($tags);
4209 return ["author" => $handle,
4210 "first_name" => $first,
4211 "last_name" => $last,
4212 "image_url" => $large,
4213 "image_url_medium" => $medium,
4214 "image_url_small" => $small,
4217 "location" => $location,
4218 "searchable" => $searchable,
4220 "tag_string" => $tags];
4224 * Sends profile data
4226 * @param int $uid The user id
4227 * @param bool $recips optional, default false
4229 * @throws \Exception
4231 public static function sendProfile($uid, $recips = false)
4237 $owner = User::getOwnerDataById($uid);
4244 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4245 AND `uid` = %d AND `rel` != %d",
4246 DBA::escape(Protocol::DIASPORA),
4248 intval(Contact::SHARING)
4256 $message = self::createProfileData($uid);
4258 // @ToDo Split this into single worker jobs
4259 foreach ($recips as $recip) {
4260 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4261 self::buildAndTransmit($owner, $recip, "profile", $message);
4266 * Creates the signature for likes that are created on our system
4268 * @param integer $uid The user of that comment
4269 * @param array $item Item array
4271 * @return array Signed content
4272 * @throws \Exception
4274 public static function createLikeSignature($uid, array $item)
4276 $owner = User::getOwnerDataById($uid);
4277 if (empty($owner)) {
4278 Logger::info('No owner post, so not storing signature');
4282 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4286 $message = self::constructLike($item, $owner);
4287 if ($message === false) {
4291 $message["author_signature"] = self::signature($owner, $message);
4297 * Creates the signature for Comments that are created on our system
4299 * @param integer $uid The user of that comment
4300 * @param array $item Item array
4302 * @return array Signed content
4303 * @throws \Exception
4305 public static function createCommentSignature($uid, array $item)
4307 $owner = User::getOwnerDataById($uid);
4308 if (empty($owner)) {
4309 Logger::info('No owner post, so not storing signature');
4313 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4314 $item['thr-parent'] = $item['parent-uri'];
4316 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4317 if (!DBA::isResult($parent)) {
4321 $item['parent-uri'] = $parent['parent-uri'];
4323 $message = self::constructComment($item, $owner);
4324 if ($message === false) {
4328 $message["author_signature"] = self::signature($owner, $message);