3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GContact;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\Probe;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Map;
47 use Friendica\Util\Network;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
50 use Friendica\Worker\Delivery;
54 * This class contain functions to create and send Diaspora XML files
59 * Mark the relay contact of the given contact for archival
60 * This is called whenever there is a communication issue with the server.
61 * It avoids sending stuff to servers who don't exist anymore.
62 * The relay contact is a technical contact entry that exists once per server.
64 * @param array $contact of the relay contact
66 public static function markRelayForArchival(array $contact)
68 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
69 // This is already the relay contact, we don't need to fetch it
70 $relay_contact = $contact;
71 } elseif (empty($contact['baseurl'])) {
72 if (!empty($contact['batch'])) {
73 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
74 $relay_contact = DBA::selectFirst('contact', [], $condition);
79 $relay_contact = self::getRelayContact($contact['baseurl'], []);
82 if (!empty($relay_contact)) {
83 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
84 Contact::markForArchival($relay_contact);
89 * Return a list of relay servers
91 * The list contains not only the official relays but also servers that we serve directly
93 * @param integer $item_id The id of the item that is sent
94 * @param array $contacts The previously fetched contacts
96 * @return array of relay servers
97 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
99 public static function relayList($item_id, array $contacts = [])
103 // Fetching relay servers
104 $serverdata = DI::config()->get("system", "relay_server");
106 if (!empty($serverdata)) {
107 $servers = explode(",", $serverdata);
108 foreach ($servers as $server) {
109 $serverlist[$server] = trim($server);
113 if (DI::config()->get("system", "relay_directly", false)) {
114 // We distribute our stuff based on the parent to ensure that the thread will be complete
115 $parent = Item::selectFirst(['uri-id'], ['id' => $item_id]);
116 if (!DBA::isResult($parent)) {
120 // Servers that want to get all content
121 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
122 while ($server = DBA::fetch($servers)) {
123 $serverlist[$server['url']] = $server['url'];
125 DBA::close($servers);
127 // All tags of the current post
128 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
130 while ($tag = DBA::fetch($tags)) {
131 $taglist[] = $tag['name'];
135 // All servers who wants content with this tag
137 if (!empty($taglist)) {
138 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
139 while ($server = DBA::fetch($tagserver)) {
140 $tagserverlist[] = $server['gserver-id'];
142 DBA::close($tagserver);
145 // All adresses with the given id
146 if (!empty($tagserverlist)) {
147 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
148 while ($server = DBA::fetch($servers)) {
149 $serverlist[$server['url']] = $server['url'];
151 DBA::close($servers);
155 // Now we are collecting all relay contacts
156 foreach ($serverlist as $server_url) {
157 // We don't send messages to ourselves
158 if (Strings::compareLink($server_url, DI::baseUrl())) {
161 $contact = self::getRelayContact($server_url);
162 if (is_bool($contact)) {
167 foreach ($contacts as $entry) {
168 if ($entry['batch'] == $contact['batch']) {
174 $contacts[] = $contact;
182 * Return a contact for a given server address or creates a dummy entry
184 * @param string $server_url The url of the server
185 * @param array $fields Fieldlist
186 * @return array with the contact
189 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
191 // Fetch the relay contact
192 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
193 'contact-type' => Contact::TYPE_RELAY];
194 $contact = DBA::selectFirst('contact', $fields, $condition);
196 if (DBA::isResult($contact)) {
197 if ($contact['archive'] || $contact['blocked']) {
202 self::setRelayContact($server_url);
204 $contact = DBA::selectFirst('contact', $fields, $condition);
205 if (DBA::isResult($contact)) {
210 // It should never happen that we arrive here
215 * Update or insert a relay contact
217 * @param string $server_url The url of the server
218 * @param array $network_fields Optional network specific fields
221 public static function setRelayContact($server_url, array $network_fields = [])
223 $fields = ['created' => DateTimeFormat::utcNow(),
224 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
225 'nurl' => Strings::normaliseLink($server_url),
226 'network' => Protocol::DIASPORA, 'uid' => 0,
227 'batch' => $server_url . '/receive/public',
228 'rel' => Contact::FOLLOWER, 'blocked' => false,
229 'pending' => false, 'writable' => true,
230 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
232 $fields = array_merge($fields, $network_fields);
234 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
235 $old = DBA::selectFirst('contact', [], $condition);
236 if (DBA::isResult($old)) {
237 unset($fields['created']);
238 $condition = ['id' => $old['id']];
240 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
241 DBA::update('contact', $fields, $condition, $old);
243 Logger::info('Create relay contact', ['fields' => $fields]);
244 Contact::insert($fields);
249 * Return a list of participating contacts for a thread
251 * This is used for the participation feature.
252 * One of the parameters is a contact array.
253 * This is done to avoid duplicates.
255 * @param integer $thread The id of the thread
256 * @param array $contacts The previously fetched contacts
258 * @return array of relay servers
261 public static function participantsForThread($thread, array $contacts)
263 $participation = DBA::select('participation-view', [], ['iid' => $thread]);
265 while ($contact = DBA::fetch($participation)) {
266 if (empty($contact['protocol'])) {
267 $contact['protocol'] = $contact['network'];
271 foreach ($contacts as $entry) {
272 if ($entry['batch'] == $contact['batch']) {
278 $contacts[] = $contact;
282 DBA::close($participation);
288 * repairs a signature that was double encoded
290 * The function is unused at the moment. It was copied from the old implementation.
292 * @param string $signature The signature
293 * @param string $handle The handle of the signature owner
294 * @param integer $level This value is only set inside this function to avoid endless loops
296 * @return string the repaired signature
299 private static function repairSignature($signature, $handle = "", $level = 1)
301 if ($signature == "") {
305 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
306 $signature = base64_decode($signature);
307 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
309 // Do a recursive call to be able to fix even multiple levels
311 $signature = self::repairSignature($signature, $handle, ++$level);
319 * verify the envelope and return the verified data
321 * @param string $envelope The magic envelope
323 * @return string verified data
324 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
325 * @throws \ImagickException
327 private static function verifyMagicEnvelope($envelope)
329 $basedom = XML::parseString($envelope, true);
331 if (!is_object($basedom)) {
332 Logger::log("Envelope is no XML file");
336 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
338 if (sizeof($children) == 0) {
339 Logger::log("XML has no children");
345 $data = Strings::base64UrlDecode($children->data);
346 $type = $children->data->attributes()->type[0];
348 $encoding = $children->encoding;
350 $alg = $children->alg;
352 $sig = Strings::base64UrlDecode($children->sig);
353 $key_id = $children->sig->attributes()->key_id[0];
355 $handle = Strings::base64UrlDecode($key_id);
358 $b64url_data = Strings::base64UrlEncode($data);
359 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
361 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
364 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
368 $key = self::key($handle);
370 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
374 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
376 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
384 * encrypts data via AES
386 * @param string $key The AES key
387 * @param string $iv The IV (is used for CBC encoding)
388 * @param string $data The data that is to be encrypted
390 * @return string encrypted data
392 private static function aesEncrypt($key, $iv, $data)
394 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
398 * decrypts data via AES
400 * @param string $key The AES key
401 * @param string $iv The IV (is used for CBC encoding)
402 * @param string $encrypted The encrypted data
404 * @return string decrypted data
406 private static function aesDecrypt($key, $iv, $encrypted)
408 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
412 * Decodes incoming Diaspora message in the new format
414 * @param string $raw raw post message
415 * @param string $privKey The private key of the importer
416 * @param boolean $no_exit Don't do an http exit on error
419 * 'message' -> decoded Diaspora XML message
420 * 'author' -> author diaspora handle
421 * 'key' -> author public key (converted to pkcs#8)
422 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
423 * @throws \ImagickException
425 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
427 $data = json_decode($raw);
429 // Is it a private post? Then decrypt the outer Salmon
430 if (is_object($data)) {
431 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
432 $ciphertext = base64_decode($data->encrypted_magic_envelope);
434 $outer_key_bundle = '';
435 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
436 $j_outer_key_bundle = json_decode($outer_key_bundle);
438 if (!is_object($j_outer_key_bundle)) {
439 Logger::log('Outer Salmon did not verify. Discarding.');
443 throw new \Friendica\Network\HTTPException\BadRequestException();
447 $outer_iv = base64_decode($j_outer_key_bundle->iv);
448 $outer_key = base64_decode($j_outer_key_bundle->key);
450 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
455 $basedom = XML::parseString($xml, true);
457 if (!is_object($basedom)) {
458 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
462 throw new \Friendica\Network\HTTPException\BadRequestException();
466 $base = $basedom->children(ActivityNamespace::SALMON_ME);
468 // Not sure if this cleaning is needed
469 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
471 // Build the signed data
472 $type = $base->data[0]->attributes()->type[0];
473 $encoding = $base->encoding;
475 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
477 // This is the signature
478 $signature = Strings::base64UrlDecode($base->sig);
480 // Get the senders' public key
481 $key_id = $base->sig[0]->attributes()->key_id[0];
482 $author_addr = base64_decode($key_id);
483 if ($author_addr == '') {
484 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
488 throw new \Friendica\Network\HTTPException\BadRequestException();
492 $key = self::key($author_addr);
494 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
498 throw new \Friendica\Network\HTTPException\BadRequestException();
502 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
504 Logger::log('Message did not verify. Discarding.');
508 throw new \Friendica\Network\HTTPException\BadRequestException();
512 return ['message' => (string)Strings::base64UrlDecode($base->data),
513 'author' => XML::unescape($author_addr),
514 'key' => (string)$key];
518 * Decodes incoming Diaspora message in the deprecated format
520 * @param string $xml urldecoded Diaspora salmon
521 * @param string $privKey The private key of the importer
524 * 'message' -> decoded Diaspora XML message
525 * 'author' -> author diaspora handle
526 * 'key' -> author public key (converted to pkcs#8)
527 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
528 * @throws \ImagickException
530 public static function decode(string $xml, string $privKey = '')
533 $basedom = XML::parseString($xml);
535 if (!is_object($basedom)) {
536 Logger::log("XML is not parseable.");
539 $children = $basedom->children('https://joindiaspora.com/protocol');
541 $inner_aes_key = null;
544 if ($children->header) {
546 $author_link = str_replace('acct:', '', $children->header->author_id);
548 // This happens with posts from a relais
549 if (empty($privKey)) {
550 Logger::log("This is no private post in the old format", Logger::DEBUG);
554 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
556 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
557 $ciphertext = base64_decode($encrypted_header->ciphertext);
559 $outer_key_bundle = '';
560 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
562 $j_outer_key_bundle = json_decode($outer_key_bundle);
564 $outer_iv = base64_decode($j_outer_key_bundle->iv);
565 $outer_key = base64_decode($j_outer_key_bundle->key);
567 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
569 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
570 $idom = XML::parseString($decrypted);
572 $inner_iv = base64_decode($idom->iv);
573 $inner_aes_key = base64_decode($idom->aes_key);
575 $author_link = str_replace('acct:', '', $idom->author_id);
578 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
580 // figure out where in the DOM tree our data is hiding
583 if ($dom->provenance->data) {
584 $base = $dom->provenance;
585 } elseif ($dom->env->data) {
587 } elseif ($dom->data) {
592 Logger::log('unable to locate salmon data in xml');
593 throw new \Friendica\Network\HTTPException\BadRequestException();
597 // Stash the signature away for now. We have to find their key or it won't be good for anything.
598 $signature = Strings::base64UrlDecode($base->sig);
602 // strip whitespace so our data element will return to one big base64 blob
603 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
606 // stash away some other stuff for later
608 $type = $base->data[0]->attributes()->type[0];
609 $keyhash = $base->sig[0]->attributes()->keyhash[0];
610 $encoding = $base->encoding;
614 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
618 $data = Strings::base64UrlDecode($data);
622 $inner_decrypted = $data;
624 // Decode the encrypted blob
625 $inner_encrypted = base64_decode($data);
626 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
630 Logger::log('Could not retrieve author URI.');
631 throw new \Friendica\Network\HTTPException\BadRequestException();
633 // Once we have the author URI, go to the web and try to find their public key
634 // (first this will look it up locally if it is in the fcontact cache)
635 // This will also convert diaspora public key from pkcs#1 to pkcs#8
637 Logger::log('Fetching key for '.$author_link);
638 $key = self::key($author_link);
641 Logger::log('Could not retrieve author key.');
642 throw new \Friendica\Network\HTTPException\BadRequestException();
645 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
648 Logger::log('Message did not verify. Discarding.');
649 throw new \Friendica\Network\HTTPException\BadRequestException();
652 Logger::log('Message verified.');
654 return ['message' => (string)$inner_decrypted,
655 'author' => XML::unescape($author_link),
656 'key' => (string)$key];
661 * Dispatches public messages and find the fitting receivers
663 * @param array $msg The post that will be dispatched
665 * @return int The message id of the generated message, "true" or "false" if there was an error
666 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
667 * @throws \ImagickException
669 public static function dispatchPublic($msg)
671 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
673 Logger::log("diaspora is disabled");
677 if (!($fields = self::validPosting($msg))) {
678 Logger::log("Invalid posting");
682 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
683 $success = self::dispatch($importer, $msg, $fields);
689 * Dispatches the different message types to the different functions
691 * @param array $importer Array of the importer user
692 * @param array $msg The post that will be dispatched
693 * @param SimpleXMLElement $fields SimpleXML object that contains the message
695 * @return int The message id of the generated message, "true" or "false" if there was an error
696 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
697 * @throws \ImagickException
699 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
701 // The sender is the handle of the contact that sent the message.
702 // This will often be different with relayed messages (for example "like" and "comment")
703 $sender = $msg["author"];
705 // This is only needed for private postings since this is already done for public ones before
706 if (is_null($fields)) {
708 if (!($fields = self::validPosting($msg))) {
709 Logger::log("Invalid posting");
716 $type = $fields->getName();
718 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
721 case "account_migration":
723 Logger::log('Message with type ' . $type . ' is not private, quitting.');
726 return self::receiveAccountMigration($importer, $fields);
728 case "account_deletion":
729 return self::receiveAccountDeletion($fields);
732 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
736 Logger::log('Message with type ' . $type . ' is not private, quitting.');
739 return self::receiveContactRequest($importer, $fields);
743 Logger::log('Message with type ' . $type . ' is not private, quitting.');
746 return self::receiveConversation($importer, $msg, $fields);
749 return self::receiveLike($importer, $sender, $fields);
753 Logger::log('Message with type ' . $type . ' is not private, quitting.');
756 return self::receiveMessage($importer, $fields);
758 case "participation":
760 Logger::log('Message with type ' . $type . ' is not private, quitting.');
763 return self::receiveParticipation($importer, $fields);
765 case "photo": // Not implemented
766 return self::receivePhoto($importer, $fields);
768 case "poll_participation": // Not implemented
769 return self::receivePollParticipation($importer, $fields);
773 Logger::log('Message with type ' . $type . ' is not private, quitting.');
776 return self::receiveProfile($importer, $fields);
779 return self::receiveReshare($importer, $fields, $msg["message"]);
782 return self::receiveRetraction($importer, $sender, $fields);
784 case "status_message":
785 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
788 Logger::log("Unknown message type ".$type);
794 * Checks if a posting is valid and fetches the data fields.
796 * This function does not only check the signature.
797 * It also does the conversion between the old and the new diaspora format.
799 * @param array $msg Array with the XML, the sender handle and the sender signature
801 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
802 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
803 * @throws \ImagickException
805 private static function validPosting($msg)
807 $data = XML::parseString($msg["message"]);
809 if (!is_object($data)) {
810 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
814 // Is this the new or the old version?
815 if ($data->getName() == "XML") {
817 foreach ($data->post->children() as $child) {
825 $type = $element->getName();
828 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
830 // All retractions are handled identically from now on.
831 // In the new version there will only be "retraction".
832 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
833 $type = "retraction";
835 if ($type == "request") {
839 $fields = new SimpleXMLElement("<".$type."/>");
842 $author_signature = null;
843 $parent_author_signature = null;
845 foreach ($element->children() as $fieldname => $entry) {
847 // Translation for the old XML structure
848 if ($fieldname == "diaspora_handle") {
849 $fieldname = "author";
851 if ($fieldname == "participant_handles") {
852 $fieldname = "participants";
854 if (in_array($type, ["like", "participation"])) {
855 if ($fieldname == "target_type") {
856 $fieldname = "parent_type";
859 if ($fieldname == "sender_handle") {
860 $fieldname = "author";
862 if ($fieldname == "recipient_handle") {
863 $fieldname = "recipient";
865 if ($fieldname == "root_diaspora_id") {
866 $fieldname = "root_author";
868 if ($type == "status_message") {
869 if ($fieldname == "raw_message") {
873 if ($type == "retraction") {
874 if ($fieldname == "post_guid") {
875 $fieldname = "target_guid";
877 if ($fieldname == "type") {
878 $fieldname = "target_type";
883 if (($fieldname == "author_signature") && ($entry != "")) {
884 $author_signature = base64_decode($entry);
885 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
886 $parent_author_signature = base64_decode($entry);
887 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
888 if ($signed_data != "") {
892 $signed_data .= $entry;
894 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
895 || ($orig_type == "relayable_retraction")
897 XML::copy($entry, $fields, $fieldname);
901 // This is something that shouldn't happen at all.
902 if (in_array($type, ["status_message", "reshare", "profile"])) {
903 if ($msg["author"] != $fields->author) {
904 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
909 // Only some message types have signatures. So we quit here for the other types.
910 if (!in_array($type, ["comment", "like"])) {
913 // No author_signature? This is a must, so we quit.
914 if (!isset($author_signature)) {
915 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
919 if (isset($parent_author_signature)) {
920 $key = self::key($msg["author"]);
922 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
926 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
927 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);
932 $key = self::key($fields->author);
934 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
938 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
939 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);
947 * Fetches the public key for a given handle
949 * @param string $handle The handle
951 * @return string The public key
952 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
953 * @throws \ImagickException
955 private static function key($handle)
957 $handle = strval($handle);
959 Logger::log("Fetching diaspora key for: ".$handle);
961 $r = self::personByHandle($handle);
970 * Fetches data for a given handle
972 * @param string $handle The handle
973 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
975 * @return array the queried data
976 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
977 * @throws \ImagickException
979 public static function personByHandle($handle, $update = null)
981 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
982 if (!DBA::isResult($person)) {
983 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
984 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
987 if (DBA::isResult($person)) {
988 Logger::debug("In cache " . print_r($person, true));
990 if (is_null($update)) {
991 // update record occasionally so it doesn't get stale
992 $d = strtotime($person["updated"]." +00:00");
993 if ($d < strtotime("now - 14 days")) {
997 if ($person["guid"] == "") {
1001 } elseif (is_null($update)) {
1002 $update = !DBA::isResult($person);
1008 Logger::log("create or refresh", Logger::DEBUG);
1009 $r = Probe::uri($handle, Protocol::DIASPORA);
1011 // Note that Friendica contacts will return a "Diaspora person"
1012 // if Diaspora connectivity is enabled on their server
1013 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1014 self::updateFContact($r);
1016 $person = self::personByHandle($handle, false);
1024 * Updates the fcontact table
1026 * @param array $arr The fcontact data
1027 * @throws \Exception
1029 private static function updateFContact($arr)
1031 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1032 'request' => $arr["request"], 'nick' => $arr["nick"],
1033 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1034 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1035 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1036 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1037 'updated' => DateTimeFormat::utcNow()];
1039 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1041 DBA::update('fcontact', $fields, $condition, true);
1045 * get a handle (user@domain.tld) from a given contact id
1047 * @param int $contact_id The id in the contact table
1048 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1050 * @return string the handle
1051 * @throws \Exception
1053 private static function handleFromContact($contact_id, $pcontact_id = 0)
1057 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1059 if ($pcontact_id != 0) {
1060 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1062 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1063 return strtolower($contact["addr"]);
1068 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1072 if (DBA::isResult($r)) {
1075 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1077 if ($contact['addr'] != "") {
1078 $handle = $contact['addr'];
1080 $baseurl_start = strpos($contact['url'], '://') + 3;
1081 // allows installations in a subdirectory--not sure how Diaspora will handle
1082 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1083 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1084 $handle = $contact['nick'].'@'.$baseurl;
1088 return strtolower($handle);
1092 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1095 * @param mixed $fcontact_guid Hexadecimal string guid
1097 * @return string the contact url or null
1098 * @throws \Exception
1100 public static function urlFromContactGuid($fcontact_guid)
1102 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1105 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1106 DBA::escape(Protocol::DIASPORA),
1107 DBA::escape($fcontact_guid)
1110 if (DBA::isResult($r)) {
1111 return $r[0]['url'];
1118 * Get a contact id for a given handle
1120 * @todo Move to Friendica\Model\Contact
1122 * @param int $uid The user id
1123 * @param string $handle The handle in the format user@domain.tld
1125 * @return array Contact data
1126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1127 * @throws \ImagickException
1129 private static function contactByHandle($uid, $handle)
1131 $cid = Contact::getIdForURL($handle, $uid);
1133 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1137 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1138 if (!DBA::isResult($contact)) {
1139 // This here shouldn't happen at all
1140 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1148 * Checks if the given contact url does support ActivityPub
1150 * @param string $url profile url
1151 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1153 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1154 * @throws \ImagickException
1156 public static function isSupportedByContactUrl($url, $update = null)
1158 return !empty(self::personByHandle($url, $update));
1162 * Check if posting is allowed for this contact
1164 * @param array $importer Array of the importer user
1165 * @param array $contact The contact that is checked
1166 * @param bool $is_comment Is the check for a comment?
1168 * @return bool is the contact allowed to post?
1170 private static function postAllow(array $importer, array $contact, $is_comment = false)
1173 * Perhaps we were already sharing with this person. Now they're sharing with us.
1174 * That makes us friends.
1175 * Normally this should have handled by getting a request - but this could get lost
1177 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1178 // It is not removed by now. Possibly the code is needed?
1179 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1182 // array('rel' => Contact::FRIEND, 'writable' => true),
1183 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1186 // $contact["rel"] = Contact::FRIEND;
1187 // Logger::log("defining user ".$contact["nick"]." as friend");
1190 // Contact server is blocked
1191 if (Network::isUrlBlocked($contact['url'])) {
1193 // We don't seem to like that person
1194 } elseif ($contact["blocked"]) {
1195 // Maybe blocked, don't accept.
1197 // We are following this person?
1198 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1199 // Yes, then it is fine.
1201 // Is it a post to a community?
1202 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1205 // Is the message a global user or a comment?
1206 } elseif (($importer["uid"] == 0) || $is_comment) {
1207 // Messages for the global users and comments are always accepted
1215 * Fetches the contact id for a handle and checks if posting is allowed
1217 * @param array $importer Array of the importer user
1218 * @param string $handle The checked handle in the format user@domain.tld
1219 * @param bool $is_comment Is the check for a comment?
1221 * @return array The contact data
1222 * @throws \Exception
1224 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1226 $contact = self::contactByHandle($importer["uid"], $handle);
1228 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1229 // If a contact isn't found, we accept it anyway if it is a comment
1230 if ($is_comment && ($importer["uid"] != 0)) {
1231 return self::contactByHandle(0, $handle);
1232 } elseif ($is_comment) {
1239 if (!self::postAllow($importer, $contact, $is_comment)) {
1240 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1247 * Does the message already exists on the system?
1249 * @param int $uid The user id
1250 * @param string $guid The guid of the message
1252 * @return int|bool message id if the message already was stored into the system - or false.
1253 * @throws \Exception
1255 private static function messageExists($uid, $guid)
1257 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1258 if (DBA::isResult($item)) {
1259 Logger::log("message ".$guid." already exists for user ".$uid);
1267 * Checks for links to posts in a message
1269 * @param array $item The item array
1272 private static function fetchGuid(array $item)
1274 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1275 preg_replace_callback(
1277 function ($match) use ($item) {
1278 self::fetchGuidSub($match, $item);
1283 preg_replace_callback(
1284 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1285 function ($match) use ($item) {
1286 self::fetchGuidSub($match, $item);
1293 * Checks for relative /people/* links in an item body to match local
1294 * contacts or prepends the remote host taken from the author link.
1296 * @param string $body The item body to replace links from
1297 * @param string $author_link The author link for missing local contact fallback
1299 * @return string the replaced string
1301 public static function replacePeopleGuid($body, $author_link)
1303 $return = preg_replace_callback(
1304 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1305 function ($match) use ($author_link) {
1307 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1308 // 1 => '0123456789abcdef'
1310 $handle = self::urlFromContactGuid($match[1]);
1313 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1315 // No local match, restoring absolute remote URL from author scheme and host
1316 $author_url = parse_url($author_link);
1317 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1329 * sub function of "fetchGuid" which checks for links in messages
1331 * @param array $match array containing a link that has to be checked for a message link
1332 * @param array $item The item array
1334 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1335 * @throws \ImagickException
1337 private static function fetchGuidSub($match, $item)
1339 if (!self::storeByGuid($match[1], $item["author-link"])) {
1340 self::storeByGuid($match[1], $item["owner-link"]);
1345 * Fetches an item with a given guid from a given server
1347 * @param string $guid the message guid
1348 * @param string $server The server address
1349 * @param int $uid The user id of the user
1351 * @return int the message id of the stored message or false
1352 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1353 * @throws \ImagickException
1355 private static function storeByGuid($guid, $server, $uid = 0)
1357 $serverparts = parse_url($server);
1359 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1363 $server = $serverparts["scheme"]."://".$serverparts["host"];
1365 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1367 $msg = self::message($guid, $server);
1373 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1375 // Now call the dispatcher
1376 return self::dispatchPublic($msg);
1380 * Fetches a message from a server
1382 * @param string $guid message guid
1383 * @param string $server The url of the server
1384 * @param int $level Endless loop prevention
1387 * 'message' => The message XML
1388 * 'author' => The author handle
1389 * 'key' => The public key of the author
1390 * @throws \Exception
1392 private static function message($guid, $server, $level = 0)
1398 // This will work for new Diaspora servers and Friendica servers from 3.5
1399 $source_url = $server."/fetch/post/".urlencode($guid);
1401 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1403 $envelope = Network::fetchUrl($source_url);
1405 Logger::log("Envelope was fetched.", Logger::DEBUG);
1406 $x = self::verifyMagicEnvelope($envelope);
1408 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1410 Logger::log("Envelope was verified.", Logger::DEBUG);
1420 $source_xml = XML::parseString($x);
1422 if (!is_object($source_xml)) {
1426 if ($source_xml->post->reshare) {
1427 // Reshare of a reshare - old Diaspora version
1428 Logger::log("Message is a reshare", Logger::DEBUG);
1429 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1430 } elseif ($source_xml->getName() == "reshare") {
1431 // Reshare of a reshare - new Diaspora version
1432 Logger::log("Message is a new reshare", Logger::DEBUG);
1433 return self::message($source_xml->root_guid, $server, ++$level);
1438 // Fetch the author - for the old and the new Diaspora version
1439 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1440 $author = (string)$source_xml->post->status_message->diaspora_handle;
1441 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1442 $author = (string)$source_xml->author;
1445 // If this isn't a "status_message" then quit
1447 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1451 $msg = ["message" => $x, "author" => $author];
1453 $msg["key"] = self::key($msg["author"]);
1459 * Fetches an item with a given URL
1461 * @param string $url the message url
1463 * @return int the message id of the stored message or false
1464 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1465 * @throws \ImagickException
1467 public static function fetchByURL($url, $uid = 0)
1469 // Check for Diaspora (and Friendica) typical paths
1470 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1471 Logger::info('Invalid url', ['url' => $url]);
1475 $guid = urldecode($matches[2]);
1477 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1478 if (DBA::isResult($item)) {
1479 Logger::info('Found', ['id' => $item['id']]);
1483 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1484 $ret = self::storeByGuid($guid, $matches[1], $uid);
1485 Logger::info('Result', ['ret' => $ret]);
1487 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1488 if (DBA::isResult($item)) {
1489 Logger::info('Found', ['id' => $item['id']]);
1492 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1498 * Fetches the item record of a given guid
1500 * @param int $uid The user id
1501 * @param string $guid message guid
1502 * @param string $author The handle of the item
1503 * @param array $contact The contact of the item owner
1505 * @return array the item record
1506 * @throws \Exception
1508 private static function parentItem($uid, $guid, $author, array $contact)
1510 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1511 'author-name', 'author-link', 'author-avatar',
1512 'owner-name', 'owner-link', 'owner-avatar'];
1513 $condition = ['uid' => $uid, 'guid' => $guid];
1514 $item = Item::selectFirst($fields, $condition);
1516 if (!DBA::isResult($item)) {
1517 $person = self::personByHandle($author);
1518 $result = self::storeByGuid($guid, $person["url"], $uid);
1520 // We don't have an url for items that arrived at the public dispatcher
1521 if (!$result && !empty($contact["url"])) {
1522 $result = self::storeByGuid($guid, $contact["url"], $uid);
1526 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1528 $item = Item::selectFirst($fields, $condition);
1532 if (!DBA::isResult($item)) {
1533 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1536 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1542 * returns contact details
1544 * @param array $def_contact The default contact if the person isn't found
1545 * @param array $person The record of the person
1546 * @param int $uid The user id
1549 * 'cid' => contact id
1550 * 'network' => network type
1551 * @throws \Exception
1553 private static function authorContactByUrl($def_contact, $person, $uid)
1555 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1556 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1557 if (DBA::isResult($contact)) {
1558 $cid = $contact["id"];
1559 $network = $contact["network"];
1561 $cid = $def_contact["id"];
1562 $network = Protocol::DIASPORA;
1565 return ["cid" => $cid, "network" => $network];
1569 * Is the profile a hubzilla profile?
1571 * @param string $url The profile link
1573 * @return bool is it a hubzilla server?
1575 private static function isHubzilla($url)
1577 return(strstr($url, '/channel/'));
1581 * Generate a post link with a given handle and message guid
1583 * @param string $addr The user handle
1584 * @param string $guid message guid
1585 * @param string $parent_guid optional parent guid
1587 * @return string the post link
1588 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1589 * @throws \ImagickException
1591 private static function plink($addr, $guid, $parent_guid = '')
1593 $contact = Contact::getDetailsByAddr($addr);
1594 if (empty($contact)) {
1595 Logger::info('No contact data for address', ['addr' => $addr]);
1599 if (empty($contact['baseurl'])) {
1600 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1601 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1605 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1606 if (!empty($gserver['platform'])) {
1607 $platform = strtolower($gserver['platform']);
1608 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1611 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1612 if (self::isHubzilla($contact['url'])) {
1613 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1614 $platform = 'hubzilla';
1615 } elseif ($contact['network'] == Protocol::DFRN) {
1616 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1617 $platform = 'friendica';
1621 if ($platform == 'friendica') {
1622 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1625 if ($platform == 'hubzilla') {
1626 return $contact['baseurl'] . '/item/' . $guid;
1629 if ($platform == 'socialhome') {
1630 return $contact['baseurl'] . '/content/' . $guid;
1633 if ($platform != 'diaspora') {
1634 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1638 if ($parent_guid != '') {
1639 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1641 return $contact['baseurl'] . '/posts/' . $guid;
1646 * Receives account migration
1648 * @param array $importer Array of the importer user
1649 * @param object $data The message object
1651 * @return bool Success
1652 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1653 * @throws \ImagickException
1655 private static function receiveAccountMigration(array $importer, $data)
1657 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1658 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1659 $signature = Strings::escapeTags(XML::unescape($data->signature));
1661 $contact = self::contactByHandle($importer["uid"], $old_handle);
1663 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1667 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1670 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1671 $key = self::key($old_handle);
1672 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1673 Logger::log('No valid signature for migration.');
1677 // Update the profile
1678 self::receiveProfile($importer, $data->profile);
1680 // change the technical stuff in contact and gcontact
1681 $data = Probe::uri($new_handle);
1682 if ($data['network'] == Protocol::PHANTOM) {
1683 Logger::log('Account for '.$new_handle." couldn't be probed.");
1687 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1688 'name' => $data['name'], 'nick' => $data['nick'],
1689 'addr' => $data['addr'], 'batch' => $data['batch'],
1690 'notify' => $data['notify'], 'poll' => $data['poll'],
1691 'network' => $data['network']];
1693 DBA::update('contact', $fields, ['addr' => $old_handle]);
1695 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1696 'name' => $data['name'], 'nick' => $data['nick'],
1697 'addr' => $data['addr'], 'connect' => $data['addr'],
1698 'notify' => $data['notify'], 'photo' => $data['photo'],
1699 'server_url' => $data['baseurl'], 'network' => $data['network']];
1701 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1703 Logger::log('Contacts are updated.');
1709 * Processes an account deletion
1711 * @param object $data The message object
1713 * @return bool Success
1714 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1716 private static function receiveAccountDeletion($data)
1718 $author = Strings::escapeTags(XML::unescape($data->author));
1720 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1721 while ($contact = DBA::fetch($contacts)) {
1722 Contact::remove($contact["id"]);
1724 DBA::close($contacts);
1726 DBA::delete('gcontact', ['addr' => $author]);
1728 Logger::log('Removed contacts for ' . $author);
1734 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1736 * @param string $author Author handle
1737 * @param string $guid Message guid
1738 * @param boolean $onlyfound Only return uri when found in the database
1740 * @return string The constructed uri or the one from our database
1741 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1742 * @throws \ImagickException
1744 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1746 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1747 if (DBA::isResult($item)) {
1748 return $item["uri"];
1749 } elseif (!$onlyfound) {
1750 $person = self::personByHandle($author);
1752 $parts = parse_url($person['url']);
1753 unset($parts['path']);
1754 $host_url = Network::unparseURL($parts);
1756 return $host_url . '/objects/' . $guid;
1763 * Fetch the guid from our database with a given uri
1765 * @param string $uri Message uri
1766 * @param string $uid Author handle
1768 * @return string The post guid
1769 * @throws \Exception
1771 private static function getGuidFromUri($uri, $uid)
1773 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1774 if (DBA::isResult($item)) {
1775 return $item["guid"];
1782 * Find the best importer for a comment, like, ...
1784 * @param string $guid The guid of the item
1786 * @return array|boolean the origin owner of that post - or false
1787 * @throws \Exception
1789 private static function importerForGuid($guid)
1791 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1792 if (DBA::isResult($item)) {
1793 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1794 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1795 if (DBA::isResult($contact)) {
1803 * Store the mentions in the tag table
1805 * @param integer $uriid
1806 * @param string $text
1808 private static function storeMentions(int $uriid, string $text)
1810 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1811 if (empty($matches)) {
1816 * Matching values for the preg match
1817 * [1] = mention type (@ or !)
1818 * [2] = name (optional)
1822 foreach ($matches as $match) {
1823 if (empty($match)) {
1827 $person = self::personByHandle($match[3]);
1828 if (empty($person)) {
1832 Tag::storeByHash($uriid, $match[1], $person['name'] ?: $person['nick'], $person['url']);
1837 * Processes an incoming comment
1839 * @param array $importer Array of the importer user
1840 * @param string $sender The sender of the message
1841 * @param object $data The message object
1842 * @param string $xml The original XML of the message
1844 * @return int The message id of the generated comment or "false" if there was an error
1845 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1846 * @throws \ImagickException
1848 private static function receiveComment(array $importer, $sender, $data, $xml)
1850 $author = Strings::escapeTags(XML::unescape($data->author));
1851 $guid = Strings::escapeTags(XML::unescape($data->guid));
1852 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1853 $text = XML::unescape($data->text);
1855 if (isset($data->created_at)) {
1856 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1858 $created_at = DateTimeFormat::utcNow();
1861 if (isset($data->thread_parent_guid)) {
1862 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1863 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1868 $contact = self::allowedContactByHandle($importer, $sender, true);
1873 $message_id = self::messageExists($importer["uid"], $guid);
1878 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1879 if (!$parent_item) {
1883 $person = self::personByHandle($author);
1884 if (!is_array($person)) {
1885 Logger::log("unable to find author details");
1889 // Fetch the contact id - if we know this contact
1890 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1894 $datarray["uid"] = $importer["uid"];
1895 $datarray["contact-id"] = $author_contact["cid"];
1896 $datarray["network"] = $author_contact["network"];
1898 $datarray["author-link"] = $person["url"];
1899 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1901 $datarray["owner-link"] = $contact["url"];
1902 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1904 $datarray["guid"] = $guid;
1905 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1906 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1908 $datarray["verb"] = Activity::POST;
1909 $datarray["gravity"] = GRAVITY_COMMENT;
1911 if ($thr_uri != "") {
1912 $datarray["parent-uri"] = $thr_uri;
1914 $datarray["parent-uri"] = $parent_item["uri"];
1917 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1919 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1920 $datarray["source"] = $xml;
1922 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1924 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1925 $body = Markdown::toBBCode($text);
1927 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1929 self::storeMentions($datarray['uri-id'], $text);
1930 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1932 self::fetchGuid($datarray);
1934 // If we are the origin of the parent we store the original data.
1935 // We notify our followers during the item storage.
1936 if ($parent_item["origin"]) {
1937 $datarray['diaspora_signed_text'] = json_encode($data);
1940 $message_id = Item::insert($datarray);
1942 if ($message_id <= 0) {
1947 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1948 if ($datarray['uid'] == 0) {
1949 Item::distribute($message_id, json_encode($data));
1957 * processes and stores private messages
1959 * @param array $importer Array of the importer user
1960 * @param array $contact The contact of the message
1961 * @param object $data The message object
1962 * @param array $msg Array of the processed message, author handle and key
1963 * @param object $mesg The private message
1964 * @param array $conversation The conversation record to which this message belongs
1966 * @return bool "true" if it was successful
1967 * @throws \Exception
1969 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1971 $author = Strings::escapeTags(XML::unescape($data->author));
1972 $guid = Strings::escapeTags(XML::unescape($data->guid));
1973 $subject = Strings::escapeTags(XML::unescape($data->subject));
1975 // "diaspora_handle" is the element name from the old version
1976 // "author" is the element name from the new version
1977 if ($mesg->author) {
1978 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1979 } elseif ($mesg->diaspora_handle) {
1980 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1985 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1986 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1987 $msg_text = XML::unescape($mesg->text);
1988 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1990 if ($msg_conversation_guid != $guid) {
1991 Logger::log("message conversation guid does not belong to the current conversation.");
1995 $body = Markdown::toBBCode($msg_text);
1996 $message_uri = $msg_author.":".$msg_guid;
1998 $person = self::personByHandle($msg_author);
2000 return Mail::insert([
2001 'uid' => $importer['uid'],
2002 'guid' => $msg_guid,
2003 'convid' => $conversation['id'],
2004 'from-name' => $person['name'],
2005 'from-photo' => $person['photo'],
2006 'from-url' => $person['url'],
2007 'contact-id' => $contact['id'],
2008 'title' => $subject,
2010 'uri' => $message_uri,
2011 'parent-uri' => $author . ':' . $guid,
2012 'created' => $msg_created_at
2017 * Processes new private messages (answers to private messages are processed elsewhere)
2019 * @param array $importer Array of the importer user
2020 * @param array $msg Array of the processed message, author handle and key
2021 * @param object $data The message object
2023 * @return bool Success
2024 * @throws \Exception
2026 private static function receiveConversation(array $importer, $msg, $data)
2028 $author = Strings::escapeTags(XML::unescape($data->author));
2029 $guid = Strings::escapeTags(XML::unescape($data->guid));
2030 $subject = Strings::escapeTags(XML::unescape($data->subject));
2031 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2032 $participants = Strings::escapeTags(XML::unescape($data->participants));
2034 $messages = $data->message;
2036 if (!count($messages)) {
2037 Logger::log("empty conversation");
2041 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2046 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2047 if (!DBA::isResult($conversation)) {
2049 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2050 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2051 intval($importer["uid"]),
2053 DBA::escape($author),
2054 DBA::escape($created_at),
2055 DBA::escape(DateTimeFormat::utcNow()),
2056 DBA::escape($subject),
2057 DBA::escape($participants)
2060 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2063 if (!$conversation) {
2064 Logger::log("unable to create conversation.");
2068 foreach ($messages as $mesg) {
2069 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2076 * Processes "like" messages
2078 * @param array $importer Array of the importer user
2079 * @param string $sender The sender of the message
2080 * @param object $data The message object
2082 * @return int The message id of the generated like or "false" if there was an error
2083 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2084 * @throws \ImagickException
2086 private static function receiveLike(array $importer, $sender, $data)
2088 $author = Strings::escapeTags(XML::unescape($data->author));
2089 $guid = Strings::escapeTags(XML::unescape($data->guid));
2090 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2091 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2092 $positive = Strings::escapeTags(XML::unescape($data->positive));
2094 // likes on comments aren't supported by Diaspora - only on posts
2095 // But maybe this will be supported in the future, so we will accept it.
2096 if (!in_array($parent_type, ["Post", "Comment"])) {
2100 $contact = self::allowedContactByHandle($importer, $sender, true);
2105 $message_id = self::messageExists($importer["uid"], $guid);
2110 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2111 if (!$parent_item) {
2115 $person = self::personByHandle($author);
2116 if (!is_array($person)) {
2117 Logger::log("unable to find author details");
2121 // Fetch the contact id - if we know this contact
2122 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2124 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2125 // We would accept this anyhow.
2126 if ($positive == "true") {
2127 $verb = Activity::LIKE;
2129 $verb = Activity::DISLIKE;
2134 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2136 $datarray["uid"] = $importer["uid"];
2137 $datarray["contact-id"] = $author_contact["cid"];
2138 $datarray["network"] = $author_contact["network"];
2140 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2141 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2143 $datarray["guid"] = $guid;
2144 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2146 $datarray["verb"] = $verb;
2147 $datarray["gravity"] = GRAVITY_ACTIVITY;
2148 $datarray["parent-uri"] = $parent_item["uri"];
2150 $datarray["object-type"] = Activity\ObjectType::NOTE;
2152 $datarray["body"] = $verb;
2154 // Diaspora doesn't provide a date for likes
2155 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2157 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2158 if ($parent_item["id"] != $parent_item["parent"]) {
2159 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2160 $origin = $toplevel["origin"];
2162 $origin = $parent_item["origin"];
2165 // If we are the origin of the parent we store the original data.
2166 // We notify our followers during the item storage.
2168 $datarray['diaspora_signed_text'] = json_encode($data);
2171 $message_id = Item::insert($datarray);
2173 if ($message_id <= 0) {
2178 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2179 if ($datarray['uid'] == 0) {
2180 Item::distribute($message_id, json_encode($data));
2188 * Processes private messages
2190 * @param array $importer Array of the importer user
2191 * @param object $data The message object
2193 * @return bool Success?
2194 * @throws \Exception
2196 private static function receiveMessage(array $importer, $data)
2198 $author = Strings::escapeTags(XML::unescape($data->author));
2199 $guid = Strings::escapeTags(XML::unescape($data->guid));
2200 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2201 $text = XML::unescape($data->text);
2202 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2204 $contact = self::allowedContactByHandle($importer, $author, true);
2209 $conversation = null;
2211 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2212 $conversation = DBA::selectFirst('conv', [], $condition);
2214 if (!DBA::isResult($conversation)) {
2215 Logger::log("conversation not available.");
2219 $message_uri = $author.":".$guid;
2221 $person = self::personByHandle($author);
2223 Logger::log("unable to find author details");
2227 $body = Markdown::toBBCode($text);
2229 $body = self::replacePeopleGuid($body, $person["url"]);
2231 return Mail::insert([
2232 'uid' => $importer['uid'],
2234 'convid' => $conversation['id'],
2235 'from-name' => $person['name'],
2236 'from-photo' => $person['photo'],
2237 'from-url' => $person['url'],
2238 'contact-id' => $contact['id'],
2239 'title' => $conversation['subject'],
2242 'uri' => $message_uri,
2243 'parent-uri' => $author.":".$conversation['guid'],
2244 'created' => $created_at
2249 * Processes participations - unsupported by now
2251 * @param array $importer Array of the importer user
2252 * @param object $data The message object
2254 * @return bool always true
2255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2256 * @throws \ImagickException
2258 private static function receiveParticipation(array $importer, $data)
2260 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2261 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2263 $contact_id = Contact::getIdForURL($author);
2265 Logger::log('Contact not found: '.$author);
2269 $person = self::personByHandle($author);
2270 if (!is_array($person)) {
2271 Logger::log("Person not found: ".$author);
2275 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2276 if (!DBA::isResult($item)) {
2277 Logger::log('Item not found, no origin or private: '.$parent_guid);
2281 $author_parts = explode('@', $author);
2282 if (isset($author_parts[1])) {
2283 $server = $author_parts[1];
2285 // Should never happen
2289 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2291 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2292 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2295 // Send all existing comments and likes to the requesting server
2296 $comments = Item::select(['id', 'uri-id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2297 while ($comment = Item::fetch($comments)) {
2298 if ($comment['id'] == $comment['parent']) {
2302 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2303 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id)) {
2304 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2307 DBA::close($comments);
2313 * Processes photos - unneeded
2315 * @param array $importer Array of the importer user
2316 * @param object $data The message object
2318 * @return bool always true
2320 private static function receivePhoto(array $importer, $data)
2322 // There doesn't seem to be a reason for this function,
2323 // since the photo data is transmitted in the status message as well
2328 * Processes poll participations - unssupported
2330 * @param array $importer Array of the importer user
2331 * @param object $data The message object
2333 * @return bool always true
2335 private static function receivePollParticipation(array $importer, $data)
2337 // We don't support polls by now
2342 * Processes incoming profile updates
2344 * @param array $importer Array of the importer user
2345 * @param object $data The message object
2347 * @return bool Success
2348 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2349 * @throws \ImagickException
2351 private static function receiveProfile(array $importer, $data)
2353 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2355 $contact = self::contactByHandle($importer["uid"], $author);
2360 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2361 $image_url = XML::unescape($data->image_url);
2362 $birthday = XML::unescape($data->birthday);
2363 $about = Markdown::toBBCode(XML::unescape($data->bio));
2364 $location = Markdown::toBBCode(XML::unescape($data->location));
2365 $searchable = (XML::unescape($data->searchable) == "true");
2366 $nsfw = (XML::unescape($data->nsfw) == "true");
2367 $tags = XML::unescape($data->tag_string);
2369 $tags = explode("#", $tags);
2372 foreach ($tags as $tag) {
2373 $tag = trim(strtolower($tag));
2379 $keywords = implode(", ", $keywords);
2381 $handle_parts = explode("@", $author);
2382 $nick = $handle_parts[0];
2385 $name = $handle_parts[0];
2388 if (preg_match("|^https?://|", $image_url) === 0) {
2389 $image_url = "http://".$handle_parts[1].$image_url;
2392 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2394 // Generic birthday. We don't know the timezone. The year is irrelevant.
2396 $birthday = str_replace("1000", "1901", $birthday);
2398 if ($birthday != "") {
2399 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2402 // this is to prevent multiple birthday notifications in a single year
2403 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2405 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2406 $birthday = $contact["bd"];
2409 $fields = ['name' => $name, 'location' => $location,
2410 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2411 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2412 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2414 if (!empty($birthday)) {
2415 $fields['bd'] = $birthday;
2418 DBA::update('contact', $fields, ['id' => $contact['id']]);
2420 // @todo Update the public contact, then update the gcontact from that
2422 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2423 "photo" => $image_url, "name" => $name, "location" => $location,
2424 "about" => $about, "birthday" => $birthday,
2425 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2426 "hide" => !$searchable, "nsfw" => $nsfw];
2428 $gcid = GContact::update($gcontact);
2430 GContact::link($gcid, $importer["uid"], $contact["id"]);
2432 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2438 * Processes incoming friend requests
2440 * @param array $importer Array of the importer user
2441 * @param array $contact The contact that send the request
2443 * @throws \Exception
2445 private static function receiveRequestMakeFriend(array $importer, array $contact)
2447 if ($contact["rel"] == Contact::SHARING) {
2450 ['rel' => Contact::FRIEND, 'writable' => true],
2451 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2457 * Processes incoming sharing notification
2459 * @param array $importer Array of the importer user
2460 * @param object $data The message object
2462 * @return bool Success
2463 * @throws \Exception
2465 private static function receiveContactRequest(array $importer, $data)
2467 $author = XML::unescape($data->author);
2468 $recipient = XML::unescape($data->recipient);
2470 if (!$author || !$recipient) {
2474 // the current protocol version doesn't know these fields
2475 // That means that we will assume their existance
2476 if (isset($data->following)) {
2477 $following = (XML::unescape($data->following) == "true");
2482 if (isset($data->sharing)) {
2483 $sharing = (XML::unescape($data->sharing) == "true");
2488 $contact = self::contactByHandle($importer["uid"], $author);
2490 // perhaps we were already sharing with this person. Now they're sharing with us.
2491 // That makes us friends.
2494 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2495 self::receiveRequestMakeFriend($importer, $contact);
2497 // refetch the contact array
2498 $contact = self::contactByHandle($importer["uid"], $author);
2500 // If we are now friends, we are sending a share message.
2501 // Normally we needn't to do so, but the first message could have been vanished.
2502 if (in_array($contact["rel"], [Contact::FRIEND])) {
2503 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2504 if (DBA::isResult($user)) {
2505 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2506 self::sendShare($user, $contact);
2511 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2512 Contact::removeFollower($importer, $contact);
2517 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2518 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2520 } elseif (!$following && !$sharing) {
2521 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2523 } elseif (!$following && $sharing) {
2524 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2525 } elseif ($following && $sharing) {
2526 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2527 } elseif ($following && !$sharing) {
2528 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2531 $ret = self::personByHandle($author);
2533 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2534 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2538 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2540 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2545 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2546 'author-link' => $ret['url']];
2548 $result = Contact::addRelationship($importer, $contact, $item, false);
2549 if ($result === true) {
2550 $contact_record = self::contactByHandle($importer['uid'], $author);
2551 if (!$contact_record) {
2552 Logger::info('unable to locate newly created contact record.');
2556 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2557 if (DBA::isResult($user)) {
2558 self::sendShare($user, $contact_record);
2560 // Send the profile data, maybe it weren't transmitted before
2561 self::sendProfile($importer['uid'], [$contact_record]);
2569 * Fetches a message with a given guid
2571 * @param string $guid message guid
2572 * @param string $orig_author handle of the original post
2573 * @return array The fetched item
2574 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2575 * @throws \ImagickException
2577 public static function originalItem($guid, $orig_author)
2580 Logger::log('Empty guid. Quitting.');
2584 // Do we already have this item?
2585 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2586 'author-name', 'author-link', 'author-avatar'];
2587 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2588 $item = Item::selectFirst($fields, $condition);
2590 if (DBA::isResult($item)) {
2591 Logger::log("reshared message ".$guid." already exists on system.");
2593 // Maybe it is already a reshared item?
2594 // Then refetch the content, if it is a reshare from a reshare.
2595 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2596 if (self::isReshare($item["body"], true)) {
2598 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2599 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2601 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2603 // Add OEmbed and other information to the body
2604 $item["body"] = add_page_info_to_body($item["body"], false, true);
2612 if (!DBA::isResult($item)) {
2613 if (empty($orig_author)) {
2614 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2618 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2619 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2620 $stored = self::storeByGuid($guid, $server);
2623 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2624 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2625 $stored = self::storeByGuid($guid, $server);
2629 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2630 'author-name', 'author-link', 'author-avatar'];
2631 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2632 $item = Item::selectFirst($fields, $condition);
2634 if (DBA::isResult($item)) {
2635 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2636 if (self::isReshare($item["body"], false)) {
2637 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2638 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2649 * Stores a reshare activity
2651 * @param array $item Array of reshare post
2652 * @param integer $parent_message_id Id of the parent post
2653 * @param string $guid GUID string of reshare action
2654 * @param string $author Author handle
2656 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2658 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2662 $datarray['uid'] = $item['uid'];
2663 $datarray['contact-id'] = $item['contact-id'];
2664 $datarray['network'] = $item['network'];
2666 $datarray['author-link'] = $item['author-link'];
2667 $datarray['author-id'] = $item['author-id'];
2669 $datarray['owner-link'] = $datarray['author-link'];
2670 $datarray['owner-id'] = $datarray['author-id'];
2672 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2673 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2674 $datarray['parent-uri'] = $parent['uri'];
2676 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2677 $datarray['gravity'] = GRAVITY_ACTIVITY;
2678 $datarray['object-type'] = Activity\ObjectType::NOTE;
2680 $datarray['protocol'] = $item['protocol'];
2682 $datarray['plink'] = self::plink($author, $datarray['guid']);
2683 $datarray['private'] = $item['private'];
2684 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2686 $message_id = Item::insert($datarray);
2689 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2690 if ($datarray['uid'] == 0) {
2691 Item::distribute($message_id);
2697 * Processes a reshare message
2699 * @param array $importer Array of the importer user
2700 * @param object $data The message object
2701 * @param string $xml The original XML of the message
2703 * @return int the message id
2704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2705 * @throws \ImagickException
2707 private static function receiveReshare(array $importer, $data, $xml)
2709 $author = Strings::escapeTags(XML::unescape($data->author));
2710 $guid = Strings::escapeTags(XML::unescape($data->guid));
2711 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2712 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2713 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2714 /// @todo handle unprocessed property "provider_display_name"
2715 $public = Strings::escapeTags(XML::unescape($data->public));
2717 $contact = self::allowedContactByHandle($importer, $author, false);
2722 $message_id = self::messageExists($importer["uid"], $guid);
2727 $original_item = self::originalItem($root_guid, $root_author);
2728 if (!$original_item) {
2732 $orig_url = DI::baseUrl()."/display/".$original_item["guid"];
2736 $datarray["uid"] = $importer["uid"];
2737 $datarray["contact-id"] = $contact["id"];
2738 $datarray["network"] = Protocol::DIASPORA;
2740 $datarray["author-link"] = $contact["url"];
2741 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2743 $datarray["owner-link"] = $datarray["author-link"];
2744 $datarray["owner-id"] = $datarray["author-id"];
2746 $datarray["guid"] = $guid;
2747 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2748 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2750 $datarray["verb"] = Activity::POST;
2751 $datarray["gravity"] = GRAVITY_PARENT;
2753 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2754 $datarray["source"] = $xml;
2756 /// @todo Copy tag data from original post
2758 $prefix = share_header(
2759 $original_item["author-name"],
2760 $original_item["author-link"],
2761 $original_item["author-avatar"],
2762 $original_item["guid"],
2763 $original_item["created"],
2767 if (!empty($original_item['title'])) {
2768 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2771 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2773 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2775 $datarray["tag"] = $original_item["tag"];
2776 $datarray["attach"] = $original_item["attach"];
2777 $datarray["app"] = $original_item["app"];
2779 $datarray["plink"] = self::plink($author, $guid);
2780 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2781 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2783 $datarray["object-type"] = $original_item["object-type"];
2785 self::fetchGuid($datarray);
2786 $message_id = Item::insert($datarray);
2788 self::sendParticipation($contact, $datarray);
2790 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2791 if ($root_message_id) {
2792 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2796 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2797 if ($datarray['uid'] == 0) {
2798 Item::distribute($message_id);
2807 * Processes retractions
2809 * @param array $importer Array of the importer user
2810 * @param array $contact The contact of the item owner
2811 * @param object $data The message object
2813 * @return bool success
2814 * @throws \Exception
2816 private static function itemRetraction(array $importer, array $contact, $data)
2818 $author = Strings::escapeTags(XML::unescape($data->author));
2819 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2820 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2822 $person = self::personByHandle($author);
2823 if (!is_array($person)) {
2824 Logger::log("unable to find author detail for ".$author);
2828 if (empty($contact["url"])) {
2829 $contact["url"] = $person["url"];
2832 // Fetch items that are about to be deleted
2833 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2835 // When we receive a public retraction, we delete every item that we find.
2836 if ($importer['uid'] == 0) {
2837 $condition = ['guid' => $target_guid, 'deleted' => false];
2839 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2842 $r = Item::select($fields, $condition);
2843 if (!DBA::isResult($r)) {
2844 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2848 while ($item = Item::fetch($r)) {
2849 if (strstr($item['file'], '[')) {
2850 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2854 // Fetch the parent item
2855 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2857 // Only delete it if the parent author really fits
2858 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2859 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2863 Item::markForDeletion(['id' => $item['id']]);
2865 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2872 * Receives retraction messages
2874 * @param array $importer Array of the importer user
2875 * @param string $sender The sender of the message
2876 * @param object $data The message object
2878 * @return bool Success
2879 * @throws \Exception
2881 private static function receiveRetraction(array $importer, $sender, $data)
2883 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2885 $contact = self::contactByHandle($importer["uid"], $sender);
2886 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2887 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2895 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2897 switch ($target_type) {
2902 case "StatusMessage":
2903 return self::itemRetraction($importer, $contact, $data);
2905 case "PollParticipation":
2907 // Currently unsupported
2911 Logger::log("Unknown target type ".$target_type);
2918 * Receives status messages
2920 * @param array $importer Array of the importer user
2921 * @param SimpleXMLElement $data The message object
2922 * @param string $xml The original XML of the message
2924 * @return int The message id of the newly created item
2925 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2926 * @throws \ImagickException
2928 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2930 $author = Strings::escapeTags(XML::unescape($data->author));
2931 $guid = Strings::escapeTags(XML::unescape($data->guid));
2932 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2933 $public = Strings::escapeTags(XML::unescape($data->public));
2934 $text = XML::unescape($data->text);
2935 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2937 $contact = self::allowedContactByHandle($importer, $author, false);
2942 $message_id = self::messageExists($importer["uid"], $guid);
2948 if ($data->location) {
2949 foreach ($data->location->children() as $fieldname => $data) {
2950 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2954 $body = Markdown::toBBCode($text);
2958 // Attach embedded pictures to the body
2960 foreach ($data->photo as $photo) {
2961 $body = "[img]".XML::unescape($photo->remote_photo_path).
2962 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2965 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2967 $datarray["object-type"] = Activity\ObjectType::NOTE;
2969 // Add OEmbed and other information to the body
2970 if (!self::isHubzilla($contact["url"])) {
2971 $body = add_page_info_to_body($body, false, true);
2975 /// @todo enable support for polls
2976 //if ($data->poll) {
2977 // foreach ($data->poll AS $poll)
2982 /// @todo enable support for events
2984 $datarray["uid"] = $importer["uid"];
2985 $datarray["contact-id"] = $contact["id"];
2986 $datarray["network"] = Protocol::DIASPORA;
2988 $datarray["author-link"] = $contact["url"];
2989 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2991 $datarray["owner-link"] = $datarray["author-link"];
2992 $datarray["owner-id"] = $datarray["author-id"];
2994 $datarray["guid"] = $guid;
2995 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2996 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2998 $datarray["verb"] = Activity::POST;
2999 $datarray["gravity"] = GRAVITY_PARENT;
3001 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3002 $datarray["source"] = $xml;
3004 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3006 self::storeMentions($datarray['uri-id'], $text);
3007 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
3009 if ($provider_display_name != "") {
3010 $datarray["app"] = $provider_display_name;
3013 $datarray["plink"] = self::plink($author, $guid);
3014 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3015 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3017 if (isset($address["address"])) {
3018 $datarray["location"] = $address["address"];
3021 if (isset($address["lat"]) && isset($address["lng"])) {
3022 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3025 self::fetchGuid($datarray);
3026 $message_id = Item::insert($datarray);
3028 self::sendParticipation($contact, $datarray);
3031 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3032 if ($datarray['uid'] == 0) {
3033 Item::distribute($message_id);
3041 /* ************************************************************************************** *
3042 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3043 * ************************************************************************************** */
3046 * returnes the handle of a contact
3048 * @param array $contact contact array
3050 * @return string the handle in the format user@domain.tld
3051 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3053 private static function myHandle(array $contact)
3055 if (!empty($contact["addr"])) {
3056 return $contact["addr"];
3059 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3060 // So - just in case - we build the the address here.
3061 if ($contact["nickname"] != "") {
3062 $nick = $contact["nickname"];
3064 $nick = $contact["nick"];
3067 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3072 * Creates the data for a private message in the new format
3074 * @param string $msg The message that is to be transmitted
3075 * @param array $user The record of the sender
3076 * @param array $contact Target of the communication
3077 * @param string $prvkey The private key of the sender
3078 * @param string $pubkey The public key of the receiver
3080 * @return string The encrypted data
3081 * @throws \Exception
3083 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3085 Logger::log("Message: ".$msg, Logger::DATA);
3087 // without a public key nothing will work
3089 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3093 $aes_key = openssl_random_pseudo_bytes(32);
3094 $b_aes_key = base64_encode($aes_key);
3095 $iv = openssl_random_pseudo_bytes(16);
3096 $b_iv = base64_encode($iv);
3098 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3100 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3102 $encrypted_key_bundle = "";
3103 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3105 $json_object = json_encode(
3106 ["aes_key" => base64_encode($encrypted_key_bundle),
3107 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3110 return $json_object;
3114 * Creates the envelope for the "fetch" endpoint and for the new format
3116 * @param string $msg The message that is to be transmitted
3117 * @param array $user The record of the sender
3119 * @return string The envelope
3120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3122 public static function buildMagicEnvelope($msg, array $user)
3124 $b64url_data = Strings::base64UrlEncode($msg);
3125 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3127 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3128 $type = "application/xml";
3129 $encoding = "base64url";
3130 $alg = "RSA-SHA256";
3131 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3133 // Fallback if the private key wasn't transmitted in the expected field
3134 if ($user['uprvkey'] == "") {
3135 $user['uprvkey'] = $user['prvkey'];
3138 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3139 $sig = Strings::base64UrlEncode($signature);
3141 $xmldata = ["me:env" => ["me:data" => $data,
3142 "@attributes" => ["type" => $type],
3143 "me:encoding" => $encoding,
3146 "@attributes2" => ["key_id" => $key_id]]];
3148 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3150 return XML::fromArray($xmldata, $xml, false, $namespaces);
3154 * Create the envelope for a message
3156 * @param string $msg The message that is to be transmitted
3157 * @param array $user The record of the sender
3158 * @param array $contact Target of the communication
3159 * @param string $prvkey The private key of the sender
3160 * @param string $pubkey The public key of the receiver
3161 * @param bool $public Is the message public?
3163 * @return string The message that will be transmitted to other servers
3164 * @throws \Exception
3166 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3168 // The message is put into an envelope with the sender's signature
3169 $envelope = self::buildMagicEnvelope($msg, $user);
3171 // Private messages are put into a second envelope, encrypted with the receivers public key
3173 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3180 * Creates a signature for a message
3182 * @param array $owner the array of the owner of the message
3183 * @param array $message The message that is to be signed
3185 * @return string The signature
3187 private static function signature($owner, $message)
3190 unset($sigmsg["author_signature"]);
3191 unset($sigmsg["parent_author_signature"]);
3193 $signed_text = implode(";", $sigmsg);
3195 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3199 * Transmit a message to a target server
3201 * @param array $owner the array of the item owner
3202 * @param array $contact Target of the communication
3203 * @param string $envelope The message that is to be transmitted
3204 * @param bool $public_batch Is it a public post?
3205 * @param string $guid message guid
3207 * @return int Result of the transmission
3208 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3209 * @throws \ImagickException
3211 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3213 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3218 $logid = Strings::getRandomHex(4);
3220 // We always try to use the data from the fcontact table.
3221 // This is important for transmitting data to Friendica servers.
3222 if (!empty($contact['addr'])) {
3223 $fcontact = self::personByHandle($contact['addr']);
3224 if (!empty($fcontact)) {
3225 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3229 if (empty($dest_url)) {
3230 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3234 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3238 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3240 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3241 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3243 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3244 $return_code = $postResult->getReturnCode();
3246 Logger::log("test_mode");
3250 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3252 return $return_code ? $return_code : -1;
3257 * Build the post xml
3259 * @param string $type The message type
3260 * @param array $message The message data
3262 * @return string The post XML
3264 public static function buildPostXml($type, $message)
3266 $data = [$type => $message];
3268 return XML::fromArray($data, $xml);
3272 * Builds and transmit messages
3274 * @param array $owner the array of the item owner
3275 * @param array $contact Target of the communication
3276 * @param string $type The message type
3277 * @param array $message The message data
3278 * @param bool $public_batch Is it a public post?
3279 * @param string $guid message guid
3281 * @return int Result of the transmission
3282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3283 * @throws \ImagickException
3285 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3287 $msg = self::buildPostXml($type, $message);
3289 Logger::log('message: '.$msg, Logger::DATA);
3290 Logger::log('send guid '.$guid, Logger::DEBUG);
3292 // Fallback if the private key wasn't transmitted in the expected field
3293 if (empty($owner['uprvkey'])) {
3294 $owner['uprvkey'] = $owner['prvkey'];
3297 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3299 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3301 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3303 return $return_code;
3307 * sends a participation (Used to get all further updates)
3309 * @param array $contact Target of the communication
3310 * @param array $item Item array
3312 * @return int The result of the transmission
3313 * @throws \Exception
3315 private static function sendParticipation(array $contact, array $item)
3317 // Don't send notifications for private postings
3318 if ($item['private'] == Item::PRIVATE) {
3322 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3324 $result = DI::cache()->get($cachekey);
3325 if (!is_null($result)) {
3329 // Fetch some user id to have a valid handle to transmit the participation.
3330 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3331 // If the item belongs to a user, we take this user id.
3332 if ($item['uid'] == 0) {
3333 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3334 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3335 $owner = User::getOwnerDataById($first_user['uid']);
3337 $owner = User::getOwnerDataById($item['uid']);
3340 $author = self::myHandle($owner);
3342 $message = ["author" => $author,
3343 "guid" => System::createUUID(),
3344 "parent_type" => "Post",
3345 "parent_guid" => $item["guid"]];
3347 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3349 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3350 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3352 return self::buildAndTransmit($owner, $contact, "participation", $message);
3356 * sends an account migration
3358 * @param array $owner the array of the item owner
3359 * @param array $contact Target of the communication
3360 * @param int $uid User ID
3362 * @return int The result of the transmission
3363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3364 * @throws \ImagickException
3366 public static function sendAccountMigration(array $owner, array $contact, $uid)
3368 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3369 $profile = self::createProfileData($uid);
3371 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3372 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3374 $message = ["author" => $old_handle,
3375 "profile" => $profile,
3376 "signature" => $signature];
3378 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3380 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3384 * Sends a "share" message
3386 * @param array $owner the array of the item owner
3387 * @param array $contact Target of the communication
3389 * @return int The result of the transmission
3390 * @throws \Exception
3392 public static function sendShare(array $owner, array $contact)
3395 * @todo support the different possible combinations of "following" and "sharing"
3396 * Currently, Diaspora only interprets the "sharing" field
3398 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3402 switch ($contact["rel"]) {
3403 case Contact::FRIEND:
3407 case Contact::SHARING:
3411 case Contact::FOLLOWER:
3417 $message = ["author" => self::myHandle($owner),
3418 "recipient" => $contact["addr"],
3419 "following" => "true",
3420 "sharing" => "true"];
3422 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3424 return self::buildAndTransmit($owner, $contact, "contact", $message);
3428 * sends an "unshare"
3430 * @param array $owner the array of the item owner
3431 * @param array $contact Target of the communication
3433 * @return int The result of the transmission
3434 * @throws \Exception
3436 public static function sendUnshare(array $owner, array $contact)
3438 $message = ["author" => self::myHandle($owner),
3439 "recipient" => $contact["addr"],
3440 "following" => "false",
3441 "sharing" => "false"];
3443 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3445 return self::buildAndTransmit($owner, $contact, "contact", $message);
3449 * Checks a message body if it is a reshare
3451 * @param string $body The message body that is to be check
3452 * @param bool $complete Should it be a complete check or a simple check?
3454 * @return array|bool Reshare details or "false" if no reshare
3455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3456 * @throws \ImagickException
3458 public static function isReshare($body, $complete = true)
3460 $body = trim($body);
3462 $reshared = Item::getShareArray(['body' => $body]);
3463 if (empty($reshared)) {
3467 // Skip if it isn't a pure repeated messages
3468 // Does it start with a share?
3469 if (!empty($reshared['comment']) && $complete) {
3473 if (!empty($reshared['guid']) && $complete) {
3474 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3475 $item = Item::selectFirst(['contact-id'], $condition);
3476 if (DBA::isResult($item)) {
3478 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3479 $ret["root_guid"] = $reshared['guid'];
3481 } elseif ($complete) {
3482 // We are resharing something that isn't a DFRN or Diaspora post.
3483 // So we have to return "false" on "$complete" to not trigger a reshare.
3486 } elseif (empty($reshared['guid']) && $complete) {
3492 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3493 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3494 if (!empty($contact['addr'])) {
3495 $ret['root_handle'] = $contact['addr'];
3499 if (empty($ret) && !$complete) {
3507 * Create an event array
3509 * @param integer $event_id The id of the event
3511 * @return array with event data
3512 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3514 private static function buildEvent($event_id)
3516 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3517 if (!DBA::isResult($r)) {
3525 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3526 if (!DBA::isResult($r)) {
3532 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3533 if (!DBA::isResult($r)) {
3539 $eventdata['author'] = self::myHandle($owner);
3541 if ($event['guid']) {
3542 $eventdata['guid'] = $event['guid'];
3545 $mask = DateTimeFormat::ATOM;
3547 /// @todo - establish "all day" events in Friendica
3548 $eventdata["all_day"] = "false";
3550 $eventdata['timezone'] = 'UTC';
3551 if (!$event['adjust'] && $user['timezone']) {
3552 $eventdata['timezone'] = $user['timezone'];
3555 if ($event['start']) {
3556 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3558 if ($event['finish'] && !$event['nofinish']) {
3559 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3561 if ($event['summary']) {
3562 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3564 if ($event['desc']) {
3565 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3567 if ($event['location']) {
3568 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3569 $coord = Map::getCoordinates($event['location']);
3572 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3573 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3574 $location["lat"] = $coord['lat'];
3575 $location["lng"] = $coord['lon'];
3577 $location["lat"] = 0;
3578 $location["lng"] = 0;
3580 $eventdata['location'] = $location;
3587 * Create a post (status message or reshare)
3589 * @param array $item The item that will be exported
3590 * @param array $owner the array of the item owner
3593 * 'type' -> Message type ("status_message" or "reshare")
3594 * 'message' -> Array of XML elements of the status
3595 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3596 * @throws \ImagickException
3598 public static function buildStatus(array $item, array $owner)
3600 $cachekey = "diaspora:buildStatus:".$item['guid'];
3602 $result = DI::cache()->get($cachekey);
3603 if (!is_null($result)) {
3607 $myaddr = self::myHandle($owner);
3609 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3610 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3611 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3613 // Detect a share element and do a reshare
3614 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3615 $message = ["author" => $myaddr,
3616 "guid" => $item["guid"],
3617 "created_at" => $created,
3618 "root_author" => $ret["root_handle"],
3619 "root_guid" => $ret["root_guid"],
3620 "provider_display_name" => $item["app"],
3621 "public" => $public];
3625 $title = $item["title"];
3626 $body = $item["body"];
3628 // Fetch the title from an attached link - if there is one
3629 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3630 $page_data = BBCode::getAttachmentData($item['body']);
3631 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3632 $title = $page_data['title'];
3636 if ($item['author-link'] != $item['owner-link']) {
3637 require_once 'mod/share.php';
3638 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3639 "", $item['created'], $item['plink']) . $body . '[/share]';
3642 // convert to markdown
3643 $body = html_entity_decode(BBCode::toMarkdown($body));
3646 if (strlen($title)) {
3647 $body = "### ".html_entity_decode($title)."\n\n".$body;
3650 if ($item["attach"]) {
3651 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3653 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3654 foreach ($matches as $mtch) {
3655 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3662 if ($item["location"] != "")
3663 $location["address"] = $item["location"];
3665 if ($item["coord"] != "") {
3666 $coord = explode(" ", $item["coord"]);
3667 $location["lat"] = $coord[0];
3668 $location["lng"] = $coord[1];
3671 $message = ["author" => $myaddr,
3672 "guid" => $item["guid"],
3673 "created_at" => $created,
3674 "edited_at" => $edited,
3675 "public" => $public,
3677 "provider_display_name" => $item["app"],
3678 "location" => $location];
3680 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3681 if (!isset($location["lat"]) || !isset($location["lng"])) {
3682 unset($message["location"]);
3685 if ($item['event-id'] > 0) {
3686 $event = self::buildEvent($item['event-id']);
3687 if (count($event)) {
3688 $message['event'] = $event;
3690 if (!empty($event['location']['address']) &&
3691 !empty($event['location']['lat']) &&
3692 !empty($event['location']['lng'])) {
3693 $message['location'] = $event['location'];
3696 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3697 // $message['text'] = '';
3701 $type = "status_message";
3704 $msg = ["type" => $type, "message" => $message];
3706 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3711 private static function prependParentAuthorMention($body, $profile_url)
3713 $profile = Contact::getDetailsByURL($profile_url);
3714 if (!empty($profile['addr'])
3715 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3716 && !strstr($body, $profile['addr'])
3717 && !strstr($body, $profile_url)
3719 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3728 * @param array $item The item that will be exported
3729 * @param array $owner the array of the item owner
3730 * @param array $contact Target of the communication
3731 * @param bool $public_batch Is it a public post?
3733 * @return int The result of the transmission
3734 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3735 * @throws \ImagickException
3737 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3739 $status = self::buildStatus($item, $owner);
3741 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3745 * Creates a "like" object
3747 * @param array $item The item that will be exported
3748 * @param array $owner the array of the item owner
3750 * @return array The data for a "like"
3751 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3753 private static function constructLike(array $item, array $owner)
3755 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3756 if (!DBA::isResult($parent)) {
3760 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3762 if ($item['verb'] === Activity::LIKE) {
3764 } elseif ($item['verb'] === Activity::DISLIKE) {
3765 $positive = "false";
3768 return(["author" => self::myHandle($owner),
3769 "guid" => $item["guid"],
3770 "parent_guid" => $parent["guid"],
3771 "parent_type" => $target_type,
3772 "positive" => $positive,
3773 "author_signature" => ""]);
3777 * Creates an "EventParticipation" object
3779 * @param array $item The item that will be exported
3780 * @param array $owner the array of the item owner
3782 * @return array The data for an "EventParticipation"
3783 * @throws \Exception
3785 private static function constructAttend(array $item, array $owner)
3787 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3788 if (!DBA::isResult($parent)) {
3792 switch ($item['verb']) {
3793 case Activity::ATTEND:
3794 $attend_answer = 'accepted';
3796 case Activity::ATTENDNO:
3797 $attend_answer = 'declined';
3799 case Activity::ATTENDMAYBE:
3800 $attend_answer = 'tentative';
3803 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3807 return(["author" => self::myHandle($owner),
3808 "guid" => $item["guid"],
3809 "parent_guid" => $parent["guid"],
3810 "status" => $attend_answer,
3811 "author_signature" => ""]);
3815 * Creates the object for a comment
3817 * @param array $item The item that will be exported
3818 * @param array $owner the array of the item owner
3820 * @return array|false The data for a comment
3821 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3823 private static function constructComment(array $item, array $owner)
3825 $cachekey = "diaspora:constructComment:".$item['guid'];
3827 $result = DI::cache()->get($cachekey);
3828 if (!is_null($result)) {
3832 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3833 if (!DBA::isResult($toplevel_item)) {
3834 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3838 $thread_parent_item = $toplevel_item;
3839 if ($item['thr-parent'] != $item['parent-uri']) {
3840 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3843 $body = $item["body"];
3845 // The replied to autor mention is prepended for clarity if:
3846 // - Item replied isn't yours
3847 // - Item is public or explicit mentions are disabled
3848 // - Implicit mentions are enabled
3850 $item['author-id'] != $thread_parent_item['author-id']
3851 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3852 && !DI::config()->get('system', 'disable_implicit_mentions')
3854 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3857 $text = html_entity_decode(BBCode::toMarkdown($body));
3858 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3859 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3862 "author" => self::myHandle($owner),
3863 "guid" => $item["guid"],
3864 "created_at" => $created,
3865 "edited_at" => $edited,
3866 "parent_guid" => $toplevel_item["guid"],
3868 "author_signature" => ""
3871 // Send the thread parent guid only if it is a threaded comment
3872 if ($item['thr-parent'] != $item['parent-uri']) {
3873 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3876 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3882 * Send a like or a comment
3884 * @param array $item The item that will be exported
3885 * @param array $owner the array of the item owner
3886 * @param array $contact Target of the communication
3887 * @param bool $public_batch Is it a public post?
3889 * @return int The result of the transmission
3890 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3891 * @throws \ImagickException
3893 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3895 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3896 $message = self::constructAttend($item, $owner);
3897 $type = "event_participation";
3898 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3899 $message = self::constructLike($item, $owner);
3901 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3902 $message = self::constructComment($item, $owner);
3906 if (empty($message)) {
3910 $message["author_signature"] = self::signature($owner, $message);
3912 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3916 * Creates a message from a signature record entry
3918 * @param array $item The item that will be exported
3919 * @return array The message
3921 private static function messageFromSignature(array $item)
3923 // Split the signed text
3924 $signed_parts = explode(";", $item['signed_text']);
3926 if ($item["deleted"]) {
3927 $message = ["author" => $item['signer'],
3928 "target_guid" => $signed_parts[0],
3929 "target_type" => $signed_parts[1]];
3930 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3931 $message = ["author" => $signed_parts[4],
3932 "guid" => $signed_parts[1],
3933 "parent_guid" => $signed_parts[3],
3934 "parent_type" => $signed_parts[2],
3935 "positive" => $signed_parts[0],
3936 "author_signature" => $item['signature'],
3937 "parent_author_signature" => ""];
3939 // Remove the comment guid
3940 $guid = array_shift($signed_parts);
3942 // Remove the parent guid
3943 $parent_guid = array_shift($signed_parts);
3945 // Remove the handle
3946 $handle = array_pop($signed_parts);
3949 "author" => $handle,
3951 "parent_guid" => $parent_guid,
3952 "text" => implode(";", $signed_parts),
3953 "author_signature" => $item['signature'],
3954 "parent_author_signature" => ""
3961 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3963 * @param array $item The item that will be exported
3964 * @param array $owner the array of the item owner
3965 * @param array $contact Target of the communication
3966 * @param bool $public_batch Is it a public post?
3968 * @return int The result of the transmission
3969 * @throws \Exception
3971 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3973 if ($item["deleted"]) {
3974 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3975 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3981 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3983 $msg = json_decode($item['signed_text'], true);
3986 if (is_array($msg)) {
3987 foreach ($msg as $field => $data) {
3988 if (!$item["deleted"]) {
3989 if ($field == "diaspora_handle") {
3992 if ($field == "target_type") {
3993 $field = "parent_type";
3997 $message[$field] = $data;
4000 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4003 $message["parent_author_signature"] = self::signature($owner, $message);
4005 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4007 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4011 * Sends a retraction (deletion) of a message, like or comment
4013 * @param array $item The item that will be exported
4014 * @param array $owner the array of the item owner
4015 * @param array $contact Target of the communication
4016 * @param bool $public_batch Is it a public post?
4017 * @param bool $relay Is the retraction transmitted from a relay?
4019 * @return int The result of the transmission
4020 * @throws \Exception
4022 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4024 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4026 $msg_type = "retraction";
4028 if ($item['id'] == $item['parent']) {
4029 $target_type = "Post";
4030 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4031 $target_type = "Like";
4033 $target_type = "Comment";
4036 $message = ["author" => $itemaddr,
4037 "target_guid" => $item['guid'],
4038 "target_type" => $target_type];
4040 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4042 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4048 * @param array $item The item that will be exported
4049 * @param array $owner The owner
4050 * @param array $contact Target of the communication
4052 * @return int The result of the transmission
4053 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4054 * @throws \ImagickException
4056 public static function sendMail(array $item, array $owner, array $contact)
4058 $myaddr = self::myHandle($owner);
4060 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4061 if (!DBA::isResult($cnv)) {
4062 Logger::log("conversation not found.");
4066 $body = BBCode::toMarkdown($item["body"]);
4067 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4070 "author" => $myaddr,
4071 "guid" => $item["guid"],
4072 "conversation_guid" => $cnv["guid"],
4074 "created_at" => $created,
4077 if ($item["reply"]) {
4082 "author" => $cnv["creator"],
4083 "guid" => $cnv["guid"],
4084 "subject" => $cnv["subject"],
4085 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4086 "participants" => $cnv["recips"],
4090 $type = "conversation";
4093 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4097 * Split a name into first name and last name
4099 * @param string $name The name
4101 * @return array The array with "first" and "last"
4103 public static function splitName($name) {
4104 $name = trim($name);
4106 // Is the name longer than 64 characters? Then cut the rest of it.
4107 if (strlen($name) > 64) {
4108 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4109 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4111 $name = substr($name, 0, 64);
4115 // Take the first word as first name
4116 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4117 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4118 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4119 return ['first' => $first, 'last' => $last];
4122 // Take the last word as last name
4123 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4124 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4126 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4127 return ['first' => $first, 'last' => $last];
4130 // Take the first 32 characters if there is no space in the first 32 characters
4131 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4132 $first = substr($name, 0, 32);
4133 $last = substr($name, 32);
4134 return ['first' => $first, 'last' => $last];
4137 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4138 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4140 // Check if the last name is longer than 32 characters
4141 if (strlen($last) > 32) {
4142 if (strpos($last, ' ') <= 32) {
4143 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4145 $last = substr($last, 0, 32);
4149 return ['first' => $first, 'last' => $last];
4153 * Create profile data
4155 * @param int $uid The user id
4157 * @return array The profile data
4158 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4160 private static function createProfileData($uid)
4162 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4163 if (!DBA::isResult($profile)) {
4167 $handle = $profile["addr"];
4169 $split_name = self::splitName($profile['name']);
4170 $first = $split_name['first'];
4171 $last = $split_name['last'];
4173 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4174 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4175 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4176 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4182 if ($searchable === 'true') {
4185 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4186 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4190 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4193 $about = BBCode::toMarkdown($profile['about']);
4195 $location = $profile['location'];
4197 if ($profile['pub_keywords']) {
4198 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4199 $kw = str_replace(' ', ' ', $kw);
4200 $arr = explode(' ', $kw);
4202 for ($x = 0; $x < 5; $x ++) {
4203 if (!empty($arr[$x])) {
4204 $tags .= '#'. trim($arr[$x]) .' ';
4209 $tags = trim($tags);
4212 return ["author" => $handle,
4213 "first_name" => $first,
4214 "last_name" => $last,
4215 "image_url" => $large,
4216 "image_url_medium" => $medium,
4217 "image_url_small" => $small,
4220 "location" => $location,
4221 "searchable" => $searchable,
4223 "tag_string" => $tags];
4227 * Sends profile data
4229 * @param int $uid The user id
4230 * @param bool $recips optional, default false
4232 * @throws \Exception
4234 public static function sendProfile($uid, $recips = false)
4240 $owner = User::getOwnerDataById($uid);
4247 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4248 AND `uid` = %d AND `rel` != %d",
4249 DBA::escape(Protocol::DIASPORA),
4251 intval(Contact::SHARING)
4259 $message = self::createProfileData($uid);
4261 // @ToDo Split this into single worker jobs
4262 foreach ($recips as $recip) {
4263 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4264 self::buildAndTransmit($owner, $recip, "profile", $message);
4269 * Creates the signature for likes that are created on our system
4271 * @param integer $uid The user of that comment
4272 * @param array $item Item array
4274 * @return array Signed content
4275 * @throws \Exception
4277 public static function createLikeSignature($uid, array $item)
4279 $owner = User::getOwnerDataById($uid);
4280 if (empty($owner)) {
4281 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4285 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4289 $message = self::constructLike($item, $owner);
4290 if ($message === false) {
4294 $message["author_signature"] = self::signature($owner, $message);
4300 * Creates the signature for Comments that are created on our system
4302 * @param integer $uid The user of that comment
4303 * @param array $item Item array
4305 * @return array Signed content
4306 * @throws \Exception
4308 public static function createCommentSignature($uid, array $item)
4310 $owner = User::getOwnerDataById($uid);
4311 if (empty($owner)) {
4312 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4316 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4317 $item['thr-parent'] = $item['parent-uri'];
4319 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4320 if (!DBA::isResult($parent)) {
4324 $item['parent-uri'] = $parent['parent-uri'];
4326 $message = self::constructComment($item, $owner);
4327 if ($message === false) {
4331 $message["author_signature"] = self::signature($owner, $message);