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\ItemDeliveryData;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Profile;
42 use Friendica\Model\Term;
43 use Friendica\Model\User;
44 use Friendica\Network\Probe;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Map;
48 use Friendica\Util\Network;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
51 use Friendica\Worker\Delivery;
55 * This class contain functions to create and send Diaspora XML files
60 * Mark the relay contact of the given contact for archival
61 * This is called whenever there is a communication issue with the server.
62 * It avoids sending stuff to servers who don't exist anymore.
63 * The relay contact is a technical contact entry that exists once per server.
65 * @param array $contact of the relay contact
67 public static function markRelayForArchival(array $contact)
69 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
70 // This is already the relay contact, we don't need to fetch it
71 $relay_contact = $contact;
72 } elseif (empty($contact['baseurl'])) {
73 if (!empty($contact['batch'])) {
74 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
75 $relay_contact = DBA::selectFirst('contact', [], $condition);
80 $relay_contact = self::getRelayContact($contact['baseurl'], []);
83 if (!empty($relay_contact)) {
84 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
85 Contact::markForArchival($relay_contact);
90 * Return a list of relay servers
92 * The list contains not only the official relays but also servers that we serve directly
94 * @param integer $item_id The id of the item that is sent
95 * @param array $contacts The previously fetched contacts
97 * @return array of relay servers
98 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
100 public static function relayList($item_id, array $contacts = [])
104 // Fetching relay servers
105 $serverdata = DI::config()->get("system", "relay_server");
107 if (!empty($serverdata)) {
108 $servers = explode(",", $serverdata);
109 foreach ($servers as $server) {
110 $serverlist[$server] = trim($server);
114 if (DI::config()->get("system", "relay_directly", false)) {
115 // We distribute our stuff based on the parent to ensure that the thread will be complete
116 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
117 if (!DBA::isResult($parent)) {
121 // Servers that want to get all content
122 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
123 while ($server = DBA::fetch($servers)) {
124 $serverlist[$server['url']] = $server['url'];
127 // All tags of the current post
128 $condition = ['otype' => Term::OBJECT_TYPE_POST, 'type' => Term::HASHTAG, 'oid' => $parent['parent']];
129 $tags = DBA::select('term', ['term'], $condition);
131 while ($tag = DBA::fetch($tags)) {
132 $taglist[] = $tag['term'];
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'];
144 // All adresses with the given id
145 if (!empty($tagserverlist)) {
146 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
147 while ($server = DBA::fetch($servers)) {
148 $serverlist[$server['url']] = $server['url'];
153 // Now we are collecting all relay contacts
154 foreach ($serverlist as $server_url) {
155 // We don't send messages to ourselves
156 if (Strings::compareLink($server_url, DI::baseUrl())) {
159 $contact = self::getRelayContact($server_url);
160 if (is_bool($contact)) {
165 foreach ($contacts as $entry) {
166 if ($entry['batch'] == $contact['batch']) {
172 $contacts[] = $contact;
180 * Return a contact for a given server address or creates a dummy entry
182 * @param string $server_url The url of the server
183 * @param array $fields Fieldlist
184 * @return array with the contact
187 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
189 // Fetch the relay contact
190 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
191 'contact-type' => Contact::TYPE_RELAY];
192 $contact = DBA::selectFirst('contact', $fields, $condition);
194 if (DBA::isResult($contact)) {
195 if ($contact['archive'] || $contact['blocked']) {
200 self::setRelayContact($server_url);
202 $contact = DBA::selectFirst('contact', $fields, $condition);
203 if (DBA::isResult($contact)) {
208 // It should never happen that we arrive here
213 * Update or insert a relay contact
215 * @param string $server_url The url of the server
216 * @param array $network_fields Optional network specific fields
219 public static function setRelayContact($server_url, array $network_fields = [])
221 $fields = ['created' => DateTimeFormat::utcNow(),
222 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
223 'nurl' => Strings::normaliseLink($server_url),
224 'network' => Protocol::DIASPORA, 'uid' => 0,
225 'batch' => $server_url . '/receive/public',
226 'rel' => Contact::FOLLOWER, 'blocked' => false,
227 'pending' => false, 'writable' => true,
228 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
230 $fields = array_merge($fields, $network_fields);
232 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
233 $old = DBA::selectFirst('contact', [], $condition);
234 if (DBA::isResult($old)) {
235 unset($fields['created']);
236 $condition = ['id' => $old['id']];
238 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
239 DBA::update('contact', $fields, $condition, $old);
241 Logger::info('Create relay contact', ['fields' => $fields]);
242 Contact::insert($fields);
247 * Return a list of participating contacts for a thread
249 * This is used for the participation feature.
250 * One of the parameters is a contact array.
251 * This is done to avoid duplicates.
253 * @param integer $thread The id of the thread
254 * @param array $contacts The previously fetched contacts
256 * @return array of relay servers
259 public static function participantsForThread($thread, array $contacts)
261 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`url`, `contact`.`name`, `contact`.`network`, `contact`.`protocol`,
262 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
263 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
264 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
265 WHERE `participation`.`iid` = ? AND NOT `contact`.`archive`", $thread);
267 while ($contact = DBA::fetch($r)) {
268 if (!empty($contact['fnetwork'])) {
269 $contact['network'] = $contact['fnetwork'];
271 unset($contact['fnetwork']);
273 if (empty($contact['protocol'])) {
274 $contact['protocol'] = $contact['network'];
277 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
278 $contact['batch'] = $contact['fbatch'];
280 unset($contact['fbatch']);
283 foreach ($contacts as $entry) {
284 if ($entry['batch'] == $contact['batch']) {
290 $contacts[] = $contact;
299 * repairs a signature that was double encoded
301 * The function is unused at the moment. It was copied from the old implementation.
303 * @param string $signature The signature
304 * @param string $handle The handle of the signature owner
305 * @param integer $level This value is only set inside this function to avoid endless loops
307 * @return string the repaired signature
310 private static function repairSignature($signature, $handle = "", $level = 1)
312 if ($signature == "") {
316 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
317 $signature = base64_decode($signature);
318 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
320 // Do a recursive call to be able to fix even multiple levels
322 $signature = self::repairSignature($signature, $handle, ++$level);
330 * verify the envelope and return the verified data
332 * @param string $envelope The magic envelope
334 * @return string verified data
335 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
336 * @throws \ImagickException
338 private static function verifyMagicEnvelope($envelope)
340 $basedom = XML::parseString($envelope);
342 if (!is_object($basedom)) {
343 Logger::log("Envelope is no XML file");
347 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
349 if (sizeof($children) == 0) {
350 Logger::log("XML has no children");
356 $data = Strings::base64UrlDecode($children->data);
357 $type = $children->data->attributes()->type[0];
359 $encoding = $children->encoding;
361 $alg = $children->alg;
363 $sig = Strings::base64UrlDecode($children->sig);
364 $key_id = $children->sig->attributes()->key_id[0];
366 $handle = Strings::base64UrlDecode($key_id);
369 $b64url_data = Strings::base64UrlEncode($data);
370 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
372 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
375 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
379 $key = self::key($handle);
381 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
385 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
387 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
395 * encrypts data via AES
397 * @param string $key The AES key
398 * @param string $iv The IV (is used for CBC encoding)
399 * @param string $data The data that is to be encrypted
401 * @return string encrypted data
403 private static function aesEncrypt($key, $iv, $data)
405 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
409 * decrypts data via AES
411 * @param string $key The AES key
412 * @param string $iv The IV (is used for CBC encoding)
413 * @param string $encrypted The encrypted data
415 * @return string decrypted data
417 private static function aesDecrypt($key, $iv, $encrypted)
419 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
423 * Decodes incoming Diaspora message in the new format
425 * @param string $raw raw post message
426 * @param string $privKey The private key of the importer
427 * @param boolean $no_exit Don't do an http exit on error
430 * 'message' -> decoded Diaspora XML message
431 * 'author' -> author diaspora handle
432 * 'key' -> author public key (converted to pkcs#8)
433 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
434 * @throws \ImagickException
436 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
438 $data = json_decode($raw);
440 // Is it a private post? Then decrypt the outer Salmon
441 if (is_object($data)) {
442 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
443 $ciphertext = base64_decode($data->encrypted_magic_envelope);
445 $outer_key_bundle = '';
446 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
447 $j_outer_key_bundle = json_decode($outer_key_bundle);
449 if (!is_object($j_outer_key_bundle)) {
450 Logger::log('Outer Salmon did not verify. Discarding.');
454 throw new \Friendica\Network\HTTPException\BadRequestException();
458 $outer_iv = base64_decode($j_outer_key_bundle->iv);
459 $outer_key = base64_decode($j_outer_key_bundle->key);
461 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
466 $basedom = XML::parseString($xml);
468 if (!is_object($basedom)) {
469 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
473 throw new \Friendica\Network\HTTPException\BadRequestException();
477 $base = $basedom->children(ActivityNamespace::SALMON_ME);
479 // Not sure if this cleaning is needed
480 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
482 // Build the signed data
483 $type = $base->data[0]->attributes()->type[0];
484 $encoding = $base->encoding;
486 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
488 // This is the signature
489 $signature = Strings::base64UrlDecode($base->sig);
491 // Get the senders' public key
492 $key_id = $base->sig[0]->attributes()->key_id[0];
493 $author_addr = base64_decode($key_id);
494 if ($author_addr == '') {
495 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
499 throw new \Friendica\Network\HTTPException\BadRequestException();
503 $key = self::key($author_addr);
505 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
509 throw new \Friendica\Network\HTTPException\BadRequestException();
513 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
515 Logger::log('Message did not verify. Discarding.');
519 throw new \Friendica\Network\HTTPException\BadRequestException();
523 return ['message' => (string)Strings::base64UrlDecode($base->data),
524 'author' => XML::unescape($author_addr),
525 'key' => (string)$key];
529 * Decodes incoming Diaspora message in the deprecated format
531 * @param string $xml urldecoded Diaspora salmon
532 * @param string $privKey The private key of the importer
535 * 'message' -> decoded Diaspora XML message
536 * 'author' -> author diaspora handle
537 * 'key' -> author public key (converted to pkcs#8)
538 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
539 * @throws \ImagickException
541 public static function decode(string $xml, string $privKey = '')
544 $basedom = XML::parseString($xml);
546 if (!is_object($basedom)) {
547 Logger::log("XML is not parseable.");
550 $children = $basedom->children('https://joindiaspora.com/protocol');
552 $inner_aes_key = null;
555 if ($children->header) {
557 $author_link = str_replace('acct:', '', $children->header->author_id);
559 // This happens with posts from a relais
560 if (empty($privKey)) {
561 Logger::log("This is no private post in the old format", Logger::DEBUG);
565 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
567 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
568 $ciphertext = base64_decode($encrypted_header->ciphertext);
570 $outer_key_bundle = '';
571 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
573 $j_outer_key_bundle = json_decode($outer_key_bundle);
575 $outer_iv = base64_decode($j_outer_key_bundle->iv);
576 $outer_key = base64_decode($j_outer_key_bundle->key);
578 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
580 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
581 $idom = XML::parseString($decrypted);
583 $inner_iv = base64_decode($idom->iv);
584 $inner_aes_key = base64_decode($idom->aes_key);
586 $author_link = str_replace('acct:', '', $idom->author_id);
589 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
591 // figure out where in the DOM tree our data is hiding
594 if ($dom->provenance->data) {
595 $base = $dom->provenance;
596 } elseif ($dom->env->data) {
598 } elseif ($dom->data) {
603 Logger::log('unable to locate salmon data in xml');
604 throw new \Friendica\Network\HTTPException\BadRequestException();
608 // Stash the signature away for now. We have to find their key or it won't be good for anything.
609 $signature = Strings::base64UrlDecode($base->sig);
613 // strip whitespace so our data element will return to one big base64 blob
614 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
617 // stash away some other stuff for later
619 $type = $base->data[0]->attributes()->type[0];
620 $keyhash = $base->sig[0]->attributes()->keyhash[0];
621 $encoding = $base->encoding;
625 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
629 $data = Strings::base64UrlDecode($data);
633 $inner_decrypted = $data;
635 // Decode the encrypted blob
636 $inner_encrypted = base64_decode($data);
637 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
641 Logger::log('Could not retrieve author URI.');
642 throw new \Friendica\Network\HTTPException\BadRequestException();
644 // Once we have the author URI, go to the web and try to find their public key
645 // (first this will look it up locally if it is in the fcontact cache)
646 // This will also convert diaspora public key from pkcs#1 to pkcs#8
648 Logger::log('Fetching key for '.$author_link);
649 $key = self::key($author_link);
652 Logger::log('Could not retrieve author key.');
653 throw new \Friendica\Network\HTTPException\BadRequestException();
656 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
659 Logger::log('Message did not verify. Discarding.');
660 throw new \Friendica\Network\HTTPException\BadRequestException();
663 Logger::log('Message verified.');
665 return ['message' => (string)$inner_decrypted,
666 'author' => XML::unescape($author_link),
667 'key' => (string)$key];
672 * Dispatches public messages and find the fitting receivers
674 * @param array $msg The post that will be dispatched
676 * @return int The message id of the generated message, "true" or "false" if there was an error
677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
678 * @throws \ImagickException
680 public static function dispatchPublic($msg)
682 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
684 Logger::log("diaspora is disabled");
688 if (!($fields = self::validPosting($msg))) {
689 Logger::log("Invalid posting");
693 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
694 $success = self::dispatch($importer, $msg, $fields);
700 * Dispatches the different message types to the different functions
702 * @param array $importer Array of the importer user
703 * @param array $msg The post that will be dispatched
704 * @param SimpleXMLElement $fields SimpleXML object that contains the message
706 * @return int The message id of the generated message, "true" or "false" if there was an error
707 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
708 * @throws \ImagickException
710 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
712 // The sender is the handle of the contact that sent the message.
713 // This will often be different with relayed messages (for example "like" and "comment")
714 $sender = $msg["author"];
716 // This is only needed for private postings since this is already done for public ones before
717 if (is_null($fields)) {
719 if (!($fields = self::validPosting($msg))) {
720 Logger::log("Invalid posting");
727 $type = $fields->getName();
729 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
732 case "account_migration":
734 Logger::log('Message with type ' . $type . ' is not private, quitting.');
737 return self::receiveAccountMigration($importer, $fields);
739 case "account_deletion":
740 return self::receiveAccountDeletion($fields);
743 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
747 Logger::log('Message with type ' . $type . ' is not private, quitting.');
750 return self::receiveContactRequest($importer, $fields);
754 Logger::log('Message with type ' . $type . ' is not private, quitting.');
757 return self::receiveConversation($importer, $msg, $fields);
760 return self::receiveLike($importer, $sender, $fields);
764 Logger::log('Message with type ' . $type . ' is not private, quitting.');
767 return self::receiveMessage($importer, $fields);
769 case "participation":
771 Logger::log('Message with type ' . $type . ' is not private, quitting.');
774 return self::receiveParticipation($importer, $fields);
776 case "photo": // Not implemented
777 return self::receivePhoto($importer, $fields);
779 case "poll_participation": // Not implemented
780 return self::receivePollParticipation($importer, $fields);
784 Logger::log('Message with type ' . $type . ' is not private, quitting.');
787 return self::receiveProfile($importer, $fields);
790 return self::receiveReshare($importer, $fields, $msg["message"]);
793 return self::receiveRetraction($importer, $sender, $fields);
795 case "status_message":
796 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
799 Logger::log("Unknown message type ".$type);
805 * Checks if a posting is valid and fetches the data fields.
807 * This function does not only check the signature.
808 * It also does the conversion between the old and the new diaspora format.
810 * @param array $msg Array with the XML, the sender handle and the sender signature
812 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
814 * @throws \ImagickException
816 private static function validPosting($msg)
818 $data = XML::parseString($msg["message"]);
820 if (!is_object($data)) {
821 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
825 // Is this the new or the old version?
826 if ($data->getName() == "XML") {
828 foreach ($data->post->children() as $child) {
836 $type = $element->getName();
839 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
841 // All retractions are handled identically from now on.
842 // In the new version there will only be "retraction".
843 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
844 $type = "retraction";
846 if ($type == "request") {
850 $fields = new SimpleXMLElement("<".$type."/>");
853 $author_signature = null;
854 $parent_author_signature = null;
856 foreach ($element->children() as $fieldname => $entry) {
858 // Translation for the old XML structure
859 if ($fieldname == "diaspora_handle") {
860 $fieldname = "author";
862 if ($fieldname == "participant_handles") {
863 $fieldname = "participants";
865 if (in_array($type, ["like", "participation"])) {
866 if ($fieldname == "target_type") {
867 $fieldname = "parent_type";
870 if ($fieldname == "sender_handle") {
871 $fieldname = "author";
873 if ($fieldname == "recipient_handle") {
874 $fieldname = "recipient";
876 if ($fieldname == "root_diaspora_id") {
877 $fieldname = "root_author";
879 if ($type == "status_message") {
880 if ($fieldname == "raw_message") {
884 if ($type == "retraction") {
885 if ($fieldname == "post_guid") {
886 $fieldname = "target_guid";
888 if ($fieldname == "type") {
889 $fieldname = "target_type";
894 if (($fieldname == "author_signature") && ($entry != "")) {
895 $author_signature = base64_decode($entry);
896 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
897 $parent_author_signature = base64_decode($entry);
898 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
899 if ($signed_data != "") {
903 $signed_data .= $entry;
905 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
906 || ($orig_type == "relayable_retraction")
908 XML::copy($entry, $fields, $fieldname);
912 // This is something that shouldn't happen at all.
913 if (in_array($type, ["status_message", "reshare", "profile"])) {
914 if ($msg["author"] != $fields->author) {
915 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
920 // Only some message types have signatures. So we quit here for the other types.
921 if (!in_array($type, ["comment", "like"])) {
924 // No author_signature? This is a must, so we quit.
925 if (!isset($author_signature)) {
926 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
930 if (isset($parent_author_signature)) {
931 $key = self::key($msg["author"]);
933 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
937 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
938 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);
943 $key = self::key($fields->author);
945 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
949 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
950 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);
958 * Fetches the public key for a given handle
960 * @param string $handle The handle
962 * @return string The public key
963 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
964 * @throws \ImagickException
966 private static function key($handle)
968 $handle = strval($handle);
970 Logger::log("Fetching diaspora key for: ".$handle);
972 $r = self::personByHandle($handle);
981 * Fetches data for a given handle
983 * @param string $handle The handle
984 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
986 * @return array the queried data
987 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
988 * @throws \ImagickException
990 public static function personByHandle($handle, $update = null)
992 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
993 if (!DBA::isResult($person)) {
994 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
995 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
998 if (DBA::isResult($person)) {
999 Logger::debug("In cache " . print_r($person, true));
1001 if (is_null($update)) {
1002 // update record occasionally so it doesn't get stale
1003 $d = strtotime($person["updated"]." +00:00");
1004 if ($d < strtotime("now - 14 days")) {
1008 if ($person["guid"] == "") {
1012 } elseif (is_null($update)) {
1013 $update = !DBA::isResult($person);
1019 Logger::log("create or refresh", Logger::DEBUG);
1020 $r = Probe::uri($handle, Protocol::DIASPORA);
1022 // Note that Friendica contacts will return a "Diaspora person"
1023 // if Diaspora connectivity is enabled on their server
1024 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1025 self::updateFContact($r);
1027 $person = self::personByHandle($handle, false);
1035 * Updates the fcontact table
1037 * @param array $arr The fcontact data
1038 * @throws \Exception
1040 private static function updateFContact($arr)
1042 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1043 'request' => $arr["request"], 'nick' => $arr["nick"],
1044 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1045 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1046 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1047 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1048 'updated' => DateTimeFormat::utcNow()];
1050 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1052 DBA::update('fcontact', $fields, $condition, true);
1056 * get a handle (user@domain.tld) from a given contact id
1058 * @param int $contact_id The id in the contact table
1059 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1061 * @return string the handle
1062 * @throws \Exception
1064 private static function handleFromContact($contact_id, $pcontact_id = 0)
1068 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1070 if ($pcontact_id != 0) {
1071 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1073 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1074 return strtolower($contact["addr"]);
1079 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1083 if (DBA::isResult($r)) {
1086 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1088 if ($contact['addr'] != "") {
1089 $handle = $contact['addr'];
1091 $baseurl_start = strpos($contact['url'], '://') + 3;
1092 // allows installations in a subdirectory--not sure how Diaspora will handle
1093 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1094 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1095 $handle = $contact['nick'].'@'.$baseurl;
1099 return strtolower($handle);
1103 * get a url (scheme://domain.tld/u/user) from a given Diaspora*
1106 * @param mixed $fcontact_guid Hexadecimal string guid
1108 * @return string the contact url or null
1109 * @throws \Exception
1111 public static function urlFromContactGuid($fcontact_guid)
1113 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1116 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1117 DBA::escape(Protocol::DIASPORA),
1118 DBA::escape($fcontact_guid)
1121 if (DBA::isResult($r)) {
1122 return $r[0]['url'];
1129 * Get a contact id for a given handle
1131 * @todo Move to Friendica\Model\Contact
1133 * @param int $uid The user id
1134 * @param string $handle The handle in the format user@domain.tld
1136 * @return array Contact data
1137 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1138 * @throws \ImagickException
1140 private static function contactByHandle($uid, $handle)
1142 $cid = Contact::getIdForURL($handle, $uid);
1144 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1148 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1149 if (!DBA::isResult($contact)) {
1150 // This here shouldn't happen at all
1151 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1159 * Checks if the given contact url does support ActivityPub
1161 * @param string $url profile url
1162 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1164 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1165 * @throws \ImagickException
1167 public static function isSupportedByContactUrl($url, $update = null)
1169 return !empty(self::personByHandle($url, $update));
1173 * Check if posting is allowed for this contact
1175 * @param array $importer Array of the importer user
1176 * @param array $contact The contact that is checked
1177 * @param bool $is_comment Is the check for a comment?
1179 * @return bool is the contact allowed to post?
1181 private static function postAllow(array $importer, array $contact, $is_comment = false)
1184 * Perhaps we were already sharing with this person. Now they're sharing with us.
1185 * That makes us friends.
1186 * Normally this should have handled by getting a request - but this could get lost
1188 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1189 // It is not removed by now. Possibly the code is needed?
1190 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1193 // array('rel' => Contact::FRIEND, 'writable' => true),
1194 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1197 // $contact["rel"] = Contact::FRIEND;
1198 // Logger::log("defining user ".$contact["nick"]." as friend");
1201 // Contact server is blocked
1202 if (Network::isUrlBlocked($contact['url'])) {
1204 // We don't seem to like that person
1205 } elseif ($contact["blocked"]) {
1206 // Maybe blocked, don't accept.
1208 // We are following this person?
1209 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1210 // Yes, then it is fine.
1212 // Is it a post to a community?
1213 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1216 // Is the message a global user or a comment?
1217 } elseif (($importer["uid"] == 0) || $is_comment) {
1218 // Messages for the global users and comments are always accepted
1226 * Fetches the contact id for a handle and checks if posting is allowed
1228 * @param array $importer Array of the importer user
1229 * @param string $handle The checked handle in the format user@domain.tld
1230 * @param bool $is_comment Is the check for a comment?
1232 * @return array The contact data
1233 * @throws \Exception
1235 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1237 $contact = self::contactByHandle($importer["uid"], $handle);
1239 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1240 // If a contact isn't found, we accept it anyway if it is a comment
1241 if ($is_comment && ($importer["uid"] != 0)) {
1242 return self::contactByHandle(0, $handle);
1243 } elseif ($is_comment) {
1250 if (!self::postAllow($importer, $contact, $is_comment)) {
1251 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1258 * Does the message already exists on the system?
1260 * @param int $uid The user id
1261 * @param string $guid The guid of the message
1263 * @return int|bool message id if the message already was stored into the system - or false.
1264 * @throws \Exception
1266 private static function messageExists($uid, $guid)
1268 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1269 if (DBA::isResult($item)) {
1270 Logger::log("message ".$guid." already exists for user ".$uid);
1278 * Checks for links to posts in a message
1280 * @param array $item The item array
1283 private static function fetchGuid(array $item)
1285 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1286 preg_replace_callback(
1288 function ($match) use ($item) {
1289 self::fetchGuidSub($match, $item);
1294 preg_replace_callback(
1295 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1296 function ($match) use ($item) {
1297 self::fetchGuidSub($match, $item);
1304 * Checks for relative /people/* links in an item body to match local
1305 * contacts or prepends the remote host taken from the author link.
1307 * @param string $body The item body to replace links from
1308 * @param string $author_link The author link for missing local contact fallback
1310 * @return string the replaced string
1312 public static function replacePeopleGuid($body, $author_link)
1314 $return = preg_replace_callback(
1315 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1316 function ($match) use ($author_link) {
1318 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1319 // 1 => '0123456789abcdef'
1321 $handle = self::urlFromContactGuid($match[1]);
1324 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1326 // No local match, restoring absolute remote URL from author scheme and host
1327 $author_url = parse_url($author_link);
1328 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1340 * sub function of "fetchGuid" which checks for links in messages
1342 * @param array $match array containing a link that has to be checked for a message link
1343 * @param array $item The item array
1345 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1346 * @throws \ImagickException
1348 private static function fetchGuidSub($match, $item)
1350 if (!self::storeByGuid($match[1], $item["author-link"])) {
1351 self::storeByGuid($match[1], $item["owner-link"]);
1356 * Fetches an item with a given guid from a given server
1358 * @param string $guid the message guid
1359 * @param string $server The server address
1360 * @param int $uid The user id of the user
1362 * @return int the message id of the stored message or false
1363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1364 * @throws \ImagickException
1366 private static function storeByGuid($guid, $server, $uid = 0)
1368 $serverparts = parse_url($server);
1370 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1374 $server = $serverparts["scheme"]."://".$serverparts["host"];
1376 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1378 $msg = self::message($guid, $server);
1384 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1386 // Now call the dispatcher
1387 return self::dispatchPublic($msg);
1391 * Fetches a message from a server
1393 * @param string $guid message guid
1394 * @param string $server The url of the server
1395 * @param int $level Endless loop prevention
1398 * 'message' => The message XML
1399 * 'author' => The author handle
1400 * 'key' => The public key of the author
1401 * @throws \Exception
1403 private static function message($guid, $server, $level = 0)
1409 // This will work for new Diaspora servers and Friendica servers from 3.5
1410 $source_url = $server."/fetch/post/".urlencode($guid);
1412 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1414 $envelope = Network::fetchUrl($source_url);
1416 Logger::log("Envelope was fetched.", Logger::DEBUG);
1417 $x = self::verifyMagicEnvelope($envelope);
1419 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1421 Logger::log("Envelope was verified.", Logger::DEBUG);
1431 $source_xml = XML::parseString($x);
1433 if (!is_object($source_xml)) {
1437 if ($source_xml->post->reshare) {
1438 // Reshare of a reshare - old Diaspora version
1439 Logger::log("Message is a reshare", Logger::DEBUG);
1440 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1441 } elseif ($source_xml->getName() == "reshare") {
1442 // Reshare of a reshare - new Diaspora version
1443 Logger::log("Message is a new reshare", Logger::DEBUG);
1444 return self::message($source_xml->root_guid, $server, ++$level);
1449 // Fetch the author - for the old and the new Diaspora version
1450 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1451 $author = (string)$source_xml->post->status_message->diaspora_handle;
1452 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1453 $author = (string)$source_xml->author;
1456 // If this isn't a "status_message" then quit
1458 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1462 $msg = ["message" => $x, "author" => $author];
1464 $msg["key"] = self::key($msg["author"]);
1470 * Fetches an item with a given URL
1472 * @param string $url the message url
1474 * @return int the message id of the stored message or false
1475 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1476 * @throws \ImagickException
1478 public static function fetchByURL($url, $uid = 0)
1480 // Check for Diaspora (and Friendica) typical paths
1481 if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1482 Logger::info('Invalid url', ['url' => $url]);
1486 $guid = urldecode($matches[2]);
1488 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1489 if (DBA::isResult($item)) {
1490 Logger::info('Found', ['id' => $item['id']]);
1494 Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]);
1495 $ret = self::storeByGuid($guid, $matches[1], $uid);
1496 Logger::info('Result', ['ret' => $ret]);
1498 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1499 if (DBA::isResult($item)) {
1500 Logger::info('Found', ['id' => $item['id']]);
1503 Logger::info('Not found', ['guid' => $guid, 'uid' => $uid]);
1509 * Fetches the item record of a given guid
1511 * @param int $uid The user id
1512 * @param string $guid message guid
1513 * @param string $author The handle of the item
1514 * @param array $contact The contact of the item owner
1516 * @return array the item record
1517 * @throws \Exception
1519 private static function parentItem($uid, $guid, $author, array $contact)
1521 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1522 'author-name', 'author-link', 'author-avatar',
1523 'owner-name', 'owner-link', 'owner-avatar'];
1524 $condition = ['uid' => $uid, 'guid' => $guid];
1525 $item = Item::selectFirst($fields, $condition);
1527 if (!DBA::isResult($item)) {
1528 $person = self::personByHandle($author);
1529 $result = self::storeByGuid($guid, $person["url"], $uid);
1531 // We don't have an url for items that arrived at the public dispatcher
1532 if (!$result && !empty($contact["url"])) {
1533 $result = self::storeByGuid($guid, $contact["url"], $uid);
1537 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1539 $item = Item::selectFirst($fields, $condition);
1543 if (!DBA::isResult($item)) {
1544 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1547 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1553 * returns contact details
1555 * @param array $def_contact The default contact if the person isn't found
1556 * @param array $person The record of the person
1557 * @param int $uid The user id
1560 * 'cid' => contact id
1561 * 'network' => network type
1562 * @throws \Exception
1564 private static function authorContactByUrl($def_contact, $person, $uid)
1566 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1567 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1568 if (DBA::isResult($contact)) {
1569 $cid = $contact["id"];
1570 $network = $contact["network"];
1572 $cid = $def_contact["id"];
1573 $network = Protocol::DIASPORA;
1576 return ["cid" => $cid, "network" => $network];
1580 * Is the profile a hubzilla profile?
1582 * @param string $url The profile link
1584 * @return bool is it a hubzilla server?
1586 private static function isHubzilla($url)
1588 return(strstr($url, '/channel/'));
1592 * Generate a post link with a given handle and message guid
1594 * @param string $addr The user handle
1595 * @param string $guid message guid
1596 * @param string $parent_guid optional parent guid
1598 * @return string the post link
1599 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1600 * @throws \ImagickException
1602 private static function plink($addr, $guid, $parent_guid = '')
1604 $contact = Contact::getDetailsByAddr($addr);
1605 if (empty($contact)) {
1606 Logger::info('No contact data for address', ['addr' => $addr]);
1610 if (empty($contact['baseurl'])) {
1611 $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1);
1612 Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]);
1616 $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]);
1617 if (!empty($gserver['platform'])) {
1618 $platform = strtolower($gserver['platform']);
1619 Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]);
1622 if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) {
1623 if (self::isHubzilla($contact['url'])) {
1624 Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]);
1625 $platform = 'hubzilla';
1626 } elseif ($contact['network'] == Protocol::DFRN) {
1627 Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]);
1628 $platform = 'friendica';
1632 if ($platform == 'friendica') {
1633 return str_replace('/profile/' . $contact['nick'] . '/', '/display/' . $guid, $contact['url'] . '/');
1636 if ($platform == 'hubzilla') {
1637 return $contact['baseurl'] . '/item/' . $guid;
1640 if ($platform == 'socialhome') {
1641 return $contact['baseurl'] . '/content/' . $guid;
1644 if ($platform != 'diaspora') {
1645 Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]);
1649 if ($parent_guid != '') {
1650 return $contact['baseurl'] . '/posts/' . $parent_guid . '#' . $guid;
1652 return $contact['baseurl'] . '/posts/' . $guid;
1657 * Receives account migration
1659 * @param array $importer Array of the importer user
1660 * @param object $data The message object
1662 * @return bool Success
1663 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1664 * @throws \ImagickException
1666 private static function receiveAccountMigration(array $importer, $data)
1668 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1669 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1670 $signature = Strings::escapeTags(XML::unescape($data->signature));
1672 $contact = self::contactByHandle($importer["uid"], $old_handle);
1674 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1678 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1681 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1682 $key = self::key($old_handle);
1683 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1684 Logger::log('No valid signature for migration.');
1688 // Update the profile
1689 self::receiveProfile($importer, $data->profile);
1691 // change the technical stuff in contact and gcontact
1692 $data = Probe::uri($new_handle);
1693 if ($data['network'] == Protocol::PHANTOM) {
1694 Logger::log('Account for '.$new_handle." couldn't be probed.");
1698 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1699 'name' => $data['name'], 'nick' => $data['nick'],
1700 'addr' => $data['addr'], 'batch' => $data['batch'],
1701 'notify' => $data['notify'], 'poll' => $data['poll'],
1702 'network' => $data['network']];
1704 DBA::update('contact', $fields, ['addr' => $old_handle]);
1706 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1707 'name' => $data['name'], 'nick' => $data['nick'],
1708 'addr' => $data['addr'], 'connect' => $data['addr'],
1709 'notify' => $data['notify'], 'photo' => $data['photo'],
1710 'server_url' => $data['baseurl'], 'network' => $data['network']];
1712 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1714 Logger::log('Contacts are updated.');
1720 * Processes an account deletion
1722 * @param object $data The message object
1724 * @return bool Success
1725 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1727 private static function receiveAccountDeletion($data)
1729 $author = Strings::escapeTags(XML::unescape($data->author));
1731 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1732 while ($contact = DBA::fetch($contacts)) {
1733 Contact::remove($contact["id"]);
1736 DBA::delete('gcontact', ['addr' => $author]);
1738 Logger::log('Removed contacts for ' . $author);
1744 * Fetch the uri from our database if we already have this item (maybe from ourselves)
1746 * @param string $author Author handle
1747 * @param string $guid Message guid
1748 * @param boolean $onlyfound Only return uri when found in the database
1750 * @return string The constructed uri or the one from our database
1751 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1752 * @throws \ImagickException
1754 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1756 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1757 if (DBA::isResult($item)) {
1758 return $item["uri"];
1759 } elseif (!$onlyfound) {
1760 $person = self::personByHandle($author);
1762 $parts = parse_url($person['url']);
1763 unset($parts['path']);
1764 $host_url = Network::unparseURL($parts);
1766 return $host_url . '/objects/' . $guid;
1773 * Fetch the guid from our database with a given uri
1775 * @param string $uri Message uri
1776 * @param string $uid Author handle
1778 * @return string The post guid
1779 * @throws \Exception
1781 private static function getGuidFromUri($uri, $uid)
1783 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1784 if (DBA::isResult($item)) {
1785 return $item["guid"];
1792 * Find the best importer for a comment, like, ...
1794 * @param string $guid The guid of the item
1796 * @return array|boolean the origin owner of that post - or false
1797 * @throws \Exception
1799 private static function importerForGuid($guid)
1801 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1802 if (DBA::isResult($item)) {
1803 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1804 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1805 if (DBA::isResult($contact)) {
1812 private static function storeMentions(int $uriid, string $text)
1814 preg_match_all('/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', $text, $matches, PREG_SET_ORDER);
1815 if (empty($matches)) {
1820 * Matching values for the preg match
1821 * [1] = mention type (@ or !)
1822 * [2] = name (optional)
1826 foreach ($matches as $match) {
1827 if (empty($match)) {
1831 $person = self::personByHandle($match[3]);
1832 if (empty($person)) {
1836 $fields = ['uri-id' => $uriid, 'name' => substr($person['addr'], 0, 64), 'url' => $person['url']];
1838 if ($match[1] == Term::TAG_CHARACTER[Term::MENTION]) {
1839 $fields['type'] = Term::MENTION;
1840 } elseif ($match[1] == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]) {
1841 $fields['type'] = Term::EXCLUSIVE_MENTION;
1842 } elseif ($match[1] == Term::TAG_CHARACTER[Term::IMPLICIT_MENTION]) {
1843 $fields['type'] = Term::IMPLICIT_MENTION;
1848 DBA::insert('tag', $fields, true);
1849 Logger::info('Stored mention', ['uriid' => $uriid, 'match' => $match, 'fields' => $fields]);
1853 private static function storeTags(int $uriid, string $body)
1855 $tags = BBCode::getTags($body);
1860 foreach ($tags as $tag) {
1861 if ((substr($tag, 0, 1) != Term::TAG_CHARACTER[Term::HASHTAG]) || (strlen($tag) <= 1)) {
1862 Logger::info('Skip tag', ['uriid' => $uriid, 'tag' => $tag]);
1866 $fields = ['uri-id' => $uriid, 'name' => substr($tag, 1, 64), 'type' => Term::HASHTAG];
1867 DBA::insert('tag', $fields, true);
1868 Logger::info('Stored tag', ['uriid' => $uriid, 'tag' => $tag, 'fields' => $fields]);
1873 * Processes an incoming comment
1875 * @param array $importer Array of the importer user
1876 * @param string $sender The sender of the message
1877 * @param object $data The message object
1878 * @param string $xml The original XML of the message
1880 * @return int The message id of the generated comment or "false" if there was an error
1881 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1882 * @throws \ImagickException
1884 private static function receiveComment(array $importer, $sender, $data, $xml)
1886 $author = Strings::escapeTags(XML::unescape($data->author));
1887 $guid = Strings::escapeTags(XML::unescape($data->guid));
1888 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1889 $text = XML::unescape($data->text);
1891 if (isset($data->created_at)) {
1892 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1894 $created_at = DateTimeFormat::utcNow();
1897 if (isset($data->thread_parent_guid)) {
1898 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1899 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1904 $contact = self::allowedContactByHandle($importer, $sender, true);
1909 $message_id = self::messageExists($importer["uid"], $guid);
1914 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1915 if (!$parent_item) {
1919 $person = self::personByHandle($author);
1920 if (!is_array($person)) {
1921 Logger::log("unable to find author details");
1925 // Fetch the contact id - if we know this contact
1926 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1930 $datarray["uid"] = $importer["uid"];
1931 $datarray["contact-id"] = $author_contact["cid"];
1932 $datarray["network"] = $author_contact["network"];
1934 $datarray["author-link"] = $person["url"];
1935 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1937 $datarray["owner-link"] = $contact["url"];
1938 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1940 $datarray["guid"] = $guid;
1941 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1942 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1944 $datarray["verb"] = Activity::POST;
1945 $datarray["gravity"] = GRAVITY_COMMENT;
1947 if ($thr_uri != "") {
1948 $datarray["parent-uri"] = $thr_uri;
1950 $datarray["parent-uri"] = $parent_item["uri"];
1953 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1955 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1956 $datarray["source"] = $xml;
1958 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1960 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1962 $body = Markdown::toBBCode($text);
1964 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1966 self::storeMentions($datarray['uri-id'], $text);
1967 self::storeTags($datarray['uri-id'], $datarray["body"]);
1969 self::fetchGuid($datarray);
1971 // If we are the origin of the parent we store the original data.
1972 // We notify our followers during the item storage.
1973 if ($parent_item["origin"]) {
1974 $datarray['diaspora_signed_text'] = json_encode($data);
1977 $message_id = Item::insert($datarray);
1979 if ($message_id <= 0) {
1984 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1985 if ($datarray['uid'] == 0) {
1986 Item::distribute($message_id, json_encode($data));
1994 * processes and stores private messages
1996 * @param array $importer Array of the importer user
1997 * @param array $contact The contact of the message
1998 * @param object $data The message object
1999 * @param array $msg Array of the processed message, author handle and key
2000 * @param object $mesg The private message
2001 * @param array $conversation The conversation record to which this message belongs
2003 * @return bool "true" if it was successful
2004 * @throws \Exception
2006 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
2008 $author = Strings::escapeTags(XML::unescape($data->author));
2009 $guid = Strings::escapeTags(XML::unescape($data->guid));
2010 $subject = Strings::escapeTags(XML::unescape($data->subject));
2012 // "diaspora_handle" is the element name from the old version
2013 // "author" is the element name from the new version
2014 if ($mesg->author) {
2015 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
2016 } elseif ($mesg->diaspora_handle) {
2017 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
2022 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
2023 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
2024 $msg_text = XML::unescape($mesg->text);
2025 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
2027 if ($msg_conversation_guid != $guid) {
2028 Logger::log("message conversation guid does not belong to the current conversation.");
2032 $body = Markdown::toBBCode($msg_text);
2033 $message_uri = $msg_author.":".$msg_guid;
2035 $person = self::personByHandle($msg_author);
2037 return Mail::insert([
2038 'uid' => $importer['uid'],
2039 'guid' => $msg_guid,
2040 'convid' => $conversation['id'],
2041 'from-name' => $person['name'],
2042 'from-photo' => $person['photo'],
2043 'from-url' => $person['url'],
2044 'contact-id' => $contact['id'],
2045 'title' => $subject,
2047 'uri' => $message_uri,
2048 'parent-uri' => $author . ':' . $guid,
2049 'created' => $msg_created_at
2054 * Processes new private messages (answers to private messages are processed elsewhere)
2056 * @param array $importer Array of the importer user
2057 * @param array $msg Array of the processed message, author handle and key
2058 * @param object $data The message object
2060 * @return bool Success
2061 * @throws \Exception
2063 private static function receiveConversation(array $importer, $msg, $data)
2065 $author = Strings::escapeTags(XML::unescape($data->author));
2066 $guid = Strings::escapeTags(XML::unescape($data->guid));
2067 $subject = Strings::escapeTags(XML::unescape($data->subject));
2068 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2069 $participants = Strings::escapeTags(XML::unescape($data->participants));
2071 $messages = $data->message;
2073 if (!count($messages)) {
2074 Logger::log("empty conversation");
2078 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
2083 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2084 if (!DBA::isResult($conversation)) {
2086 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
2087 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
2088 intval($importer["uid"]),
2090 DBA::escape($author),
2091 DBA::escape($created_at),
2092 DBA::escape(DateTimeFormat::utcNow()),
2093 DBA::escape($subject),
2094 DBA::escape($participants)
2097 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
2100 if (!$conversation) {
2101 Logger::log("unable to create conversation.");
2105 foreach ($messages as $mesg) {
2106 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2113 * Processes "like" messages
2115 * @param array $importer Array of the importer user
2116 * @param string $sender The sender of the message
2117 * @param object $data The message object
2119 * @return int The message id of the generated like or "false" if there was an error
2120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2121 * @throws \ImagickException
2123 private static function receiveLike(array $importer, $sender, $data)
2125 $author = Strings::escapeTags(XML::unescape($data->author));
2126 $guid = Strings::escapeTags(XML::unescape($data->guid));
2127 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2128 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2129 $positive = Strings::escapeTags(XML::unescape($data->positive));
2131 // likes on comments aren't supported by Diaspora - only on posts
2132 // But maybe this will be supported in the future, so we will accept it.
2133 if (!in_array($parent_type, ["Post", "Comment"])) {
2137 $contact = self::allowedContactByHandle($importer, $sender, true);
2142 $message_id = self::messageExists($importer["uid"], $guid);
2147 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2148 if (!$parent_item) {
2152 $person = self::personByHandle($author);
2153 if (!is_array($person)) {
2154 Logger::log("unable to find author details");
2158 // Fetch the contact id - if we know this contact
2159 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2161 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2162 // We would accept this anyhow.
2163 if ($positive == "true") {
2164 $verb = Activity::LIKE;
2166 $verb = Activity::DISLIKE;
2171 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2173 $datarray["uid"] = $importer["uid"];
2174 $datarray["contact-id"] = $author_contact["cid"];
2175 $datarray["network"] = $author_contact["network"];
2177 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2178 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2180 $datarray["guid"] = $guid;
2181 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2183 $datarray["verb"] = $verb;
2184 $datarray["gravity"] = GRAVITY_ACTIVITY;
2185 $datarray["parent-uri"] = $parent_item["uri"];
2187 $datarray["object-type"] = Activity\ObjectType::NOTE;
2189 $datarray["body"] = $verb;
2191 // Diaspora doesn't provide a date for likes
2192 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2194 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2195 if ($parent_item["id"] != $parent_item["parent"]) {
2196 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2197 $origin = $toplevel["origin"];
2199 $origin = $parent_item["origin"];
2202 // If we are the origin of the parent we store the original data.
2203 // We notify our followers during the item storage.
2205 $datarray['diaspora_signed_text'] = json_encode($data);
2208 $message_id = Item::insert($datarray);
2210 if ($message_id <= 0) {
2215 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2216 if ($datarray['uid'] == 0) {
2217 Item::distribute($message_id, json_encode($data));
2225 * Processes private messages
2227 * @param array $importer Array of the importer user
2228 * @param object $data The message object
2230 * @return bool Success?
2231 * @throws \Exception
2233 private static function receiveMessage(array $importer, $data)
2235 $author = Strings::escapeTags(XML::unescape($data->author));
2236 $guid = Strings::escapeTags(XML::unescape($data->guid));
2237 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2238 $text = XML::unescape($data->text);
2239 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2241 $contact = self::allowedContactByHandle($importer, $author, true);
2246 $conversation = null;
2248 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2249 $conversation = DBA::selectFirst('conv', [], $condition);
2251 if (!DBA::isResult($conversation)) {
2252 Logger::log("conversation not available.");
2256 $message_uri = $author.":".$guid;
2258 $person = self::personByHandle($author);
2260 Logger::log("unable to find author details");
2264 $body = Markdown::toBBCode($text);
2266 $body = self::replacePeopleGuid($body, $person["url"]);
2268 return Mail::insert([
2269 'uid' => $importer['uid'],
2271 'convid' => $conversation['id'],
2272 'from-name' => $person['name'],
2273 'from-photo' => $person['photo'],
2274 'from-url' => $person['url'],
2275 'contact-id' => $contact['id'],
2276 'title' => $conversation['subject'],
2279 'uri' => $message_uri,
2280 'parent-uri' => $author.":".$conversation['guid'],
2281 'created' => $created_at
2286 * Processes participations - unsupported by now
2288 * @param array $importer Array of the importer user
2289 * @param object $data The message object
2291 * @return bool always true
2292 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2293 * @throws \ImagickException
2295 private static function receiveParticipation(array $importer, $data)
2297 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2298 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2300 $contact_id = Contact::getIdForURL($author);
2302 Logger::log('Contact not found: '.$author);
2306 $person = self::personByHandle($author);
2307 if (!is_array($person)) {
2308 Logger::log("Person not found: ".$author);
2312 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2313 if (!DBA::isResult($item)) {
2314 Logger::log('Item not found, no origin or private: '.$parent_guid);
2318 $author_parts = explode('@', $author);
2319 if (isset($author_parts[1])) {
2320 $server = $author_parts[1];
2322 // Should never happen
2326 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2328 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2329 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2332 // Send all existing comments and likes to the requesting server
2333 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2334 while ($comment = Item::fetch($comments)) {
2335 if ($comment['id'] == $comment['parent']) {
2339 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2340 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id)) {
2341 ItemDeliveryData::incrementQueueCount($comment['id'], 1);
2344 DBA::close($comments);
2350 * Processes photos - unneeded
2352 * @param array $importer Array of the importer user
2353 * @param object $data The message object
2355 * @return bool always true
2357 private static function receivePhoto(array $importer, $data)
2359 // There doesn't seem to be a reason for this function,
2360 // since the photo data is transmitted in the status message as well
2365 * Processes poll participations - unssupported
2367 * @param array $importer Array of the importer user
2368 * @param object $data The message object
2370 * @return bool always true
2372 private static function receivePollParticipation(array $importer, $data)
2374 // We don't support polls by now
2379 * Processes incoming profile updates
2381 * @param array $importer Array of the importer user
2382 * @param object $data The message object
2384 * @return bool Success
2385 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2386 * @throws \ImagickException
2388 private static function receiveProfile(array $importer, $data)
2390 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2392 $contact = self::contactByHandle($importer["uid"], $author);
2397 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2398 $image_url = XML::unescape($data->image_url);
2399 $birthday = XML::unescape($data->birthday);
2400 $about = Markdown::toBBCode(XML::unescape($data->bio));
2401 $location = Markdown::toBBCode(XML::unescape($data->location));
2402 $searchable = (XML::unescape($data->searchable) == "true");
2403 $nsfw = (XML::unescape($data->nsfw) == "true");
2404 $tags = XML::unescape($data->tag_string);
2406 $tags = explode("#", $tags);
2409 foreach ($tags as $tag) {
2410 $tag = trim(strtolower($tag));
2416 $keywords = implode(", ", $keywords);
2418 $handle_parts = explode("@", $author);
2419 $nick = $handle_parts[0];
2422 $name = $handle_parts[0];
2425 if (preg_match("|^https?://|", $image_url) === 0) {
2426 $image_url = "http://".$handle_parts[1].$image_url;
2429 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2431 // Generic birthday. We don't know the timezone. The year is irrelevant.
2433 $birthday = str_replace("1000", "1901", $birthday);
2435 if ($birthday != "") {
2436 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2439 // this is to prevent multiple birthday notifications in a single year
2440 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2442 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2443 $birthday = $contact["bd"];
2446 $fields = ['name' => $name, 'location' => $location,
2447 'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2448 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2449 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2451 if (!empty($birthday)) {
2452 $fields['bd'] = $birthday;
2455 DBA::update('contact', $fields, ['id' => $contact['id']]);
2457 // @todo Update the public contact, then update the gcontact from that
2459 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2460 "photo" => $image_url, "name" => $name, "location" => $location,
2461 "about" => $about, "birthday" => $birthday,
2462 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2463 "hide" => !$searchable, "nsfw" => $nsfw];
2465 $gcid = GContact::update($gcontact);
2467 GContact::link($gcid, $importer["uid"], $contact["id"]);
2469 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2475 * Processes incoming friend requests
2477 * @param array $importer Array of the importer user
2478 * @param array $contact The contact that send the request
2480 * @throws \Exception
2482 private static function receiveRequestMakeFriend(array $importer, array $contact)
2484 if ($contact["rel"] == Contact::SHARING) {
2487 ['rel' => Contact::FRIEND, 'writable' => true],
2488 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2494 * Processes incoming sharing notification
2496 * @param array $importer Array of the importer user
2497 * @param object $data The message object
2499 * @return bool Success
2500 * @throws \Exception
2502 private static function receiveContactRequest(array $importer, $data)
2504 $author = XML::unescape($data->author);
2505 $recipient = XML::unescape($data->recipient);
2507 if (!$author || !$recipient) {
2511 // the current protocol version doesn't know these fields
2512 // That means that we will assume their existance
2513 if (isset($data->following)) {
2514 $following = (XML::unescape($data->following) == "true");
2519 if (isset($data->sharing)) {
2520 $sharing = (XML::unescape($data->sharing) == "true");
2525 $contact = self::contactByHandle($importer["uid"], $author);
2527 // perhaps we were already sharing with this person. Now they're sharing with us.
2528 // That makes us friends.
2531 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2532 self::receiveRequestMakeFriend($importer, $contact);
2534 // refetch the contact array
2535 $contact = self::contactByHandle($importer["uid"], $author);
2537 // If we are now friends, we are sending a share message.
2538 // Normally we needn't to do so, but the first message could have been vanished.
2539 if (in_array($contact["rel"], [Contact::FRIEND])) {
2540 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2541 if (DBA::isResult($user)) {
2542 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2543 self::sendShare($user, $contact);
2548 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2549 Contact::removeFollower($importer, $contact);
2554 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2555 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2557 } elseif (!$following && !$sharing) {
2558 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2560 } elseif (!$following && $sharing) {
2561 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2562 } elseif ($following && $sharing) {
2563 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2564 } elseif ($following && !$sharing) {
2565 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2568 $ret = self::personByHandle($author);
2570 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2571 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2575 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2577 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2582 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2583 'author-link' => $ret['url']];
2585 $result = Contact::addRelationship($importer, $contact, $item, false);
2586 if ($result === true) {
2587 $contact_record = self::contactByHandle($importer['uid'], $author);
2588 if (!$contact_record) {
2589 Logger::info('unable to locate newly created contact record.');
2593 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2594 if (DBA::isResult($user)) {
2595 self::sendShare($user, $contact_record);
2597 // Send the profile data, maybe it weren't transmitted before
2598 self::sendProfile($importer['uid'], [$contact_record]);
2606 * Fetches a message with a given guid
2608 * @param string $guid message guid
2609 * @param string $orig_author handle of the original post
2610 * @return array The fetched item
2611 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2612 * @throws \ImagickException
2614 public static function originalItem($guid, $orig_author)
2617 Logger::log('Empty guid. Quitting.');
2621 // Do we already have this item?
2622 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2623 'author-name', 'author-link', 'author-avatar'];
2624 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2625 $item = Item::selectFirst($fields, $condition);
2627 if (DBA::isResult($item)) {
2628 Logger::log("reshared message ".$guid." already exists on system.");
2630 // Maybe it is already a reshared item?
2631 // Then refetch the content, if it is a reshare from a reshare.
2632 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2633 if (self::isReshare($item["body"], true)) {
2635 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2636 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2638 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2640 // Add OEmbed and other information to the body
2641 $item["body"] = add_page_info_to_body($item["body"], false, true);
2649 if (!DBA::isResult($item)) {
2650 if (empty($orig_author)) {
2651 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2655 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2656 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2657 $stored = self::storeByGuid($guid, $server);
2660 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2661 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2662 $stored = self::storeByGuid($guid, $server);
2666 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2667 'author-name', 'author-link', 'author-avatar'];
2668 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2669 $item = Item::selectFirst($fields, $condition);
2671 if (DBA::isResult($item)) {
2672 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2673 if (self::isReshare($item["body"], false)) {
2674 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2675 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2686 * Stores a reshare activity
2688 * @param array $item Array of reshare post
2689 * @param integer $parent_message_id Id of the parent post
2690 * @param string $guid GUID string of reshare action
2691 * @param string $author Author handle
2693 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2695 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2699 $datarray['uid'] = $item['uid'];
2700 $datarray['contact-id'] = $item['contact-id'];
2701 $datarray['network'] = $item['network'];
2703 $datarray['author-link'] = $item['author-link'];
2704 $datarray['author-id'] = $item['author-id'];
2706 $datarray['owner-link'] = $datarray['author-link'];
2707 $datarray['owner-id'] = $datarray['author-id'];
2709 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2710 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2712 $datarray['parent-uri'] = $parent['uri'];
2714 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2715 $datarray['gravity'] = GRAVITY_ACTIVITY;
2716 $datarray['object-type'] = Activity\ObjectType::NOTE;
2718 $datarray['protocol'] = $item['protocol'];
2720 $datarray['plink'] = self::plink($author, $datarray['guid']);
2721 $datarray['private'] = $item['private'];
2722 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2724 $message_id = Item::insert($datarray);
2727 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2728 if ($datarray['uid'] == 0) {
2729 Item::distribute($message_id);
2735 * Processes a reshare message
2737 * @param array $importer Array of the importer user
2738 * @param object $data The message object
2739 * @param string $xml The original XML of the message
2741 * @return int the message id
2742 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2743 * @throws \ImagickException
2745 private static function receiveReshare(array $importer, $data, $xml)
2747 $author = Strings::escapeTags(XML::unescape($data->author));
2748 $guid = Strings::escapeTags(XML::unescape($data->guid));
2749 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2750 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2751 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2752 /// @todo handle unprocessed property "provider_display_name"
2753 $public = Strings::escapeTags(XML::unescape($data->public));
2755 $contact = self::allowedContactByHandle($importer, $author, false);
2760 $message_id = self::messageExists($importer["uid"], $guid);
2765 $original_item = self::originalItem($root_guid, $root_author);
2766 if (!$original_item) {
2770 $orig_url = DI::baseUrl()."/display/".$original_item["guid"];
2774 $datarray["uid"] = $importer["uid"];
2775 $datarray["contact-id"] = $contact["id"];
2776 $datarray["network"] = Protocol::DIASPORA;
2778 $datarray["author-link"] = $contact["url"];
2779 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2781 $datarray["owner-link"] = $datarray["author-link"];
2782 $datarray["owner-id"] = $datarray["author-id"];
2784 $datarray["guid"] = $guid;
2785 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2786 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2788 $datarray["verb"] = Activity::POST;
2789 $datarray["gravity"] = GRAVITY_PARENT;
2791 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2792 $datarray["source"] = $xml;
2794 /// @todo Copy tag data from original post
2796 $prefix = share_header(
2797 $original_item["author-name"],
2798 $original_item["author-link"],
2799 $original_item["author-avatar"],
2800 $original_item["guid"],
2801 $original_item["created"],
2805 if (!empty($original_item['title'])) {
2806 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2809 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2811 $datarray["tag"] = $original_item["tag"];
2812 $datarray["attach"] = $original_item["attach"];
2813 $datarray["app"] = $original_item["app"];
2815 $datarray["plink"] = self::plink($author, $guid);
2816 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2817 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2819 $datarray["object-type"] = $original_item["object-type"];
2821 self::fetchGuid($datarray);
2822 $message_id = Item::insert($datarray);
2824 self::sendParticipation($contact, $datarray);
2826 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2827 if ($root_message_id) {
2828 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2832 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2833 if ($datarray['uid'] == 0) {
2834 Item::distribute($message_id);
2843 * Processes retractions
2845 * @param array $importer Array of the importer user
2846 * @param array $contact The contact of the item owner
2847 * @param object $data The message object
2849 * @return bool success
2850 * @throws \Exception
2852 private static function itemRetraction(array $importer, array $contact, $data)
2854 $author = Strings::escapeTags(XML::unescape($data->author));
2855 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2856 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2858 $person = self::personByHandle($author);
2859 if (!is_array($person)) {
2860 Logger::log("unable to find author detail for ".$author);
2864 if (empty($contact["url"])) {
2865 $contact["url"] = $person["url"];
2868 // Fetch items that are about to be deleted
2869 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2871 // When we receive a public retraction, we delete every item that we find.
2872 if ($importer['uid'] == 0) {
2873 $condition = ['guid' => $target_guid, 'deleted' => false];
2875 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2878 $r = Item::select($fields, $condition);
2879 if (!DBA::isResult($r)) {
2880 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2884 while ($item = Item::fetch($r)) {
2885 if (strstr($item['file'], '[')) {
2886 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2890 // Fetch the parent item
2891 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2893 // Only delete it if the parent author really fits
2894 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2895 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2899 Item::markForDeletion(['id' => $item['id']]);
2901 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2908 * Receives retraction messages
2910 * @param array $importer Array of the importer user
2911 * @param string $sender The sender of the message
2912 * @param object $data The message object
2914 * @return bool Success
2915 * @throws \Exception
2917 private static function receiveRetraction(array $importer, $sender, $data)
2919 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2921 $contact = self::contactByHandle($importer["uid"], $sender);
2922 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2923 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2931 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2933 switch ($target_type) {
2938 case "StatusMessage":
2939 return self::itemRetraction($importer, $contact, $data);
2941 case "PollParticipation":
2943 // Currently unsupported
2947 Logger::log("Unknown target type ".$target_type);
2954 * Receives status messages
2956 * @param array $importer Array of the importer user
2957 * @param SimpleXMLElement $data The message object
2958 * @param string $xml The original XML of the message
2960 * @return int The message id of the newly created item
2961 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2962 * @throws \ImagickException
2964 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2966 $author = Strings::escapeTags(XML::unescape($data->author));
2967 $guid = Strings::escapeTags(XML::unescape($data->guid));
2968 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2969 $public = Strings::escapeTags(XML::unescape($data->public));
2970 $text = XML::unescape($data->text);
2971 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2973 $contact = self::allowedContactByHandle($importer, $author, false);
2978 $message_id = self::messageExists($importer["uid"], $guid);
2984 if ($data->location) {
2985 foreach ($data->location->children() as $fieldname => $data) {
2986 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2990 $body = Markdown::toBBCode($text);
2994 // Attach embedded pictures to the body
2996 foreach ($data->photo as $photo) {
2997 $body = "[img]".XML::unescape($photo->remote_photo_path).
2998 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
3001 $datarray["object-type"] = Activity\ObjectType::IMAGE;
3003 $datarray["object-type"] = Activity\ObjectType::NOTE;
3005 // Add OEmbed and other information to the body
3006 if (!self::isHubzilla($contact["url"])) {
3007 $body = add_page_info_to_body($body, false, true);
3011 /// @todo enable support for polls
3012 //if ($data->poll) {
3013 // foreach ($data->poll AS $poll)
3018 /// @todo enable support for events
3020 $datarray["uid"] = $importer["uid"];
3021 $datarray["contact-id"] = $contact["id"];
3022 $datarray["network"] = Protocol::DIASPORA;
3024 $datarray["author-link"] = $contact["url"];
3025 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
3027 $datarray["owner-link"] = $datarray["author-link"];
3028 $datarray["owner-id"] = $datarray["author-id"];
3030 $datarray["guid"] = $guid;
3031 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3032 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
3034 $datarray["verb"] = Activity::POST;
3035 $datarray["gravity"] = GRAVITY_PARENT;
3037 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3038 $datarray["source"] = $xml;
3040 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3042 self::storeMentions($datarray['uri-id'], $text);
3043 self::storeTags($datarray['uri-id'], $datarray["body"]);
3045 if ($provider_display_name != "") {
3046 $datarray["app"] = $provider_display_name;
3049 $datarray["plink"] = self::plink($author, $guid);
3050 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3051 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3053 if (isset($address["address"])) {
3054 $datarray["location"] = $address["address"];
3057 if (isset($address["lat"]) && isset($address["lng"])) {
3058 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3061 self::fetchGuid($datarray);
3062 $message_id = Item::insert($datarray);
3064 self::sendParticipation($contact, $datarray);
3067 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3068 if ($datarray['uid'] == 0) {
3069 Item::distribute($message_id);
3077 /* ************************************************************************************** *
3078 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3079 * ************************************************************************************** */
3082 * returnes the handle of a contact
3084 * @param array $contact contact array
3086 * @return string the handle in the format user@domain.tld
3087 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3089 private static function myHandle(array $contact)
3091 if (!empty($contact["addr"])) {
3092 return $contact["addr"];
3095 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3096 // So - just in case - we build the the address here.
3097 if ($contact["nickname"] != "") {
3098 $nick = $contact["nickname"];
3100 $nick = $contact["nick"];
3103 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3108 * Creates the data for a private message in the new format
3110 * @param string $msg The message that is to be transmitted
3111 * @param array $user The record of the sender
3112 * @param array $contact Target of the communication
3113 * @param string $prvkey The private key of the sender
3114 * @param string $pubkey The public key of the receiver
3116 * @return string The encrypted data
3117 * @throws \Exception
3119 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3121 Logger::log("Message: ".$msg, Logger::DATA);
3123 // without a public key nothing will work
3125 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3129 $aes_key = openssl_random_pseudo_bytes(32);
3130 $b_aes_key = base64_encode($aes_key);
3131 $iv = openssl_random_pseudo_bytes(16);
3132 $b_iv = base64_encode($iv);
3134 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3136 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3138 $encrypted_key_bundle = "";
3139 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3141 $json_object = json_encode(
3142 ["aes_key" => base64_encode($encrypted_key_bundle),
3143 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3146 return $json_object;
3150 * Creates the envelope for the "fetch" endpoint and for the new format
3152 * @param string $msg The message that is to be transmitted
3153 * @param array $user The record of the sender
3155 * @return string The envelope
3156 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3158 public static function buildMagicEnvelope($msg, array $user)
3160 $b64url_data = Strings::base64UrlEncode($msg);
3161 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3163 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3164 $type = "application/xml";
3165 $encoding = "base64url";
3166 $alg = "RSA-SHA256";
3167 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3169 // Fallback if the private key wasn't transmitted in the expected field
3170 if ($user['uprvkey'] == "") {
3171 $user['uprvkey'] = $user['prvkey'];
3174 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3175 $sig = Strings::base64UrlEncode($signature);
3177 $xmldata = ["me:env" => ["me:data" => $data,
3178 "@attributes" => ["type" => $type],
3179 "me:encoding" => $encoding,
3182 "@attributes2" => ["key_id" => $key_id]]];
3184 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3186 return XML::fromArray($xmldata, $xml, false, $namespaces);
3190 * Create the envelope for a message
3192 * @param string $msg The message that is to be transmitted
3193 * @param array $user The record of the sender
3194 * @param array $contact Target of the communication
3195 * @param string $prvkey The private key of the sender
3196 * @param string $pubkey The public key of the receiver
3197 * @param bool $public Is the message public?
3199 * @return string The message that will be transmitted to other servers
3200 * @throws \Exception
3202 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3204 // The message is put into an envelope with the sender's signature
3205 $envelope = self::buildMagicEnvelope($msg, $user);
3207 // Private messages are put into a second envelope, encrypted with the receivers public key
3209 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3216 * Creates a signature for a message
3218 * @param array $owner the array of the owner of the message
3219 * @param array $message The message that is to be signed
3221 * @return string The signature
3223 private static function signature($owner, $message)
3226 unset($sigmsg["author_signature"]);
3227 unset($sigmsg["parent_author_signature"]);
3229 $signed_text = implode(";", $sigmsg);
3231 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3235 * Transmit a message to a target server
3237 * @param array $owner the array of the item owner
3238 * @param array $contact Target of the communication
3239 * @param string $envelope The message that is to be transmitted
3240 * @param bool $public_batch Is it a public post?
3241 * @param string $guid message guid
3243 * @return int Result of the transmission
3244 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3245 * @throws \ImagickException
3247 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3249 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3254 $logid = Strings::getRandomHex(4);
3256 // We always try to use the data from the fcontact table.
3257 // This is important for transmitting data to Friendica servers.
3258 if (!empty($contact['addr'])) {
3259 $fcontact = self::personByHandle($contact['addr']);
3260 if (!empty($fcontact)) {
3261 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3265 if (empty($dest_url)) {
3266 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3270 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3274 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3276 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3277 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3279 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3280 $return_code = $postResult->getReturnCode();
3282 Logger::log("test_mode");
3286 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3288 return $return_code ? $return_code : -1;
3293 * Build the post xml
3295 * @param string $type The message type
3296 * @param array $message The message data
3298 * @return string The post XML
3300 public static function buildPostXml($type, $message)
3302 $data = [$type => $message];
3304 return XML::fromArray($data, $xml);
3308 * Builds and transmit messages
3310 * @param array $owner the array of the item owner
3311 * @param array $contact Target of the communication
3312 * @param string $type The message type
3313 * @param array $message The message data
3314 * @param bool $public_batch Is it a public post?
3315 * @param string $guid message guid
3317 * @return int Result of the transmission
3318 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3319 * @throws \ImagickException
3321 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3323 $msg = self::buildPostXml($type, $message);
3325 Logger::log('message: '.$msg, Logger::DATA);
3326 Logger::log('send guid '.$guid, Logger::DEBUG);
3328 // Fallback if the private key wasn't transmitted in the expected field
3329 if (empty($owner['uprvkey'])) {
3330 $owner['uprvkey'] = $owner['prvkey'];
3333 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3335 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3337 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3339 return $return_code;
3343 * sends a participation (Used to get all further updates)
3345 * @param array $contact Target of the communication
3346 * @param array $item Item array
3348 * @return int The result of the transmission
3349 * @throws \Exception
3351 private static function sendParticipation(array $contact, array $item)
3353 // Don't send notifications for private postings
3354 if ($item['private'] == Item::PRIVATE) {
3358 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3360 $result = DI::cache()->get($cachekey);
3361 if (!is_null($result)) {
3365 // Fetch some user id to have a valid handle to transmit the participation.
3366 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3367 // If the item belongs to a user, we take this user id.
3368 if ($item['uid'] == 0) {
3369 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3370 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3371 $owner = User::getOwnerDataById($first_user['uid']);
3373 $owner = User::getOwnerDataById($item['uid']);
3376 $author = self::myHandle($owner);
3378 $message = ["author" => $author,
3379 "guid" => System::createUUID(),
3380 "parent_type" => "Post",
3381 "parent_guid" => $item["guid"]];
3383 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3385 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3386 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3388 return self::buildAndTransmit($owner, $contact, "participation", $message);
3392 * sends an account migration
3394 * @param array $owner the array of the item owner
3395 * @param array $contact Target of the communication
3396 * @param int $uid User ID
3398 * @return int The result of the transmission
3399 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3400 * @throws \ImagickException
3402 public static function sendAccountMigration(array $owner, array $contact, $uid)
3404 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3405 $profile = self::createProfileData($uid);
3407 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3408 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3410 $message = ["author" => $old_handle,
3411 "profile" => $profile,
3412 "signature" => $signature];
3414 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3416 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3420 * Sends a "share" message
3422 * @param array $owner the array of the item owner
3423 * @param array $contact Target of the communication
3425 * @return int The result of the transmission
3426 * @throws \Exception
3428 public static function sendShare(array $owner, array $contact)
3431 * @todo support the different possible combinations of "following" and "sharing"
3432 * Currently, Diaspora only interprets the "sharing" field
3434 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3438 switch ($contact["rel"]) {
3439 case Contact::FRIEND:
3443 case Contact::SHARING:
3447 case Contact::FOLLOWER:
3453 $message = ["author" => self::myHandle($owner),
3454 "recipient" => $contact["addr"],
3455 "following" => "true",
3456 "sharing" => "true"];
3458 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3460 return self::buildAndTransmit($owner, $contact, "contact", $message);
3464 * sends an "unshare"
3466 * @param array $owner the array of the item owner
3467 * @param array $contact Target of the communication
3469 * @return int The result of the transmission
3470 * @throws \Exception
3472 public static function sendUnshare(array $owner, array $contact)
3474 $message = ["author" => self::myHandle($owner),
3475 "recipient" => $contact["addr"],
3476 "following" => "false",
3477 "sharing" => "false"];
3479 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3481 return self::buildAndTransmit($owner, $contact, "contact", $message);
3485 * Checks a message body if it is a reshare
3487 * @param string $body The message body that is to be check
3488 * @param bool $complete Should it be a complete check or a simple check?
3490 * @return array|bool Reshare details or "false" if no reshare
3491 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3492 * @throws \ImagickException
3494 public static function isReshare($body, $complete = true)
3496 $body = trim($body);
3498 $reshared = Item::getShareArray(['body' => $body]);
3499 if (empty($reshared)) {
3503 // Skip if it isn't a pure repeated messages
3504 // Does it start with a share?
3505 if (!empty($reshared['comment']) && $complete) {
3509 if (!empty($reshared['guid']) && $complete) {
3510 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3511 $item = Item::selectFirst(['contact-id'], $condition);
3512 if (DBA::isResult($item)) {
3514 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3515 $ret["root_guid"] = $reshared['guid'];
3517 } elseif ($complete) {
3518 // We are resharing something that isn't a DFRN or Diaspora post.
3519 // So we have to return "false" on "$complete" to not trigger a reshare.
3522 } elseif (empty($reshared['guid']) && $complete) {
3528 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3529 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3530 if (!empty($contact['addr'])) {
3531 $ret['root_handle'] = $contact['addr'];
3535 if (empty($ret) && !$complete) {
3543 * Create an event array
3545 * @param integer $event_id The id of the event
3547 * @return array with event data
3548 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3550 private static function buildEvent($event_id)
3552 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3553 if (!DBA::isResult($r)) {
3561 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3562 if (!DBA::isResult($r)) {
3568 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3569 if (!DBA::isResult($r)) {
3575 $eventdata['author'] = self::myHandle($owner);
3577 if ($event['guid']) {
3578 $eventdata['guid'] = $event['guid'];
3581 $mask = DateTimeFormat::ATOM;
3583 /// @todo - establish "all day" events in Friendica
3584 $eventdata["all_day"] = "false";
3586 $eventdata['timezone'] = 'UTC';
3587 if (!$event['adjust'] && $user['timezone']) {
3588 $eventdata['timezone'] = $user['timezone'];
3591 if ($event['start']) {
3592 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3594 if ($event['finish'] && !$event['nofinish']) {
3595 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3597 if ($event['summary']) {
3598 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3600 if ($event['desc']) {
3601 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3603 if ($event['location']) {
3604 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3605 $coord = Map::getCoordinates($event['location']);
3608 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3609 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3610 $location["lat"] = $coord['lat'];
3611 $location["lng"] = $coord['lon'];
3613 $location["lat"] = 0;
3614 $location["lng"] = 0;
3616 $eventdata['location'] = $location;
3623 * Create a post (status message or reshare)
3625 * @param array $item The item that will be exported
3626 * @param array $owner the array of the item owner
3629 * 'type' -> Message type ("status_message" or "reshare")
3630 * 'message' -> Array of XML elements of the status
3631 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3632 * @throws \ImagickException
3634 public static function buildStatus(array $item, array $owner)
3636 $cachekey = "diaspora:buildStatus:".$item['guid'];
3638 $result = DI::cache()->get($cachekey);
3639 if (!is_null($result)) {
3643 $myaddr = self::myHandle($owner);
3645 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3646 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3647 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3649 // Detect a share element and do a reshare
3650 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3651 $message = ["author" => $myaddr,
3652 "guid" => $item["guid"],
3653 "created_at" => $created,
3654 "root_author" => $ret["root_handle"],
3655 "root_guid" => $ret["root_guid"],
3656 "provider_display_name" => $item["app"],
3657 "public" => $public];
3661 $title = $item["title"];
3662 $body = $item["body"];
3664 // Fetch the title from an attached link - if there is one
3665 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3666 $page_data = BBCode::getAttachmentData($item['body']);
3667 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3668 $title = $page_data['title'];
3672 if ($item['author-link'] != $item['owner-link']) {
3673 require_once 'mod/share.php';
3674 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3675 "", $item['created'], $item['plink']) . $body . '[/share]';
3678 // convert to markdown
3679 $body = html_entity_decode(BBCode::toMarkdown($body));
3682 if (strlen($title)) {
3683 $body = "### ".html_entity_decode($title)."\n\n".$body;
3686 if ($item["attach"]) {
3687 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3689 $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3690 foreach ($matches as $mtch) {
3691 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3698 if ($item["location"] != "")
3699 $location["address"] = $item["location"];
3701 if ($item["coord"] != "") {
3702 $coord = explode(" ", $item["coord"]);
3703 $location["lat"] = $coord[0];
3704 $location["lng"] = $coord[1];
3707 $message = ["author" => $myaddr,
3708 "guid" => $item["guid"],
3709 "created_at" => $created,
3710 "edited_at" => $edited,
3711 "public" => $public,
3713 "provider_display_name" => $item["app"],
3714 "location" => $location];
3716 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3717 if (!isset($location["lat"]) || !isset($location["lng"])) {
3718 unset($message["location"]);
3721 if ($item['event-id'] > 0) {
3722 $event = self::buildEvent($item['event-id']);
3723 if (count($event)) {
3724 $message['event'] = $event;
3726 if (!empty($event['location']['address']) &&
3727 !empty($event['location']['lat']) &&
3728 !empty($event['location']['lng'])) {
3729 $message['location'] = $event['location'];
3732 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3733 // $message['text'] = '';
3737 $type = "status_message";
3740 $msg = ["type" => $type, "message" => $message];
3742 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3747 private static function prependParentAuthorMention($body, $profile_url)
3749 $profile = Contact::getDetailsByURL($profile_url);
3750 if (!empty($profile['addr'])
3751 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3752 && !strstr($body, $profile['addr'])
3753 && !strstr($body, $profile_url)
3755 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3764 * @param array $item The item that will be exported
3765 * @param array $owner the array of the item owner
3766 * @param array $contact Target of the communication
3767 * @param bool $public_batch Is it a public post?
3769 * @return int The result of the transmission
3770 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3771 * @throws \ImagickException
3773 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3775 $status = self::buildStatus($item, $owner);
3777 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3781 * Creates a "like" object
3783 * @param array $item The item that will be exported
3784 * @param array $owner the array of the item owner
3786 * @return array The data for a "like"
3787 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3789 private static function constructLike(array $item, array $owner)
3791 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3792 if (!DBA::isResult($parent)) {
3796 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3798 if ($item['verb'] === Activity::LIKE) {
3800 } elseif ($item['verb'] === Activity::DISLIKE) {
3801 $positive = "false";
3804 return(["author" => self::myHandle($owner),
3805 "guid" => $item["guid"],
3806 "parent_guid" => $parent["guid"],
3807 "parent_type" => $target_type,
3808 "positive" => $positive,
3809 "author_signature" => ""]);
3813 * Creates an "EventParticipation" object
3815 * @param array $item The item that will be exported
3816 * @param array $owner the array of the item owner
3818 * @return array The data for an "EventParticipation"
3819 * @throws \Exception
3821 private static function constructAttend(array $item, array $owner)
3823 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3824 if (!DBA::isResult($parent)) {
3828 switch ($item['verb']) {
3829 case Activity::ATTEND:
3830 $attend_answer = 'accepted';
3832 case Activity::ATTENDNO:
3833 $attend_answer = 'declined';
3835 case Activity::ATTENDMAYBE:
3836 $attend_answer = 'tentative';
3839 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3843 return(["author" => self::myHandle($owner),
3844 "guid" => $item["guid"],
3845 "parent_guid" => $parent["guid"],
3846 "status" => $attend_answer,
3847 "author_signature" => ""]);
3851 * Creates the object for a comment
3853 * @param array $item The item that will be exported
3854 * @param array $owner the array of the item owner
3856 * @return array|false The data for a comment
3857 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3859 private static function constructComment(array $item, array $owner)
3861 $cachekey = "diaspora:constructComment:".$item['guid'];
3863 $result = DI::cache()->get($cachekey);
3864 if (!is_null($result)) {
3868 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3869 if (!DBA::isResult($toplevel_item)) {
3870 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3874 $thread_parent_item = $toplevel_item;
3875 if ($item['thr-parent'] != $item['parent-uri']) {
3876 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3879 $body = $item["body"];
3881 // The replied to autor mention is prepended for clarity if:
3882 // - Item replied isn't yours
3883 // - Item is public or explicit mentions are disabled
3884 // - Implicit mentions are enabled
3886 $item['author-id'] != $thread_parent_item['author-id']
3887 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3888 && !DI::config()->get('system', 'disable_implicit_mentions')
3890 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3893 $text = html_entity_decode(BBCode::toMarkdown($body));
3894 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3895 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3898 "author" => self::myHandle($owner),
3899 "guid" => $item["guid"],
3900 "created_at" => $created,
3901 "edited_at" => $edited,
3902 "parent_guid" => $toplevel_item["guid"],
3904 "author_signature" => ""
3907 // Send the thread parent guid only if it is a threaded comment
3908 if ($item['thr-parent'] != $item['parent-uri']) {
3909 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3912 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3918 * Send a like or a comment
3920 * @param array $item The item that will be exported
3921 * @param array $owner the array of the item owner
3922 * @param array $contact Target of the communication
3923 * @param bool $public_batch Is it a public post?
3925 * @return int The result of the transmission
3926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3927 * @throws \ImagickException
3929 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3931 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3932 $message = self::constructAttend($item, $owner);
3933 $type = "event_participation";
3934 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3935 $message = self::constructLike($item, $owner);
3937 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3938 $message = self::constructComment($item, $owner);
3942 if (empty($message)) {
3946 $message["author_signature"] = self::signature($owner, $message);
3948 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3952 * Creates a message from a signature record entry
3954 * @param array $item The item that will be exported
3955 * @return array The message
3957 private static function messageFromSignature(array $item)
3959 // Split the signed text
3960 $signed_parts = explode(";", $item['signed_text']);
3962 if ($item["deleted"]) {
3963 $message = ["author" => $item['signer'],
3964 "target_guid" => $signed_parts[0],
3965 "target_type" => $signed_parts[1]];
3966 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3967 $message = ["author" => $signed_parts[4],
3968 "guid" => $signed_parts[1],
3969 "parent_guid" => $signed_parts[3],
3970 "parent_type" => $signed_parts[2],
3971 "positive" => $signed_parts[0],
3972 "author_signature" => $item['signature'],
3973 "parent_author_signature" => ""];
3975 // Remove the comment guid
3976 $guid = array_shift($signed_parts);
3978 // Remove the parent guid
3979 $parent_guid = array_shift($signed_parts);
3981 // Remove the handle
3982 $handle = array_pop($signed_parts);
3985 "author" => $handle,
3987 "parent_guid" => $parent_guid,
3988 "text" => implode(";", $signed_parts),
3989 "author_signature" => $item['signature'],
3990 "parent_author_signature" => ""
3997 * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3999 * @param array $item The item that will be exported
4000 * @param array $owner the array of the item owner
4001 * @param array $contact Target of the communication
4002 * @param bool $public_batch Is it a public post?
4004 * @return int The result of the transmission
4005 * @throws \Exception
4007 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
4009 if ($item["deleted"]) {
4010 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
4011 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4017 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
4019 $msg = json_decode($item['signed_text'], true);
4022 if (is_array($msg)) {
4023 foreach ($msg as $field => $data) {
4024 if (!$item["deleted"]) {
4025 if ($field == "diaspora_handle") {
4028 if ($field == "target_type") {
4029 $field = "parent_type";
4033 $message[$field] = $data;
4036 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4039 $message["parent_author_signature"] = self::signature($owner, $message);
4041 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4043 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4047 * Sends a retraction (deletion) of a message, like or comment
4049 * @param array $item The item that will be exported
4050 * @param array $owner the array of the item owner
4051 * @param array $contact Target of the communication
4052 * @param bool $public_batch Is it a public post?
4053 * @param bool $relay Is the retraction transmitted from a relay?
4055 * @return int The result of the transmission
4056 * @throws \Exception
4058 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4060 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4062 $msg_type = "retraction";
4064 if ($item['id'] == $item['parent']) {
4065 $target_type = "Post";
4066 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4067 $target_type = "Like";
4069 $target_type = "Comment";
4072 $message = ["author" => $itemaddr,
4073 "target_guid" => $item['guid'],
4074 "target_type" => $target_type];
4076 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4078 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4084 * @param array $item The item that will be exported
4085 * @param array $owner The owner
4086 * @param array $contact Target of the communication
4088 * @return int The result of the transmission
4089 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4090 * @throws \ImagickException
4092 public static function sendMail(array $item, array $owner, array $contact)
4094 $myaddr = self::myHandle($owner);
4096 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4097 if (!DBA::isResult($cnv)) {
4098 Logger::log("conversation not found.");
4102 $body = BBCode::toMarkdown($item["body"]);
4103 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4106 "author" => $myaddr,
4107 "guid" => $item["guid"],
4108 "conversation_guid" => $cnv["guid"],
4110 "created_at" => $created,
4113 if ($item["reply"]) {
4118 "author" => $cnv["creator"],
4119 "guid" => $cnv["guid"],
4120 "subject" => $cnv["subject"],
4121 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4122 "participants" => $cnv["recips"],
4126 $type = "conversation";
4129 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4133 * Split a name into first name and last name
4135 * @param string $name The name
4137 * @return array The array with "first" and "last"
4139 public static function splitName($name) {
4140 $name = trim($name);
4142 // Is the name longer than 64 characters? Then cut the rest of it.
4143 if (strlen($name) > 64) {
4144 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4145 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4147 $name = substr($name, 0, 64);
4151 // Take the first word as first name
4152 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4153 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4154 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4155 return ['first' => $first, 'last' => $last];
4158 // Take the last word as last name
4159 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4160 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4162 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4163 return ['first' => $first, 'last' => $last];
4166 // Take the first 32 characters if there is no space in the first 32 characters
4167 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4168 $first = substr($name, 0, 32);
4169 $last = substr($name, 32);
4170 return ['first' => $first, 'last' => $last];
4173 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4174 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4176 // Check if the last name is longer than 32 characters
4177 if (strlen($last) > 32) {
4178 if (strpos($last, ' ') <= 32) {
4179 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4181 $last = substr($last, 0, 32);
4185 return ['first' => $first, 'last' => $last];
4189 * Create profile data
4191 * @param int $uid The user id
4193 * @return array The profile data
4194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4196 private static function createProfileData($uid)
4199 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4201 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4202 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4203 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
4212 $handle = $profile["addr"];
4214 $split_name = self::splitName($profile['name']);
4215 $first = $split_name['first'];
4216 $last = $split_name['last'];
4218 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4219 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4220 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4221 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4227 if ($searchable === 'true') {
4230 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4231 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4235 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4238 $about = BBCode::toMarkdown($profile['about']);
4240 $location = Profile::formatLocation($profile);
4242 if ($profile['pub_keywords']) {
4243 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4244 $kw = str_replace(' ', ' ', $kw);
4245 $arr = explode(' ', $kw);
4247 for ($x = 0; $x < 5; $x ++) {
4248 if (!empty($arr[$x])) {
4249 $tags .= '#'. trim($arr[$x]) .' ';
4254 $tags = trim($tags);
4257 return ["author" => $handle,
4258 "first_name" => $first,
4259 "last_name" => $last,
4260 "image_url" => $large,
4261 "image_url_medium" => $medium,
4262 "image_url_small" => $small,
4265 "location" => $location,
4266 "searchable" => $searchable,
4268 "tag_string" => $tags];
4272 * Sends profile data
4274 * @param int $uid The user id
4275 * @param bool $recips optional, default false
4277 * @throws \Exception
4279 public static function sendProfile($uid, $recips = false)
4285 $owner = User::getOwnerDataById($uid);
4292 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4293 AND `uid` = %d AND `rel` != %d",
4294 DBA::escape(Protocol::DIASPORA),
4296 intval(Contact::SHARING)
4304 $message = self::createProfileData($uid);
4306 // @ToDo Split this into single worker jobs
4307 foreach ($recips as $recip) {
4308 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4309 self::buildAndTransmit($owner, $recip, "profile", $message);
4314 * Creates the signature for likes that are created on our system
4316 * @param integer $uid The user of that comment
4317 * @param array $item Item array
4319 * @return array Signed content
4320 * @throws \Exception
4322 public static function createLikeSignature($uid, array $item)
4324 $owner = User::getOwnerDataById($uid);
4325 if (empty($owner)) {
4326 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4330 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4334 $message = self::constructLike($item, $owner);
4335 if ($message === false) {
4339 $message["author_signature"] = self::signature($owner, $message);
4345 * Creates the signature for Comments that are created on our system
4347 * @param integer $uid The user of that comment
4348 * @param array $item Item array
4350 * @return array Signed content
4351 * @throws \Exception
4353 public static function createCommentSignature($uid, array $item)
4355 $owner = User::getOwnerDataById($uid);
4356 if (empty($owner)) {
4357 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4361 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4362 $item['thr-parent'] = $item['parent-uri'];
4364 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4365 if (!DBA::isResult($parent)) {
4369 $item['parent-uri'] = $parent['parent-uri'];
4371 $message = self::constructComment($item, $owner);
4372 if ($message === false) {
4376 $message["author_signature"] = self::signature($owner, $message);