3 * @file src/Protocol/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "validPosting" and interpret only the new protocol.
11 namespace Friendica\Protocol;
13 use Friendica\Content\Feature;
14 use Friendica\Content\Text\BBCode;
15 use Friendica\Content\Text\Markdown;
16 use Friendica\Core\Cache\Duration;
17 use Friendica\Core\Config;
18 use Friendica\Core\L10n;
19 use Friendica\Core\Logger;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\System;
22 use Friendica\Core\Worker;
23 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Conversation;
27 use Friendica\Model\GContact;
28 use Friendica\Model\Item;
29 use Friendica\Model\ItemDeliveryData;
30 use Friendica\Model\Mail;
31 use Friendica\Model\Profile;
32 use Friendica\Model\User;
33 use Friendica\Network\Probe;
34 use Friendica\Util\Crypto;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Map;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
39 use Friendica\Util\XML;
40 use Friendica\Worker\Delivery;
44 * @brief This class contain functions to create and send Diaspora XML files
50 * Mark the relay contact of the given contact for archival
51 * This is called whenever there is a communication issue with the server.
52 * It avoids sending stuff to servers who don't exist anymore.
53 * The relay contact is a technical contact entry that exists once per server.
55 * @param array $contact of the relay contact
57 public static function markRelayForArchival(array $contact)
59 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
60 // This is already the relay contact, we don't need to fetch it
61 $relay_contact = $contact;
62 } elseif (empty($contact['baseurl'])) {
63 if (!empty($contact['batch'])) {
64 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
65 $relay_contact = DBA::selectFirst('contact', [], $condition);
70 $relay_contact = self::getRelayContact($contact['baseurl'], []);
73 if (!empty($relay_contact)) {
74 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
75 Contact::markForArchival($relay_contact);
80 * @brief Return a list of relay servers
82 * The list contains not only the official relays but also servers that we serve directly
84 * @param integer $item_id The id of the item that is sent
85 * @param array $contacts The previously fetched contacts
87 * @return array of relay servers
88 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
90 public static function relayList($item_id, array $contacts = [])
94 // Fetching relay servers
95 $serverdata = Config::get("system", "relay_server");
97 if (!empty($serverdata)) {
98 $servers = explode(",", $serverdata);
99 foreach ($servers as $server) {
100 $serverlist[$server] = trim($server);
104 if (Config::get("system", "relay_directly", false)) {
105 // We distribute our stuff based on the parent to ensure that the thread will be complete
106 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
107 if (!DBA::isResult($parent)) {
111 // Servers that want to get all content
112 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
113 while ($server = DBA::fetch($servers)) {
114 $serverlist[$server['url']] = $server['url'];
117 // All tags of the current post
118 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
119 $tags = DBA::select('term', ['term'], $condition);
121 while ($tag = DBA::fetch($tags)) {
122 $taglist[] = $tag['term'];
125 // All servers who wants content with this tag
127 if (!empty($taglist)) {
128 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
129 while ($server = DBA::fetch($tagserver)) {
130 $tagserverlist[] = $server['gserver-id'];
134 // All adresses with the given id
135 if (!empty($tagserverlist)) {
136 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
137 while ($server = DBA::fetch($servers)) {
138 $serverlist[$server['url']] = $server['url'];
143 // Now we are collecting all relay contacts
144 foreach ($serverlist as $server_url) {
145 // We don't send messages to ourselves
146 if (Strings::compareLink($server_url, DI::baseUrl())) {
149 $contact = self::getRelayContact($server_url);
150 if (is_bool($contact)) {
155 foreach ($contacts as $entry) {
156 if ($entry['batch'] == $contact['batch']) {
162 $contacts[] = $contact;
170 * @brief Return a contact for a given server address or creates a dummy entry
172 * @param string $server_url The url of the server
173 * @param array $fields Fieldlist
174 * @return array with the contact
177 private static function getRelayContact(string $server_url, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
179 // Fetch the relay contact
180 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
181 'contact-type' => Contact::TYPE_RELAY];
182 $contact = DBA::selectFirst('contact', $fields, $condition);
184 if (DBA::isResult($contact)) {
185 if ($contact['archive'] || $contact['blocked']) {
190 self::setRelayContact($server_url);
192 $contact = DBA::selectFirst('contact', $fields, $condition);
193 if (DBA::isResult($contact)) {
198 // It should never happen that we arrive here
203 * @brief Update or insert a relay contact
205 * @param string $server_url The url of the server
206 * @param array $network_fields Optional network specific fields
209 public static function setRelayContact($server_url, array $network_fields = [])
211 $fields = ['created' => DateTimeFormat::utcNow(),
212 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
213 'nurl' => Strings::normaliseLink($server_url),
214 'network' => Protocol::DIASPORA, 'uid' => 0,
215 'batch' => $server_url . '/receive/public',
216 'rel' => Contact::FOLLOWER, 'blocked' => false,
217 'pending' => false, 'writable' => true,
218 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
220 $fields = array_merge($fields, $network_fields);
222 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
223 $old = DBA::selectFirst('contact', [], $condition);
224 if (DBA::isResult($old)) {
225 unset($fields['created']);
226 $condition = ['id' => $old['id']];
228 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
229 DBA::update('contact', $fields, $condition, $old);
231 Logger::info('Create relay contact', ['fields' => $fields]);
232 Contact::insert($fields);
237 * @brief Return a list of participating contacts for a thread
239 * This is used for the participation feature.
240 * One of the parameters is a contact array.
241 * This is done to avoid duplicates.
243 * @param integer $thread The id of the thread
244 * @param array $contacts The previously fetched contacts
246 * @return array of relay servers
249 public static function participantsForThread($thread, array $contacts)
251 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`url`, `contact`.`name`, `contact`.`network`, `contact`.`protocol`,
252 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
253 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
254 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
255 WHERE `participation`.`iid` = ? AND NOT `contact`.`archive`", $thread);
257 while ($contact = DBA::fetch($r)) {
258 if (!empty($contact['fnetwork'])) {
259 $contact['network'] = $contact['fnetwork'];
261 unset($contact['fnetwork']);
263 if (empty($contact['protocol'])) {
264 $contact['protocol'] = $contact['network'];
267 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
268 $contact['batch'] = $contact['fbatch'];
270 unset($contact['fbatch']);
273 foreach ($contacts as $entry) {
274 if ($entry['batch'] == $contact['batch']) {
280 $contacts[] = $contact;
289 * @brief repairs a signature that was double encoded
291 * The function is unused at the moment. It was copied from the old implementation.
293 * @param string $signature The signature
294 * @param string $handle The handle of the signature owner
295 * @param integer $level This value is only set inside this function to avoid endless loops
297 * @return string the repaired signature
300 private static function repairSignature($signature, $handle = "", $level = 1)
302 if ($signature == "") {
306 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
307 $signature = base64_decode($signature);
308 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
310 // Do a recursive call to be able to fix even multiple levels
312 $signature = self::repairSignature($signature, $handle, ++$level);
320 * @brief verify the envelope and return the verified data
322 * @param string $envelope The magic envelope
324 * @return string verified data
325 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
326 * @throws \ImagickException
328 private static function verifyMagicEnvelope($envelope)
330 $basedom = XML::parseString($envelope);
332 if (!is_object($basedom)) {
333 Logger::log("Envelope is no XML file");
337 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
339 if (sizeof($children) == 0) {
340 Logger::log("XML has no children");
346 $data = Strings::base64UrlDecode($children->data);
347 $type = $children->data->attributes()->type[0];
349 $encoding = $children->encoding;
351 $alg = $children->alg;
353 $sig = Strings::base64UrlDecode($children->sig);
354 $key_id = $children->sig->attributes()->key_id[0];
356 $handle = Strings::base64UrlDecode($key_id);
359 $b64url_data = Strings::base64UrlEncode($data);
360 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
362 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
365 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
369 $key = self::key($handle);
371 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
375 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
377 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
385 * @brief encrypts data via AES
387 * @param string $key The AES key
388 * @param string $iv The IV (is used for CBC encoding)
389 * @param string $data The data that is to be encrypted
391 * @return string encrypted data
393 private static function aesEncrypt($key, $iv, $data)
395 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
399 * @brief decrypts data via AES
401 * @param string $key The AES key
402 * @param string $iv The IV (is used for CBC encoding)
403 * @param string $encrypted The encrypted data
405 * @return string decrypted data
407 private static function aesDecrypt($key, $iv, $encrypted)
409 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
413 * @brief: Decodes incoming Diaspora message in the new format
415 * @param string $raw raw post message
416 * @param string $privKey The private key of the importer
417 * @param boolean $no_exit Don't do an http exit on error
420 * 'message' -> decoded Diaspora XML message
421 * 'author' -> author diaspora handle
422 * 'key' -> author public key (converted to pkcs#8)
423 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
424 * @throws \ImagickException
426 public static function decodeRaw(string $raw, string $privKey = '', bool $no_exit = false)
428 $data = json_decode($raw);
430 // Is it a private post? Then decrypt the outer Salmon
431 if (is_object($data)) {
432 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
433 $ciphertext = base64_decode($data->encrypted_magic_envelope);
435 $outer_key_bundle = '';
436 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
437 $j_outer_key_bundle = json_decode($outer_key_bundle);
439 if (!is_object($j_outer_key_bundle)) {
440 Logger::log('Outer Salmon did not verify. Discarding.');
444 throw new \Friendica\Network\HTTPException\BadRequestException();
448 $outer_iv = base64_decode($j_outer_key_bundle->iv);
449 $outer_key = base64_decode($j_outer_key_bundle->key);
451 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
456 $basedom = XML::parseString($xml);
458 if (!is_object($basedom)) {
459 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
463 throw new \Friendica\Network\HTTPException\BadRequestException();
467 $base = $basedom->children(ActivityNamespace::SALMON_ME);
469 // Not sure if this cleaning is needed
470 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
472 // Build the signed data
473 $type = $base->data[0]->attributes()->type[0];
474 $encoding = $base->encoding;
476 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
478 // This is the signature
479 $signature = Strings::base64UrlDecode($base->sig);
481 // Get the senders' public key
482 $key_id = $base->sig[0]->attributes()->key_id[0];
483 $author_addr = base64_decode($key_id);
484 if ($author_addr == '') {
485 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
489 throw new \Friendica\Network\HTTPException\BadRequestException();
493 $key = self::key($author_addr);
495 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
499 throw new \Friendica\Network\HTTPException\BadRequestException();
503 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
505 Logger::log('Message did not verify. Discarding.');
509 throw new \Friendica\Network\HTTPException\BadRequestException();
513 return ['message' => (string)Strings::base64UrlDecode($base->data),
514 'author' => XML::unescape($author_addr),
515 'key' => (string)$key];
519 * @brief: Decodes incoming Diaspora message in the deprecated format
521 * @param string $xml urldecoded Diaspora salmon
522 * @param string $privKey The private key of the importer
525 * 'message' -> decoded Diaspora XML message
526 * 'author' -> author diaspora handle
527 * 'key' -> author public key (converted to pkcs#8)
528 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
529 * @throws \ImagickException
531 public static function decode(string $xml, string $privKey = '')
534 $basedom = XML::parseString($xml);
536 if (!is_object($basedom)) {
537 Logger::log("XML is not parseable.");
540 $children = $basedom->children('https://joindiaspora.com/protocol');
542 $inner_aes_key = null;
545 if ($children->header) {
547 $author_link = str_replace('acct:', '', $children->header->author_id);
549 // This happens with posts from a relais
550 if (empty($privKey)) {
551 Logger::log("This is no private post in the old format", Logger::DEBUG);
555 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
557 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
558 $ciphertext = base64_decode($encrypted_header->ciphertext);
560 $outer_key_bundle = '';
561 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
563 $j_outer_key_bundle = json_decode($outer_key_bundle);
565 $outer_iv = base64_decode($j_outer_key_bundle->iv);
566 $outer_key = base64_decode($j_outer_key_bundle->key);
568 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
570 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
571 $idom = XML::parseString($decrypted);
573 $inner_iv = base64_decode($idom->iv);
574 $inner_aes_key = base64_decode($idom->aes_key);
576 $author_link = str_replace('acct:', '', $idom->author_id);
579 $dom = $basedom->children(ActivityNamespace::SALMON_ME);
581 // figure out where in the DOM tree our data is hiding
584 if ($dom->provenance->data) {
585 $base = $dom->provenance;
586 } elseif ($dom->env->data) {
588 } elseif ($dom->data) {
593 Logger::log('unable to locate salmon data in xml');
594 throw new \Friendica\Network\HTTPException\BadRequestException();
598 // Stash the signature away for now. We have to find their key or it won't be good for anything.
599 $signature = Strings::base64UrlDecode($base->sig);
603 // strip whitespace so our data element will return to one big base64 blob
604 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
607 // stash away some other stuff for later
609 $type = $base->data[0]->attributes()->type[0];
610 $keyhash = $base->sig[0]->attributes()->keyhash[0];
611 $encoding = $base->encoding;
615 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
619 $data = Strings::base64UrlDecode($data);
623 $inner_decrypted = $data;
625 // Decode the encrypted blob
626 $inner_encrypted = base64_decode($data);
627 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
631 Logger::log('Could not retrieve author URI.');
632 throw new \Friendica\Network\HTTPException\BadRequestException();
634 // Once we have the author URI, go to the web and try to find their public key
635 // (first this will look it up locally if it is in the fcontact cache)
636 // This will also convert diaspora public key from pkcs#1 to pkcs#8
638 Logger::log('Fetching key for '.$author_link);
639 $key = self::key($author_link);
642 Logger::log('Could not retrieve author key.');
643 throw new \Friendica\Network\HTTPException\BadRequestException();
646 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
649 Logger::log('Message did not verify. Discarding.');
650 throw new \Friendica\Network\HTTPException\BadRequestException();
653 Logger::log('Message verified.');
655 return ['message' => (string)$inner_decrypted,
656 'author' => XML::unescape($author_link),
657 'key' => (string)$key];
662 * @brief Dispatches public messages and find the fitting receivers
664 * @param array $msg The post that will be dispatched
666 * @return int The message id of the generated message, "true" or "false" if there was an error
667 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
668 * @throws \ImagickException
670 public static function dispatchPublic($msg)
672 $enabled = intval(Config::get("system", "diaspora_enabled"));
674 Logger::log("diaspora is disabled");
678 if (!($fields = self::validPosting($msg))) {
679 Logger::log("Invalid posting");
683 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
684 $success = self::dispatch($importer, $msg, $fields);
690 * @brief Dispatches the different message types to the different functions
692 * @param array $importer Array of the importer user
693 * @param array $msg The post that will be dispatched
694 * @param SimpleXMLElement $fields SimpleXML object that contains the message
696 * @return int The message id of the generated message, "true" or "false" if there was an error
697 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
698 * @throws \ImagickException
700 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
702 // The sender is the handle of the contact that sent the message.
703 // This will often be different with relayed messages (for example "like" and "comment")
704 $sender = $msg["author"];
706 // This is only needed for private postings since this is already done for public ones before
707 if (is_null($fields)) {
709 if (!($fields = self::validPosting($msg))) {
710 Logger::log("Invalid posting");
717 $type = $fields->getName();
719 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
722 case "account_migration":
724 Logger::log('Message with type ' . $type . ' is not private, quitting.');
727 return self::receiveAccountMigration($importer, $fields);
729 case "account_deletion":
730 return self::receiveAccountDeletion($fields);
733 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
737 Logger::log('Message with type ' . $type . ' is not private, quitting.');
740 return self::receiveContactRequest($importer, $fields);
744 Logger::log('Message with type ' . $type . ' is not private, quitting.');
747 return self::receiveConversation($importer, $msg, $fields);
750 return self::receiveLike($importer, $sender, $fields);
754 Logger::log('Message with type ' . $type . ' is not private, quitting.');
757 return self::receiveMessage($importer, $fields);
759 case "participation":
761 Logger::log('Message with type ' . $type . ' is not private, quitting.');
764 return self::receiveParticipation($importer, $fields);
766 case "photo": // Not implemented
767 return self::receivePhoto($importer, $fields);
769 case "poll_participation": // Not implemented
770 return self::receivePollParticipation($importer, $fields);
774 Logger::log('Message with type ' . $type . ' is not private, quitting.');
777 return self::receiveProfile($importer, $fields);
780 return self::receiveReshare($importer, $fields, $msg["message"]);
783 return self::receiveRetraction($importer, $sender, $fields);
785 case "status_message":
786 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
789 Logger::log("Unknown message type ".$type);
795 * @brief Checks if a posting is valid and fetches the data fields.
797 * This function does not only check the signature.
798 * It also does the conversion between the old and the new diaspora format.
800 * @param array $msg Array with the XML, the sender handle and the sender signature
802 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
803 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
804 * @throws \ImagickException
806 private static function validPosting($msg)
808 $data = XML::parseString($msg["message"]);
810 if (!is_object($data)) {
811 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
815 // Is this the new or the old version?
816 if ($data->getName() == "XML") {
818 foreach ($data->post->children() as $child) {
826 $type = $element->getName();
829 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
831 // All retractions are handled identically from now on.
832 // In the new version there will only be "retraction".
833 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
834 $type = "retraction";
836 if ($type == "request") {
840 $fields = new SimpleXMLElement("<".$type."/>");
843 $author_signature = null;
844 $parent_author_signature = null;
846 foreach ($element->children() as $fieldname => $entry) {
848 // Translation for the old XML structure
849 if ($fieldname == "diaspora_handle") {
850 $fieldname = "author";
852 if ($fieldname == "participant_handles") {
853 $fieldname = "participants";
855 if (in_array($type, ["like", "participation"])) {
856 if ($fieldname == "target_type") {
857 $fieldname = "parent_type";
860 if ($fieldname == "sender_handle") {
861 $fieldname = "author";
863 if ($fieldname == "recipient_handle") {
864 $fieldname = "recipient";
866 if ($fieldname == "root_diaspora_id") {
867 $fieldname = "root_author";
869 if ($type == "status_message") {
870 if ($fieldname == "raw_message") {
874 if ($type == "retraction") {
875 if ($fieldname == "post_guid") {
876 $fieldname = "target_guid";
878 if ($fieldname == "type") {
879 $fieldname = "target_type";
884 if (($fieldname == "author_signature") && ($entry != "")) {
885 $author_signature = base64_decode($entry);
886 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
887 $parent_author_signature = base64_decode($entry);
888 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
889 if ($signed_data != "") {
893 $signed_data .= $entry;
895 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
896 || ($orig_type == "relayable_retraction")
898 XML::copy($entry, $fields, $fieldname);
902 // This is something that shouldn't happen at all.
903 if (in_array($type, ["status_message", "reshare", "profile"])) {
904 if ($msg["author"] != $fields->author) {
905 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
910 // Only some message types have signatures. So we quit here for the other types.
911 if (!in_array($type, ["comment", "like"])) {
914 // No author_signature? This is a must, so we quit.
915 if (!isset($author_signature)) {
916 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
920 if (isset($parent_author_signature)) {
921 $key = self::key($msg["author"]);
923 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
927 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
928 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);
933 $key = self::key($fields->author);
935 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
939 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
940 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);
948 * @brief Fetches the public key for a given handle
950 * @param string $handle The handle
952 * @return string The public key
953 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
954 * @throws \ImagickException
956 private static function key($handle)
958 $handle = strval($handle);
960 Logger::log("Fetching diaspora key for: ".$handle);
962 $r = self::personByHandle($handle);
971 * @brief Fetches data for a given handle
973 * @param string $handle The handle
974 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
976 * @return array the queried data
977 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
978 * @throws \ImagickException
980 public static function personByHandle($handle, $update = null)
982 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
983 if (!DBA::isResult($person)) {
984 $urls = [$handle, str_replace('http://', 'https://', $handle), Strings::normaliseLink($handle)];
985 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'url' => $urls]);
988 if (DBA::isResult($person)) {
989 Logger::debug("In cache " . print_r($person, true));
991 if (is_null($update)) {
992 // update record occasionally so it doesn't get stale
993 $d = strtotime($person["updated"]." +00:00");
994 if ($d < strtotime("now - 14 days")) {
998 if ($person["guid"] == "") {
1002 } elseif (is_null($update)) {
1003 $update = !DBA::isResult($person);
1009 Logger::log("create or refresh", Logger::DEBUG);
1010 $r = Probe::uri($handle, Protocol::DIASPORA);
1012 // Note that Friendica contacts will return a "Diaspora person"
1013 // if Diaspora connectivity is enabled on their server
1014 if ($r && ($r["network"] === Protocol::DIASPORA)) {
1015 self::updateFContact($r);
1017 $person = self::personByHandle($handle, false);
1025 * @brief Updates the fcontact table
1027 * @param array $arr The fcontact data
1028 * @throws \Exception
1030 private static function updateFContact($arr)
1032 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
1033 'request' => $arr["request"], 'nick' => $arr["nick"],
1034 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1035 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1036 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1037 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1038 'updated' => DateTimeFormat::utcNow()];
1040 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1042 DBA::update('fcontact', $fields, $condition, true);
1046 * @brief get a handle (user@domain.tld) from a given contact id
1048 * @param int $contact_id The id in the contact table
1049 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1051 * @return string the handle
1052 * @throws \Exception
1054 private static function handleFromContact($contact_id, $pcontact_id = 0)
1058 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1060 if ($pcontact_id != 0) {
1061 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1063 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1064 return strtolower($contact["addr"]);
1069 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1073 if (DBA::isResult($r)) {
1076 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1078 if ($contact['addr'] != "") {
1079 $handle = $contact['addr'];
1081 $baseurl_start = strpos($contact['url'], '://') + 3;
1082 // allows installations in a subdirectory--not sure how Diaspora will handle
1083 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1084 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1085 $handle = $contact['nick'].'@'.$baseurl;
1089 return strtolower($handle);
1093 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1096 * @param mixed $fcontact_guid Hexadecimal string guid
1098 * @return string the contact url or null
1099 * @throws \Exception
1101 public static function urlFromContactGuid($fcontact_guid)
1103 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1106 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1107 DBA::escape(Protocol::DIASPORA),
1108 DBA::escape($fcontact_guid)
1111 if (DBA::isResult($r)) {
1112 return $r[0]['url'];
1119 * @brief Get a contact id for a given handle
1121 * @todo Move to Friendica\Model\Contact
1123 * @param int $uid The user id
1124 * @param string $handle The handle in the format user@domain.tld
1126 * @return array Contact data
1127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1128 * @throws \ImagickException
1130 private static function contactByHandle($uid, $handle)
1132 $cid = Contact::getIdForURL($handle, $uid);
1134 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1138 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1139 if (!DBA::isResult($contact)) {
1140 // This here shouldn't happen at all
1141 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1149 * Checks if the given contact url does support ActivityPub
1151 * @param string $url profile url
1152 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1155 * @throws \ImagickException
1157 public static function isSupportedByContactUrl($url, $update = null)
1159 return !empty(self::personByHandle($url, $update));
1163 * @brief Check if posting is allowed for this contact
1165 * @param array $importer Array of the importer user
1166 * @param array $contact The contact that is checked
1167 * @param bool $is_comment Is the check for a comment?
1169 * @return bool is the contact allowed to post?
1171 private static function postAllow(array $importer, array $contact, $is_comment = false)
1174 * Perhaps we were already sharing with this person. Now they're sharing with us.
1175 * That makes us friends.
1176 * Normally this should have handled by getting a request - but this could get lost
1178 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1179 // It is not removed by now. Possibly the code is needed?
1180 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1183 // array('rel' => Contact::FRIEND, 'writable' => true),
1184 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1187 // $contact["rel"] = Contact::FRIEND;
1188 // Logger::log("defining user ".$contact["nick"]." as friend");
1191 // Contact server is blocked
1192 if (Network::isUrlBlocked($contact['url'])) {
1194 // We don't seem to like that person
1195 } elseif ($contact["blocked"]) {
1196 // Maybe blocked, don't accept.
1198 // We are following this person?
1199 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1200 // Yes, then it is fine.
1202 // Is it a post to a community?
1203 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1206 // Is the message a global user or a comment?
1207 } elseif (($importer["uid"] == 0) || $is_comment) {
1208 // Messages for the global users and comments are always accepted
1216 * @brief Fetches the contact id for a handle and checks if posting is allowed
1218 * @param array $importer Array of the importer user
1219 * @param string $handle The checked handle in the format user@domain.tld
1220 * @param bool $is_comment Is the check for a comment?
1222 * @return array The contact data
1223 * @throws \Exception
1225 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1227 $contact = self::contactByHandle($importer["uid"], $handle);
1229 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1230 // If a contact isn't found, we accept it anyway if it is a comment
1231 if ($is_comment && ($importer["uid"] != 0)) {
1232 return self::contactByHandle(0, $handle);
1233 } elseif ($is_comment) {
1240 if (!self::postAllow($importer, $contact, $is_comment)) {
1241 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1248 * @brief Does the message already exists on the system?
1250 * @param int $uid The user id
1251 * @param string $guid The guid of the message
1253 * @return int|bool message id if the message already was stored into the system - or false.
1254 * @throws \Exception
1256 private static function messageExists($uid, $guid)
1258 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1259 if (DBA::isResult($item)) {
1260 Logger::log("message ".$guid." already exists for user ".$uid);
1268 * @brief Checks for links to posts in a message
1270 * @param array $item The item array
1273 private static function fetchGuid(array $item)
1275 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1276 preg_replace_callback(
1278 function ($match) use ($item) {
1279 self::fetchGuidSub($match, $item);
1284 preg_replace_callback(
1285 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1286 function ($match) use ($item) {
1287 self::fetchGuidSub($match, $item);
1294 * @brief Checks for relative /people/* links in an item body to match local
1295 * contacts or prepends the remote host taken from the author link.
1297 * @param string $body The item body to replace links from
1298 * @param string $author_link The author link for missing local contact fallback
1300 * @return string the replaced string
1302 public static function replacePeopleGuid($body, $author_link)
1304 $return = preg_replace_callback(
1305 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1306 function ($match) use ($author_link) {
1308 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1309 // 1 => '0123456789abcdef'
1311 $handle = self::urlFromContactGuid($match[1]);
1314 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1316 // No local match, restoring absolute remote URL from author scheme and host
1317 $author_url = parse_url($author_link);
1318 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1330 * @brief sub function of "fetchGuid" which checks for links in messages
1332 * @param array $match array containing a link that has to be checked for a message link
1333 * @param array $item The item array
1335 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1336 * @throws \ImagickException
1338 private static function fetchGuidSub($match, $item)
1340 if (!self::storeByGuid($match[1], $item["author-link"])) {
1341 self::storeByGuid($match[1], $item["owner-link"]);
1346 * @brief Fetches an item with a given guid from a given server
1348 * @param string $guid the message guid
1349 * @param string $server The server address
1350 * @param int $uid The user id of the user
1352 * @return int the message id of the stored message or false
1353 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1354 * @throws \ImagickException
1356 private static function storeByGuid($guid, $server, $uid = 0)
1358 $serverparts = parse_url($server);
1360 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1364 $server = $serverparts["scheme"]."://".$serverparts["host"];
1366 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1368 $msg = self::message($guid, $server);
1374 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1376 // Now call the dispatcher
1377 return self::dispatchPublic($msg);
1381 * @brief Fetches a message from a server
1383 * @param string $guid message guid
1384 * @param string $server The url of the server
1385 * @param int $level Endless loop prevention
1388 * 'message' => The message XML
1389 * 'author' => The author handle
1390 * 'key' => The public key of the author
1391 * @throws \Exception
1393 private static function message($guid, $server, $level = 0)
1399 // This will work for new Diaspora servers and Friendica servers from 3.5
1400 $source_url = $server."/fetch/post/".urlencode($guid);
1402 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1404 $envelope = Network::fetchUrl($source_url);
1406 Logger::log("Envelope was fetched.", Logger::DEBUG);
1407 $x = self::verifyMagicEnvelope($envelope);
1409 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1411 Logger::log("Envelope was verified.", Logger::DEBUG);
1421 $source_xml = XML::parseString($x);
1423 if (!is_object($source_xml)) {
1427 if ($source_xml->post->reshare) {
1428 // Reshare of a reshare - old Diaspora version
1429 Logger::log("Message is a reshare", Logger::DEBUG);
1430 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1431 } elseif ($source_xml->getName() == "reshare") {
1432 // Reshare of a reshare - new Diaspora version
1433 Logger::log("Message is a new reshare", Logger::DEBUG);
1434 return self::message($source_xml->root_guid, $server, ++$level);
1439 // Fetch the author - for the old and the new Diaspora version
1440 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1441 $author = (string)$source_xml->post->status_message->diaspora_handle;
1442 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1443 $author = (string)$source_xml->author;
1446 // If this isn't a "status_message" then quit
1448 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1452 $msg = ["message" => $x, "author" => $author];
1454 $msg["key"] = self::key($msg["author"]);
1460 * @brief Fetches an item with a given URL
1462 * @param string $url the message url
1464 * @return int the message id of the stored message or false
1465 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1466 * @throws \ImagickException
1468 public static function fetchByURL($url, $uid = 0)
1470 // Check for Diaspora (and Friendica) typical paths
1471 if (!preg_match("=(https?://.+)/(?:posts|display)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) {
1475 $guid = urldecode($matches[2]);
1477 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1478 if (DBA::isResult($item)) {
1482 self::storeByGuid($guid, $matches[1], $uid);
1484 $item = Item::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
1485 if (DBA::isResult($item)) {
1493 * @brief Fetches the item record of a given guid
1495 * @param int $uid The user id
1496 * @param string $guid message guid
1497 * @param string $author The handle of the item
1498 * @param array $contact The contact of the item owner
1500 * @return array the item record
1501 * @throws \Exception
1503 private static function parentItem($uid, $guid, $author, array $contact)
1505 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1506 'author-name', 'author-link', 'author-avatar',
1507 'owner-name', 'owner-link', 'owner-avatar'];
1508 $condition = ['uid' => $uid, 'guid' => $guid];
1509 $item = Item::selectFirst($fields, $condition);
1511 if (!DBA::isResult($item)) {
1512 $person = self::personByHandle($author);
1513 $result = self::storeByGuid($guid, $person["url"], $uid);
1515 // We don't have an url for items that arrived at the public dispatcher
1516 if (!$result && !empty($contact["url"])) {
1517 $result = self::storeByGuid($guid, $contact["url"], $uid);
1521 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1523 $item = Item::selectFirst($fields, $condition);
1527 if (!DBA::isResult($item)) {
1528 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1531 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1537 * @brief returns contact details
1539 * @param array $def_contact The default contact if the person isn't found
1540 * @param array $person The record of the person
1541 * @param int $uid The user id
1544 * 'cid' => contact id
1545 * 'network' => network type
1546 * @throws \Exception
1548 private static function authorContactByUrl($def_contact, $person, $uid)
1550 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1551 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1552 if (DBA::isResult($contact)) {
1553 $cid = $contact["id"];
1554 $network = $contact["network"];
1556 $cid = $def_contact["id"];
1557 $network = Protocol::DIASPORA;
1560 return ["cid" => $cid, "network" => $network];
1564 * @brief Is the profile a hubzilla profile?
1566 * @param string $url The profile link
1568 * @return bool is it a hubzilla server?
1570 public static function isRedmatrix($url)
1572 return(strstr($url, "/channel/"));
1576 * @brief Generate a post link with a given handle and message guid
1578 * @param string $addr The user handle
1579 * @param string $guid message guid
1580 * @param string $parent_guid optional parent guid
1582 * @return string the post link
1583 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1584 * @throws \ImagickException
1586 private static function plink($addr, $guid, $parent_guid = '')
1588 $contact = Contact::getDetailsByAddr($addr);
1592 if ($parent_guid != '') {
1593 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1595 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1599 if ($contact["network"] == Protocol::DFRN) {
1600 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1603 if (self::isRedmatrix($contact["url"])) {
1604 return $contact["url"] . "/?mid=" . $guid;
1607 if ($parent_guid != '') {
1608 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1610 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1615 * @brief Receives account migration
1617 * @param array $importer Array of the importer user
1618 * @param object $data The message object
1620 * @return bool Success
1621 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1622 * @throws \ImagickException
1624 private static function receiveAccountMigration(array $importer, $data)
1626 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1627 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1628 $signature = Strings::escapeTags(XML::unescape($data->signature));
1630 $contact = self::contactByHandle($importer["uid"], $old_handle);
1632 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1636 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1639 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1640 $key = self::key($old_handle);
1641 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1642 Logger::log('No valid signature for migration.');
1646 // Update the profile
1647 self::receiveProfile($importer, $data->profile);
1649 // change the technical stuff in contact and gcontact
1650 $data = Probe::uri($new_handle);
1651 if ($data['network'] == Protocol::PHANTOM) {
1652 Logger::log('Account for '.$new_handle." couldn't be probed.");
1656 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1657 'name' => $data['name'], 'nick' => $data['nick'],
1658 'addr' => $data['addr'], 'batch' => $data['batch'],
1659 'notify' => $data['notify'], 'poll' => $data['poll'],
1660 'network' => $data['network']];
1662 DBA::update('contact', $fields, ['addr' => $old_handle]);
1664 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1665 'name' => $data['name'], 'nick' => $data['nick'],
1666 'addr' => $data['addr'], 'connect' => $data['addr'],
1667 'notify' => $data['notify'], 'photo' => $data['photo'],
1668 'server_url' => $data['baseurl'], 'network' => $data['network']];
1670 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1672 Logger::log('Contacts are updated.');
1678 * @brief Processes an account deletion
1680 * @param object $data The message object
1682 * @return bool Success
1683 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1685 private static function receiveAccountDeletion($data)
1687 $author = Strings::escapeTags(XML::unescape($data->author));
1689 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1690 while ($contact = DBA::fetch($contacts)) {
1691 Contact::remove($contact["id"]);
1694 DBA::delete('gcontact', ['addr' => $author]);
1696 Logger::log('Removed contacts for ' . $author);
1702 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1704 * @param string $author Author handle
1705 * @param string $guid Message guid
1706 * @param boolean $onlyfound Only return uri when found in the database
1708 * @return string The constructed uri or the one from our database
1709 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1710 * @throws \ImagickException
1712 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1714 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1715 if (DBA::isResult($item)) {
1716 return $item["uri"];
1717 } elseif (!$onlyfound) {
1718 $person = self::personByHandle($author);
1720 $parts = parse_url($person['url']);
1721 unset($parts['path']);
1722 $host_url = Network::unparseURL($parts);
1724 return $host_url . '/objects/' . $guid;
1731 * @brief Fetch the guid from our database with a given uri
1733 * @param string $uri Message uri
1734 * @param string $uid Author handle
1736 * @return string The post guid
1737 * @throws \Exception
1739 private static function getGuidFromUri($uri, $uid)
1741 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1742 if (DBA::isResult($item)) {
1743 return $item["guid"];
1750 * @brief Find the best importer for a comment, like, ...
1752 * @param string $guid The guid of the item
1754 * @return array|boolean the origin owner of that post - or false
1755 * @throws \Exception
1757 private static function importerForGuid($guid)
1759 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1760 if (DBA::isResult($item)) {
1761 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1762 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1763 if (DBA::isResult($contact)) {
1771 * @brief Processes an incoming comment
1773 * @param array $importer Array of the importer user
1774 * @param string $sender The sender of the message
1775 * @param object $data The message object
1776 * @param string $xml The original XML of the message
1778 * @return int The message id of the generated comment or "false" if there was an error
1779 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1780 * @throws \ImagickException
1782 private static function receiveComment(array $importer, $sender, $data, $xml)
1784 $author = Strings::escapeTags(XML::unescape($data->author));
1785 $guid = Strings::escapeTags(XML::unescape($data->guid));
1786 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1787 $text = XML::unescape($data->text);
1789 if (isset($data->created_at)) {
1790 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1792 $created_at = DateTimeFormat::utcNow();
1795 if (isset($data->thread_parent_guid)) {
1796 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1797 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1802 $contact = self::allowedContactByHandle($importer, $sender, true);
1807 $message_id = self::messageExists($importer["uid"], $guid);
1812 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1813 if (!$parent_item) {
1817 $person = self::personByHandle($author);
1818 if (!is_array($person)) {
1819 Logger::log("unable to find author details");
1823 // Fetch the contact id - if we know this contact
1824 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1828 $datarray["uid"] = $importer["uid"];
1829 $datarray["contact-id"] = $author_contact["cid"];
1830 $datarray["network"] = $author_contact["network"];
1832 $datarray["author-link"] = $person["url"];
1833 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1835 $datarray["owner-link"] = $contact["url"];
1836 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1838 $datarray["guid"] = $guid;
1839 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1841 $datarray["verb"] = Activity::POST;
1842 $datarray["gravity"] = GRAVITY_COMMENT;
1844 if ($thr_uri != "") {
1845 $datarray["parent-uri"] = $thr_uri;
1847 $datarray["parent-uri"] = $parent_item["uri"];
1850 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1852 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1853 $datarray["source"] = $xml;
1855 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1857 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1859 $body = Markdown::toBBCode($text);
1861 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1863 self::fetchGuid($datarray);
1865 // If we are the origin of the parent we store the original data.
1866 // We notify our followers during the item storage.
1867 if ($parent_item["origin"]) {
1868 $datarray['diaspora_signed_text'] = json_encode($data);
1871 $message_id = Item::insert($datarray);
1873 if ($message_id <= 0) {
1878 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1879 if ($datarray['uid'] == 0) {
1880 Item::distribute($message_id, json_encode($data));
1888 * @brief processes and stores private messages
1890 * @param array $importer Array of the importer user
1891 * @param array $contact The contact of the message
1892 * @param object $data The message object
1893 * @param array $msg Array of the processed message, author handle and key
1894 * @param object $mesg The private message
1895 * @param array $conversation The conversation record to which this message belongs
1897 * @return bool "true" if it was successful
1898 * @throws \Exception
1900 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1902 $author = Strings::escapeTags(XML::unescape($data->author));
1903 $guid = Strings::escapeTags(XML::unescape($data->guid));
1904 $subject = Strings::escapeTags(XML::unescape($data->subject));
1906 // "diaspora_handle" is the element name from the old version
1907 // "author" is the element name from the new version
1908 if ($mesg->author) {
1909 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1910 } elseif ($mesg->diaspora_handle) {
1911 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1916 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1917 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1918 $msg_text = XML::unescape($mesg->text);
1919 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1921 if ($msg_conversation_guid != $guid) {
1922 Logger::log("message conversation guid does not belong to the current conversation.");
1926 $body = Markdown::toBBCode($msg_text);
1927 $message_uri = $msg_author.":".$msg_guid;
1929 $person = self::personByHandle($msg_author);
1931 return Mail::insert([
1932 'uid' => $importer['uid'],
1933 'guid' => $msg_guid,
1934 'convid' => $conversation['id'],
1935 'from-name' => $person['name'],
1936 'from-photo' => $person['photo'],
1937 'from-url' => $person['url'],
1938 'contact-id' => $contact['id'],
1939 'title' => $subject,
1941 'uri' => $message_uri,
1942 'parent-uri' => $author . ':' . $guid,
1943 'created' => $msg_created_at
1948 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1950 * @param array $importer Array of the importer user
1951 * @param array $msg Array of the processed message, author handle and key
1952 * @param object $data The message object
1954 * @return bool Success
1955 * @throws \Exception
1957 private static function receiveConversation(array $importer, $msg, $data)
1959 $author = Strings::escapeTags(XML::unescape($data->author));
1960 $guid = Strings::escapeTags(XML::unescape($data->guid));
1961 $subject = Strings::escapeTags(XML::unescape($data->subject));
1962 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1963 $participants = Strings::escapeTags(XML::unescape($data->participants));
1965 $messages = $data->message;
1967 if (!count($messages)) {
1968 Logger::log("empty conversation");
1972 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1977 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1978 if (!DBA::isResult($conversation)) {
1980 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1981 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1982 intval($importer["uid"]),
1984 DBA::escape($author),
1985 DBA::escape($created_at),
1986 DBA::escape(DateTimeFormat::utcNow()),
1987 DBA::escape($subject),
1988 DBA::escape($participants)
1991 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1994 if (!$conversation) {
1995 Logger::log("unable to create conversation.");
1999 foreach ($messages as $mesg) {
2000 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2007 * @brief Processes "like" messages
2009 * @param array $importer Array of the importer user
2010 * @param string $sender The sender of the message
2011 * @param object $data The message object
2013 * @return int The message id of the generated like or "false" if there was an error
2014 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2015 * @throws \ImagickException
2017 private static function receiveLike(array $importer, $sender, $data)
2019 $author = Strings::escapeTags(XML::unescape($data->author));
2020 $guid = Strings::escapeTags(XML::unescape($data->guid));
2021 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2022 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
2023 $positive = Strings::escapeTags(XML::unescape($data->positive));
2025 // likes on comments aren't supported by Diaspora - only on posts
2026 // But maybe this will be supported in the future, so we will accept it.
2027 if (!in_array($parent_type, ["Post", "Comment"])) {
2031 $contact = self::allowedContactByHandle($importer, $sender, true);
2036 $message_id = self::messageExists($importer["uid"], $guid);
2041 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2042 if (!$parent_item) {
2046 $person = self::personByHandle($author);
2047 if (!is_array($person)) {
2048 Logger::log("unable to find author details");
2052 // Fetch the contact id - if we know this contact
2053 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2055 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2056 // We would accept this anyhow.
2057 if ($positive == "true") {
2058 $verb = Activity::LIKE;
2060 $verb = Activity::DISLIKE;
2065 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2067 $datarray["uid"] = $importer["uid"];
2068 $datarray["contact-id"] = $author_contact["cid"];
2069 $datarray["network"] = $author_contact["network"];
2071 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2072 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2074 $datarray["guid"] = $guid;
2075 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2077 $datarray["verb"] = $verb;
2078 $datarray["gravity"] = GRAVITY_ACTIVITY;
2079 $datarray["parent-uri"] = $parent_item["uri"];
2081 $datarray["object-type"] = Activity\ObjectType::NOTE;
2083 $datarray["body"] = $verb;
2085 // Diaspora doesn't provide a date for likes
2086 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2088 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2089 if ($parent_item["id"] != $parent_item["parent"]) {
2090 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2091 $origin = $toplevel["origin"];
2093 $origin = $parent_item["origin"];
2096 // If we are the origin of the parent we store the original data.
2097 // We notify our followers during the item storage.
2099 $datarray['diaspora_signed_text'] = json_encode($data);
2102 $message_id = Item::insert($datarray);
2104 if ($message_id <= 0) {
2109 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2110 if ($datarray['uid'] == 0) {
2111 Item::distribute($message_id, json_encode($data));
2119 * @brief Processes private messages
2121 * @param array $importer Array of the importer user
2122 * @param object $data The message object
2124 * @return bool Success?
2125 * @throws \Exception
2127 private static function receiveMessage(array $importer, $data)
2129 $author = Strings::escapeTags(XML::unescape($data->author));
2130 $guid = Strings::escapeTags(XML::unescape($data->guid));
2131 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2132 $text = XML::unescape($data->text);
2133 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2135 $contact = self::allowedContactByHandle($importer, $author, true);
2140 $conversation = null;
2142 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2143 $conversation = DBA::selectFirst('conv', [], $condition);
2145 if (!DBA::isResult($conversation)) {
2146 Logger::log("conversation not available.");
2150 $message_uri = $author.":".$guid;
2152 $person = self::personByHandle($author);
2154 Logger::log("unable to find author details");
2158 $body = Markdown::toBBCode($text);
2160 $body = self::replacePeopleGuid($body, $person["url"]);
2162 return Mail::insert([
2163 'uid' => $importer['uid'],
2165 'convid' => $conversation['id'],
2166 'from-name' => $person['name'],
2167 'from-photo' => $person['photo'],
2168 'from-url' => $person['url'],
2169 'contact-id' => $contact['id'],
2170 'title' => $conversation['subject'],
2173 'uri' => $message_uri,
2174 'parent-uri' => $author.":".$conversation['guid'],
2175 'created' => $created_at
2180 * @brief Processes participations - unsupported by now
2182 * @param array $importer Array of the importer user
2183 * @param object $data The message object
2185 * @return bool always true
2186 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2187 * @throws \ImagickException
2189 private static function receiveParticipation(array $importer, $data)
2191 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2192 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2194 $contact_id = Contact::getIdForURL($author);
2196 Logger::log('Contact not found: '.$author);
2200 $person = self::personByHandle($author);
2201 if (!is_array($person)) {
2202 Logger::log("Person not found: ".$author);
2206 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2207 if (!DBA::isResult($item)) {
2208 Logger::log('Item not found, no origin or private: '.$parent_guid);
2212 $author_parts = explode('@', $author);
2213 if (isset($author_parts[1])) {
2214 $server = $author_parts[1];
2216 // Should never happen
2220 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2222 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2223 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2226 // Send all existing comments and likes to the requesting server
2227 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2228 while ($comment = Item::fetch($comments)) {
2229 if ($comment['id'] == $comment['parent']) {
2233 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2234 if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id)) {
2235 ItemDeliveryData::incrementQueueCount($comment['id'], 1);
2238 DBA::close($comments);
2244 * @brief Processes photos - unneeded
2246 * @param array $importer Array of the importer user
2247 * @param object $data The message object
2249 * @return bool always true
2251 private static function receivePhoto(array $importer, $data)
2253 // There doesn't seem to be a reason for this function,
2254 // since the photo data is transmitted in the status message as well
2259 * @brief Processes poll participations - unssupported
2261 * @param array $importer Array of the importer user
2262 * @param object $data The message object
2264 * @return bool always true
2266 private static function receivePollParticipation(array $importer, $data)
2268 // We don't support polls by now
2273 * @brief Processes incoming profile updates
2275 * @param array $importer Array of the importer user
2276 * @param object $data The message object
2278 * @return bool Success
2279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2280 * @throws \ImagickException
2282 private static function receiveProfile(array $importer, $data)
2284 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2286 $contact = self::contactByHandle($importer["uid"], $author);
2291 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2292 $image_url = XML::unescape($data->image_url);
2293 $birthday = XML::unescape($data->birthday);
2294 $gender = XML::unescape($data->gender);
2295 $about = Markdown::toBBCode(XML::unescape($data->bio));
2296 $location = Markdown::toBBCode(XML::unescape($data->location));
2297 $searchable = (XML::unescape($data->searchable) == "true");
2298 $nsfw = (XML::unescape($data->nsfw) == "true");
2299 $tags = XML::unescape($data->tag_string);
2301 $tags = explode("#", $tags);
2304 foreach ($tags as $tag) {
2305 $tag = trim(strtolower($tag));
2311 $keywords = implode(", ", $keywords);
2313 $handle_parts = explode("@", $author);
2314 $nick = $handle_parts[0];
2317 $name = $handle_parts[0];
2320 if (preg_match("|^https?://|", $image_url) === 0) {
2321 $image_url = "http://".$handle_parts[1].$image_url;
2324 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2326 // Generic birthday. We don't know the timezone. The year is irrelevant.
2328 $birthday = str_replace("1000", "1901", $birthday);
2330 if ($birthday != "") {
2331 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2334 // this is to prevent multiple birthday notifications in a single year
2335 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2337 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2338 $birthday = $contact["bd"];
2341 $fields = ['name' => $name, 'location' => $location,
2342 'name-date' => DateTimeFormat::utcNow(),
2343 'about' => $about, 'gender' => $gender,
2344 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2345 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2347 if (!empty($birthday)) {
2348 $fields['bd'] = $birthday;
2351 DBA::update('contact', $fields, ['id' => $contact['id']]);
2353 // @todo Update the public contact, then update the gcontact from that
2355 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2356 "photo" => $image_url, "name" => $name, "location" => $location,
2357 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2358 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2359 "hide" => !$searchable, "nsfw" => $nsfw];
2361 $gcid = GContact::update($gcontact);
2363 GContact::link($gcid, $importer["uid"], $contact["id"]);
2365 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2371 * @brief Processes incoming friend requests
2373 * @param array $importer Array of the importer user
2374 * @param array $contact The contact that send the request
2376 * @throws \Exception
2378 private static function receiveRequestMakeFriend(array $importer, array $contact)
2380 if ($contact["rel"] == Contact::SHARING) {
2383 ['rel' => Contact::FRIEND, 'writable' => true],
2384 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2390 * @brief Processes incoming sharing notification
2392 * @param array $importer Array of the importer user
2393 * @param object $data The message object
2395 * @return bool Success
2396 * @throws \Exception
2398 private static function receiveContactRequest(array $importer, $data)
2400 $author = XML::unescape($data->author);
2401 $recipient = XML::unescape($data->recipient);
2403 if (!$author || !$recipient) {
2407 // the current protocol version doesn't know these fields
2408 // That means that we will assume their existance
2409 if (isset($data->following)) {
2410 $following = (XML::unescape($data->following) == "true");
2415 if (isset($data->sharing)) {
2416 $sharing = (XML::unescape($data->sharing) == "true");
2421 $contact = self::contactByHandle($importer["uid"], $author);
2423 // perhaps we were already sharing with this person. Now they're sharing with us.
2424 // That makes us friends.
2427 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2428 self::receiveRequestMakeFriend($importer, $contact);
2430 // refetch the contact array
2431 $contact = self::contactByHandle($importer["uid"], $author);
2433 // If we are now friends, we are sending a share message.
2434 // Normally we needn't to do so, but the first message could have been vanished.
2435 if (in_array($contact["rel"], [Contact::FRIEND])) {
2436 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2437 if (DBA::isResult($user)) {
2438 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2439 self::sendShare($user, $contact);
2444 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2445 Contact::removeFollower($importer, $contact);
2450 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2451 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2453 } elseif (!$following && !$sharing) {
2454 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2456 } elseif (!$following && $sharing) {
2457 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2458 } elseif ($following && $sharing) {
2459 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2460 } elseif ($following && !$sharing) {
2461 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2464 $ret = self::personByHandle($author);
2466 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2467 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2471 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2473 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2478 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2479 'author-link' => $ret['url']];
2481 $result = Contact::addRelationship($importer, $contact, $item, false);
2482 if ($result === true) {
2483 $contact_record = self::contactByHandle($importer['uid'], $author);
2484 if (!$contact_record) {
2485 Logger::info('unable to locate newly created contact record.');
2489 $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2490 if (DBA::isResult($user)) {
2491 self::sendShare($user, $contact_record);
2493 // Send the profile data, maybe it weren't transmitted before
2494 self::sendProfile($importer['uid'], [$contact_record]);
2502 * @brief Fetches a message with a given guid
2504 * @param string $guid message guid
2505 * @param string $orig_author handle of the original post
2506 * @return array The fetched item
2507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2508 * @throws \ImagickException
2510 public static function originalItem($guid, $orig_author)
2513 Logger::log('Empty guid. Quitting.');
2517 // Do we already have this item?
2518 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2519 'author-name', 'author-link', 'author-avatar'];
2520 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2521 $item = Item::selectFirst($fields, $condition);
2523 if (DBA::isResult($item)) {
2524 Logger::log("reshared message ".$guid." already exists on system.");
2526 // Maybe it is already a reshared item?
2527 // Then refetch the content, if it is a reshare from a reshare.
2528 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2529 if (self::isReshare($item["body"], true)) {
2531 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2532 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2534 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2536 // Add OEmbed and other information to the body
2537 $item["body"] = add_page_info_to_body($item["body"], false, true);
2545 if (!DBA::isResult($item)) {
2546 if (empty($orig_author)) {
2547 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2551 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2552 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2553 $stored = self::storeByGuid($guid, $server);
2556 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2557 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2558 $stored = self::storeByGuid($guid, $server);
2562 $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2563 'author-name', 'author-link', 'author-avatar'];
2564 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2565 $item = Item::selectFirst($fields, $condition);
2567 if (DBA::isResult($item)) {
2568 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2569 if (self::isReshare($item["body"], false)) {
2570 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2571 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2582 * @brief Stores a reshare activity
2584 * @param array $item Array of reshare post
2585 * @param integer $parent_message_id Id of the parent post
2586 * @param string $guid GUID string of reshare action
2587 * @param string $author Author handle
2589 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2591 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2595 $datarray['uid'] = $item['uid'];
2596 $datarray['contact-id'] = $item['contact-id'];
2597 $datarray['network'] = $item['network'];
2599 $datarray['author-link'] = $item['author-link'];
2600 $datarray['author-id'] = $item['author-id'];
2602 $datarray['owner-link'] = $datarray['author-link'];
2603 $datarray['owner-id'] = $datarray['author-id'];
2605 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2606 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2607 $datarray['parent-uri'] = $parent['uri'];
2609 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2610 $datarray['gravity'] = GRAVITY_ACTIVITY;
2611 $datarray['object-type'] = Activity\ObjectType::NOTE;
2613 $datarray['protocol'] = $item['protocol'];
2615 $datarray['plink'] = self::plink($author, $datarray['guid']);
2616 $datarray['private'] = $item['private'];
2617 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2619 $message_id = Item::insert($datarray);
2622 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2623 if ($datarray['uid'] == 0) {
2624 Item::distribute($message_id);
2630 * @brief Processes a reshare message
2632 * @param array $importer Array of the importer user
2633 * @param object $data The message object
2634 * @param string $xml The original XML of the message
2636 * @return int the message id
2637 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2638 * @throws \ImagickException
2640 private static function receiveReshare(array $importer, $data, $xml)
2642 $author = Strings::escapeTags(XML::unescape($data->author));
2643 $guid = Strings::escapeTags(XML::unescape($data->guid));
2644 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2645 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2646 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2647 /// @todo handle unprocessed property "provider_display_name"
2648 $public = Strings::escapeTags(XML::unescape($data->public));
2650 $contact = self::allowedContactByHandle($importer, $author, false);
2655 $message_id = self::messageExists($importer["uid"], $guid);
2660 $original_item = self::originalItem($root_guid, $root_author);
2661 if (!$original_item) {
2665 $orig_url = DI::baseUrl()."/display/".$original_item["guid"];
2669 $datarray["uid"] = $importer["uid"];
2670 $datarray["contact-id"] = $contact["id"];
2671 $datarray["network"] = Protocol::DIASPORA;
2673 $datarray["author-link"] = $contact["url"];
2674 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2676 $datarray["owner-link"] = $datarray["author-link"];
2677 $datarray["owner-id"] = $datarray["author-id"];
2679 $datarray["guid"] = $guid;
2680 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2682 $datarray["verb"] = Activity::POST;
2683 $datarray["gravity"] = GRAVITY_PARENT;
2685 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2686 $datarray["source"] = $xml;
2688 $prefix = share_header(
2689 $original_item["author-name"],
2690 $original_item["author-link"],
2691 $original_item["author-avatar"],
2692 $original_item["guid"],
2693 $original_item["created"],
2697 if (!empty($original_item['title'])) {
2698 $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2701 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2703 $datarray["tag"] = $original_item["tag"];
2704 $datarray["attach"] = $original_item["attach"];
2705 $datarray["app"] = $original_item["app"];
2707 $datarray["plink"] = self::plink($author, $guid);
2708 $datarray["private"] = (($public == "false") ? 1 : 0);
2709 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2711 $datarray["object-type"] = $original_item["object-type"];
2713 self::fetchGuid($datarray);
2714 $message_id = Item::insert($datarray);
2716 self::sendParticipation($contact, $datarray);
2718 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2719 if ($root_message_id) {
2720 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2724 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2725 if ($datarray['uid'] == 0) {
2726 Item::distribute($message_id);
2735 * @brief Processes retractions
2737 * @param array $importer Array of the importer user
2738 * @param array $contact The contact of the item owner
2739 * @param object $data The message object
2741 * @return bool success
2742 * @throws \Exception
2744 private static function itemRetraction(array $importer, array $contact, $data)
2746 $author = Strings::escapeTags(XML::unescape($data->author));
2747 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2748 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2750 $person = self::personByHandle($author);
2751 if (!is_array($person)) {
2752 Logger::log("unable to find author detail for ".$author);
2756 if (empty($contact["url"])) {
2757 $contact["url"] = $person["url"];
2760 // Fetch items that are about to be deleted
2761 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2763 // When we receive a public retraction, we delete every item that we find.
2764 if ($importer['uid'] == 0) {
2765 $condition = ['guid' => $target_guid, 'deleted' => false];
2767 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2770 $r = Item::select($fields, $condition);
2771 if (!DBA::isResult($r)) {
2772 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2776 while ($item = Item::fetch($r)) {
2777 if (strstr($item['file'], '[')) {
2778 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2782 // Fetch the parent item
2783 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2785 // Only delete it if the parent author really fits
2786 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2787 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2791 Item::delete(['id' => $item['id']]);
2793 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2800 * @brief Receives retraction messages
2802 * @param array $importer Array of the importer user
2803 * @param string $sender The sender of the message
2804 * @param object $data The message object
2806 * @return bool Success
2807 * @throws \Exception
2809 private static function receiveRetraction(array $importer, $sender, $data)
2811 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2813 $contact = self::contactByHandle($importer["uid"], $sender);
2814 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2815 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2823 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2825 switch ($target_type) {
2830 case "StatusMessage":
2831 return self::itemRetraction($importer, $contact, $data);
2833 case "PollParticipation":
2835 // Currently unsupported
2839 Logger::log("Unknown target type ".$target_type);
2846 * @brief Receives status messages
2848 * @param array $importer Array of the importer user
2849 * @param SimpleXMLElement $data The message object
2850 * @param string $xml The original XML of the message
2852 * @return int The message id of the newly created item
2853 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2854 * @throws \ImagickException
2856 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2858 $author = Strings::escapeTags(XML::unescape($data->author));
2859 $guid = Strings::escapeTags(XML::unescape($data->guid));
2860 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2861 $public = Strings::escapeTags(XML::unescape($data->public));
2862 $text = XML::unescape($data->text);
2863 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2865 $contact = self::allowedContactByHandle($importer, $author, false);
2870 $message_id = self::messageExists($importer["uid"], $guid);
2876 if ($data->location) {
2877 foreach ($data->location->children() as $fieldname => $data) {
2878 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2882 $body = Markdown::toBBCode($text);
2886 // Attach embedded pictures to the body
2888 foreach ($data->photo as $photo) {
2889 $body = "[img]".XML::unescape($photo->remote_photo_path).
2890 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2893 $datarray["object-type"] = Activity\ObjectType::IMAGE;
2895 $datarray["object-type"] = Activity\ObjectType::NOTE;
2897 // Add OEmbed and other information to the body
2898 if (!self::isRedmatrix($contact["url"])) {
2899 $body = add_page_info_to_body($body, false, true);
2903 /// @todo enable support for polls
2904 //if ($data->poll) {
2905 // foreach ($data->poll AS $poll)
2910 /// @todo enable support for events
2912 $datarray["uid"] = $importer["uid"];
2913 $datarray["contact-id"] = $contact["id"];
2914 $datarray["network"] = Protocol::DIASPORA;
2916 $datarray["author-link"] = $contact["url"];
2917 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2919 $datarray["owner-link"] = $datarray["author-link"];
2920 $datarray["owner-id"] = $datarray["author-id"];
2922 $datarray["guid"] = $guid;
2923 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2925 $datarray["verb"] = Activity::POST;
2926 $datarray["gravity"] = GRAVITY_PARENT;
2928 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2929 $datarray["source"] = $xml;
2931 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2933 if ($provider_display_name != "") {
2934 $datarray["app"] = $provider_display_name;
2937 $datarray["plink"] = self::plink($author, $guid);
2938 $datarray["private"] = (($public == "false") ? 1 : 0);
2939 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2941 if (isset($address["address"])) {
2942 $datarray["location"] = $address["address"];
2945 if (isset($address["lat"]) && isset($address["lng"])) {
2946 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2949 self::fetchGuid($datarray);
2950 $message_id = Item::insert($datarray);
2952 self::sendParticipation($contact, $datarray);
2955 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2956 if ($datarray['uid'] == 0) {
2957 Item::distribute($message_id);
2965 /* ************************************************************************************** *
2966 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2967 * ************************************************************************************** */
2970 * @brief returnes the handle of a contact
2972 * @param array $contact contact array
2974 * @return string the handle in the format user@domain.tld
2975 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2977 private static function myHandle(array $contact)
2979 if (!empty($contact["addr"])) {
2980 return $contact["addr"];
2983 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2984 // So - just in case - we build the the address here.
2985 if ($contact["nickname"] != "") {
2986 $nick = $contact["nickname"];
2988 $nick = $contact["nick"];
2991 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
2996 * @brief Creates the data for a private message in the new format
2998 * @param string $msg The message that is to be transmitted
2999 * @param array $user The record of the sender
3000 * @param array $contact Target of the communication
3001 * @param string $prvkey The private key of the sender
3002 * @param string $pubkey The public key of the receiver
3004 * @return string The encrypted data
3005 * @throws \Exception
3007 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3009 Logger::log("Message: ".$msg, Logger::DATA);
3011 // without a public key nothing will work
3013 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3017 $aes_key = openssl_random_pseudo_bytes(32);
3018 $b_aes_key = base64_encode($aes_key);
3019 $iv = openssl_random_pseudo_bytes(16);
3020 $b_iv = base64_encode($iv);
3022 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3024 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3026 $encrypted_key_bundle = "";
3027 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3029 $json_object = json_encode(
3030 ["aes_key" => base64_encode($encrypted_key_bundle),
3031 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3034 return $json_object;
3038 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3040 * @param string $msg The message that is to be transmitted
3041 * @param array $user The record of the sender
3043 * @return string The envelope
3044 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3046 public static function buildMagicEnvelope($msg, array $user)
3048 $b64url_data = Strings::base64UrlEncode($msg);
3049 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3051 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3052 $type = "application/xml";
3053 $encoding = "base64url";
3054 $alg = "RSA-SHA256";
3055 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3057 // Fallback if the private key wasn't transmitted in the expected field
3058 if ($user['uprvkey'] == "") {
3059 $user['uprvkey'] = $user['prvkey'];
3062 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3063 $sig = Strings::base64UrlEncode($signature);
3065 $xmldata = ["me:env" => ["me:data" => $data,
3066 "@attributes" => ["type" => $type],
3067 "me:encoding" => $encoding,
3070 "@attributes2" => ["key_id" => $key_id]]];
3072 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3074 return XML::fromArray($xmldata, $xml, false, $namespaces);
3078 * @brief Create the envelope for a message
3080 * @param string $msg The message that is to be transmitted
3081 * @param array $user The record of the sender
3082 * @param array $contact Target of the communication
3083 * @param string $prvkey The private key of the sender
3084 * @param string $pubkey The public key of the receiver
3085 * @param bool $public Is the message public?
3087 * @return string The message that will be transmitted to other servers
3088 * @throws \Exception
3090 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3092 // The message is put into an envelope with the sender's signature
3093 $envelope = self::buildMagicEnvelope($msg, $user);
3095 // Private messages are put into a second envelope, encrypted with the receivers public key
3097 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3104 * @brief Creates a signature for a message
3106 * @param array $owner the array of the owner of the message
3107 * @param array $message The message that is to be signed
3109 * @return string The signature
3111 private static function signature($owner, $message)
3114 unset($sigmsg["author_signature"]);
3115 unset($sigmsg["parent_author_signature"]);
3117 $signed_text = implode(";", $sigmsg);
3119 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3123 * @brief Transmit a message to a target server
3125 * @param array $owner the array of the item owner
3126 * @param array $contact Target of the communication
3127 * @param string $envelope The message that is to be transmitted
3128 * @param bool $public_batch Is it a public post?
3129 * @param string $guid message guid
3131 * @return int Result of the transmission
3132 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3133 * @throws \ImagickException
3135 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3137 $enabled = intval(Config::get("system", "diaspora_enabled"));
3142 $logid = Strings::getRandomHex(4);
3144 // We always try to use the data from the fcontact table.
3145 // This is important for transmitting data to Friendica servers.
3146 if (!empty($contact['addr'])) {
3147 $fcontact = self::personByHandle($contact['addr']);
3148 if (!empty($fcontact)) {
3149 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3153 if (empty($dest_url)) {
3154 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3158 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3162 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3164 if (!intval(Config::get("system", "diaspora_test"))) {
3165 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3167 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3168 $return_code = $postResult->getReturnCode();
3170 Logger::log("test_mode");
3174 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3176 return $return_code ? $return_code : -1;
3181 * @brief Build the post xml
3183 * @param string $type The message type
3184 * @param array $message The message data
3186 * @return string The post XML
3188 public static function buildPostXml($type, $message)
3190 $data = [$type => $message];
3192 return XML::fromArray($data, $xml);
3196 * @brief Builds and transmit messages
3198 * @param array $owner the array of the item owner
3199 * @param array $contact Target of the communication
3200 * @param string $type The message type
3201 * @param array $message The message data
3202 * @param bool $public_batch Is it a public post?
3203 * @param string $guid message guid
3205 * @return int Result of the transmission
3206 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3207 * @throws \ImagickException
3209 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3211 $msg = self::buildPostXml($type, $message);
3213 Logger::log('message: '.$msg, Logger::DATA);
3214 Logger::log('send guid '.$guid, Logger::DEBUG);
3216 // Fallback if the private key wasn't transmitted in the expected field
3217 if (empty($owner['uprvkey'])) {
3218 $owner['uprvkey'] = $owner['prvkey'];
3221 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3223 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3225 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3227 return $return_code;
3231 * @brief sends a participation (Used to get all further updates)
3233 * @param array $contact Target of the communication
3234 * @param array $item Item array
3236 * @return int The result of the transmission
3237 * @throws \Exception
3239 private static function sendParticipation(array $contact, array $item)
3241 // Don't send notifications for private postings
3242 if ($item['private']) {
3246 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3248 $result = DI::cache()->get($cachekey);
3249 if (!is_null($result)) {
3253 // Fetch some user id to have a valid handle to transmit the participation.
3254 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3255 // If the item belongs to a user, we take this user id.
3256 if ($item['uid'] == 0) {
3257 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3258 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3259 $owner = User::getOwnerDataById($first_user['uid']);
3261 $owner = User::getOwnerDataById($item['uid']);
3264 $author = self::myHandle($owner);
3266 $message = ["author" => $author,
3267 "guid" => System::createUUID(),
3268 "parent_type" => "Post",
3269 "parent_guid" => $item["guid"]];
3271 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3273 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3274 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3276 return self::buildAndTransmit($owner, $contact, "participation", $message);
3280 * @brief sends an account migration
3282 * @param array $owner the array of the item owner
3283 * @param array $contact Target of the communication
3284 * @param int $uid User ID
3286 * @return int The result of the transmission
3287 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3288 * @throws \ImagickException
3290 public static function sendAccountMigration(array $owner, array $contact, $uid)
3292 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3293 $profile = self::createProfileData($uid);
3295 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3296 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3298 $message = ["author" => $old_handle,
3299 "profile" => $profile,
3300 "signature" => $signature];
3302 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3304 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3308 * @brief Sends a "share" message
3310 * @param array $owner the array of the item owner
3311 * @param array $contact Target of the communication
3313 * @return int The result of the transmission
3314 * @throws \Exception
3316 public static function sendShare(array $owner, array $contact)
3319 * @todo support the different possible combinations of "following" and "sharing"
3320 * Currently, Diaspora only interprets the "sharing" field
3322 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3326 switch ($contact["rel"]) {
3327 case Contact::FRIEND:
3331 case Contact::SHARING:
3335 case Contact::FOLLOWER:
3341 $message = ["author" => self::myHandle($owner),
3342 "recipient" => $contact["addr"],
3343 "following" => "true",
3344 "sharing" => "true"];
3346 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3348 return self::buildAndTransmit($owner, $contact, "contact", $message);
3352 * @brief sends an "unshare"
3354 * @param array $owner the array of the item owner
3355 * @param array $contact Target of the communication
3357 * @return int The result of the transmission
3358 * @throws \Exception
3360 public static function sendUnshare(array $owner, array $contact)
3362 $message = ["author" => self::myHandle($owner),
3363 "recipient" => $contact["addr"],
3364 "following" => "false",
3365 "sharing" => "false"];
3367 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3369 return self::buildAndTransmit($owner, $contact, "contact", $message);
3373 * @brief Checks a message body if it is a reshare
3375 * @param string $body The message body that is to be check
3376 * @param bool $complete Should it be a complete check or a simple check?
3378 * @return array|bool Reshare details or "false" if no reshare
3379 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3380 * @throws \ImagickException
3382 public static function isReshare($body, $complete = true)
3384 $body = trim($body);
3386 $reshared = Item::getShareArray(['body' => $body]);
3387 if (empty($reshared)) {
3391 // Skip if it isn't a pure repeated messages
3392 // Does it start with a share?
3393 if (!empty($reshared['comment']) && $complete) {
3397 if (!empty($reshared['guid']) && $complete) {
3398 $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3399 $item = Item::selectFirst(['contact-id'], $condition);
3400 if (DBA::isResult($item)) {
3402 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3403 $ret["root_guid"] = $reshared['guid'];
3405 } elseif ($complete) {
3406 // We are resharing something that isn't a DFRN or Diaspora post.
3407 // So we have to return "false" on "$complete" to not trigger a reshare.
3410 } elseif (empty($reshared['guid']) && $complete) {
3416 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3417 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3418 if (!empty($contact['addr'])) {
3419 $ret['root_handle'] = $contact['addr'];
3423 if (empty($ret) && !$complete) {
3431 * @brief Create an event array
3433 * @param integer $event_id The id of the event
3435 * @return array with event data
3436 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3438 private static function buildEvent($event_id)
3440 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3441 if (!DBA::isResult($r)) {
3449 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3450 if (!DBA::isResult($r)) {
3456 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3457 if (!DBA::isResult($r)) {
3463 $eventdata['author'] = self::myHandle($owner);
3465 if ($event['guid']) {
3466 $eventdata['guid'] = $event['guid'];
3469 $mask = DateTimeFormat::ATOM;
3471 /// @todo - establish "all day" events in Friendica
3472 $eventdata["all_day"] = "false";
3474 $eventdata['timezone'] = 'UTC';
3475 if (!$event['adjust'] && $user['timezone']) {
3476 $eventdata['timezone'] = $user['timezone'];
3479 if ($event['start']) {
3480 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3482 if ($event['finish'] && !$event['nofinish']) {
3483 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3485 if ($event['summary']) {
3486 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3488 if ($event['desc']) {
3489 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3491 if ($event['location']) {
3492 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3493 $coord = Map::getCoordinates($event['location']);
3496 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3497 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3498 $location["lat"] = $coord['lat'];
3499 $location["lng"] = $coord['lon'];
3501 $location["lat"] = 0;
3502 $location["lng"] = 0;
3504 $eventdata['location'] = $location;
3511 * @brief Create a post (status message or reshare)
3513 * @param array $item The item that will be exported
3514 * @param array $owner the array of the item owner
3517 * 'type' -> Message type ("status_message" or "reshare")
3518 * 'message' -> Array of XML elements of the status
3519 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3520 * @throws \ImagickException
3522 public static function buildStatus(array $item, array $owner)
3524 $cachekey = "diaspora:buildStatus:".$item['guid'];
3526 $result = DI::cache()->get($cachekey);
3527 if (!is_null($result)) {
3531 $myaddr = self::myHandle($owner);
3533 $public = ($item["private"] ? "false" : "true");
3534 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3535 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3537 // Detect a share element and do a reshare
3538 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3539 $message = ["author" => $myaddr,
3540 "guid" => $item["guid"],
3541 "created_at" => $created,
3542 "root_author" => $ret["root_handle"],
3543 "root_guid" => $ret["root_guid"],
3544 "provider_display_name" => $item["app"],
3545 "public" => $public];
3549 $title = $item["title"];
3550 $body = $item["body"];
3552 // Fetch the title from an attached link - if there is one
3553 if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3554 $page_data = BBCode::getAttachmentData($item['body']);
3555 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3556 $title = $page_data['title'];
3560 if ($item['author-link'] != $item['owner-link']) {
3561 require_once 'mod/share.php';
3562 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3563 "", $item['created'], $item['plink']) . $body . '[/share]';
3566 // convert to markdown
3567 $body = html_entity_decode(BBCode::toMarkdown($body));
3570 if (strlen($title)) {
3571 $body = "### ".html_entity_decode($title)."\n\n".$body;
3574 if ($item["attach"]) {
3575 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3577 $body .= "\n".L10n::t("Attachments:")."\n";
3578 foreach ($matches as $mtch) {
3579 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3586 if ($item["location"] != "")
3587 $location["address"] = $item["location"];
3589 if ($item["coord"] != "") {
3590 $coord = explode(" ", $item["coord"]);
3591 $location["lat"] = $coord[0];
3592 $location["lng"] = $coord[1];
3595 $message = ["author" => $myaddr,
3596 "guid" => $item["guid"],
3597 "created_at" => $created,
3598 "edited_at" => $edited,
3599 "public" => $public,
3601 "provider_display_name" => $item["app"],
3602 "location" => $location];
3604 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3605 if (!isset($location["lat"]) || !isset($location["lng"])) {
3606 unset($message["location"]);
3609 if ($item['event-id'] > 0) {
3610 $event = self::buildEvent($item['event-id']);
3611 if (count($event)) {
3612 $message['event'] = $event;
3614 if (!empty($event['location']['address']) &&
3615 !empty($event['location']['lat']) &&
3616 !empty($event['location']['lng'])) {
3617 $message['location'] = $event['location'];
3620 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3621 // $message['text'] = '';
3625 $type = "status_message";
3628 $msg = ["type" => $type, "message" => $message];
3630 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3635 private static function prependParentAuthorMention($body, $profile_url)
3637 $profile = Contact::getDetailsByURL($profile_url);
3638 if (!empty($profile['addr'])
3639 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3640 && !strstr($body, $profile['addr'])
3641 && !strstr($body, $profile_url)
3643 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3650 * @brief Sends a post
3652 * @param array $item The item that will be exported
3653 * @param array $owner the array of the item owner
3654 * @param array $contact Target of the communication
3655 * @param bool $public_batch Is it a public post?
3657 * @return int The result of the transmission
3658 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3659 * @throws \ImagickException
3661 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3663 $status = self::buildStatus($item, $owner);
3665 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3669 * @brief Creates a "like" object
3671 * @param array $item The item that will be exported
3672 * @param array $owner the array of the item owner
3674 * @return array The data for a "like"
3675 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3677 private static function constructLike(array $item, array $owner)
3679 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3680 if (!DBA::isResult($parent)) {
3684 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3686 if ($item['verb'] === Activity::LIKE) {
3688 } elseif ($item['verb'] === Activity::DISLIKE) {
3689 $positive = "false";
3692 return(["author" => self::myHandle($owner),
3693 "guid" => $item["guid"],
3694 "parent_guid" => $parent["guid"],
3695 "parent_type" => $target_type,
3696 "positive" => $positive,
3697 "author_signature" => ""]);
3701 * @brief Creates an "EventParticipation" object
3703 * @param array $item The item that will be exported
3704 * @param array $owner the array of the item owner
3706 * @return array The data for an "EventParticipation"
3707 * @throws \Exception
3709 private static function constructAttend(array $item, array $owner)
3711 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3712 if (!DBA::isResult($parent)) {
3716 switch ($item['verb']) {
3717 case Activity::ATTEND:
3718 $attend_answer = 'accepted';
3720 case Activity::ATTENDNO:
3721 $attend_answer = 'declined';
3723 case Activity::ATTENDMAYBE:
3724 $attend_answer = 'tentative';
3727 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3731 return(["author" => self::myHandle($owner),
3732 "guid" => $item["guid"],
3733 "parent_guid" => $parent["guid"],
3734 "status" => $attend_answer,
3735 "author_signature" => ""]);
3739 * @brief Creates the object for a comment
3741 * @param array $item The item that will be exported
3742 * @param array $owner the array of the item owner
3744 * @return array|false The data for a comment
3745 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3747 private static function constructComment(array $item, array $owner)
3749 $cachekey = "diaspora:constructComment:".$item['guid'];
3751 $result = DI::cache()->get($cachekey);
3752 if (!is_null($result)) {
3756 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3757 if (!DBA::isResult($toplevel_item)) {
3758 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3762 $thread_parent_item = $toplevel_item;
3763 if ($item['thr-parent'] != $item['parent-uri']) {
3764 $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3767 $body = $item["body"];
3769 // The replied to autor mention is prepended for clarity if:
3770 // - Item replied isn't yours
3771 // - Item is public or explicit mentions are disabled
3772 // - Implicit mentions are enabled
3774 $item['author-id'] != $thread_parent_item['author-id']
3775 && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3776 && !Config::get('system', 'disable_implicit_mentions')
3778 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3781 $text = html_entity_decode(BBCode::toMarkdown($body));
3782 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3783 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3786 "author" => self::myHandle($owner),
3787 "guid" => $item["guid"],
3788 "created_at" => $created,
3789 "edited_at" => $edited,
3790 "parent_guid" => $toplevel_item["guid"],
3792 "author_signature" => ""
3795 // Send the thread parent guid only if it is a threaded comment
3796 if ($item['thr-parent'] != $item['parent-uri']) {
3797 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3800 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3806 * @brief Send a like or a comment
3808 * @param array $item The item that will be exported
3809 * @param array $owner the array of the item owner
3810 * @param array $contact Target of the communication
3811 * @param bool $public_batch Is it a public post?
3813 * @return int The result of the transmission
3814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3815 * @throws \ImagickException
3817 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3819 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3820 $message = self::constructAttend($item, $owner);
3821 $type = "event_participation";
3822 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3823 $message = self::constructLike($item, $owner);
3825 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3826 $message = self::constructComment($item, $owner);
3830 if (empty($message)) {
3834 $message["author_signature"] = self::signature($owner, $message);
3836 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3840 * @brief Creates a message from a signature record entry
3842 * @param array $item The item that will be exported
3843 * @return array The message
3845 private static function messageFromSignature(array $item)
3847 // Split the signed text
3848 $signed_parts = explode(";", $item['signed_text']);
3850 if ($item["deleted"]) {
3851 $message = ["author" => $item['signer'],
3852 "target_guid" => $signed_parts[0],
3853 "target_type" => $signed_parts[1]];
3854 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3855 $message = ["author" => $signed_parts[4],
3856 "guid" => $signed_parts[1],
3857 "parent_guid" => $signed_parts[3],
3858 "parent_type" => $signed_parts[2],
3859 "positive" => $signed_parts[0],
3860 "author_signature" => $item['signature'],
3861 "parent_author_signature" => ""];
3863 // Remove the comment guid
3864 $guid = array_shift($signed_parts);
3866 // Remove the parent guid
3867 $parent_guid = array_shift($signed_parts);
3869 // Remove the handle
3870 $handle = array_pop($signed_parts);
3873 "author" => $handle,
3875 "parent_guid" => $parent_guid,
3876 "text" => implode(";", $signed_parts),
3877 "author_signature" => $item['signature'],
3878 "parent_author_signature" => ""
3885 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3887 * @param array $item The item that will be exported
3888 * @param array $owner the array of the item owner
3889 * @param array $contact Target of the communication
3890 * @param bool $public_batch Is it a public post?
3892 * @return int The result of the transmission
3893 * @throws \Exception
3895 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3897 if ($item["deleted"]) {
3898 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3899 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3905 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3907 // Old way - is used by the internal Friendica functions
3908 /// @todo Change all signatur storing functions to the new format
3909 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
3910 $message = self::messageFromSignature($item);
3912 $msg = json_decode($item['signed_text'], true);
3915 if (is_array($msg)) {
3916 foreach ($msg as $field => $data) {
3917 if (!$item["deleted"]) {
3918 if ($field == "diaspora_handle") {
3921 if ($field == "target_type") {
3922 $field = "parent_type";
3926 $message[$field] = $data;
3929 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3933 $message["parent_author_signature"] = self::signature($owner, $message);
3935 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
3937 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3941 * @brief Sends a retraction (deletion) of a message, like or comment
3943 * @param array $item The item that will be exported
3944 * @param array $owner the array of the item owner
3945 * @param array $contact Target of the communication
3946 * @param bool $public_batch Is it a public post?
3947 * @param bool $relay Is the retraction transmitted from a relay?
3949 * @return int The result of the transmission
3950 * @throws \Exception
3952 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3954 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3956 $msg_type = "retraction";
3958 if ($item['id'] == $item['parent']) {
3959 $target_type = "Post";
3960 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3961 $target_type = "Like";
3963 $target_type = "Comment";
3966 $message = ["author" => $itemaddr,
3967 "target_guid" => $item['guid'],
3968 "target_type" => $target_type];
3970 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
3972 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3976 * @brief Sends a mail
3978 * @param array $item The item that will be exported
3979 * @param array $owner The owner
3980 * @param array $contact Target of the communication
3982 * @return int The result of the transmission
3983 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3984 * @throws \ImagickException
3986 public static function sendMail(array $item, array $owner, array $contact)
3988 $myaddr = self::myHandle($owner);
3990 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3991 if (!DBA::isResult($cnv)) {
3992 Logger::log("conversation not found.");
3996 $body = BBCode::toMarkdown($item["body"]);
3997 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4000 "author" => $myaddr,
4001 "guid" => $item["guid"],
4002 "conversation_guid" => $cnv["guid"],
4004 "created_at" => $created,
4007 if ($item["reply"]) {
4012 "author" => $cnv["creator"],
4013 "guid" => $cnv["guid"],
4014 "subject" => $cnv["subject"],
4015 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4016 "participants" => $cnv["recips"],
4020 $type = "conversation";
4023 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4027 * @brief Split a name into first name and last name
4029 * @param string $name The name
4031 * @return array The array with "first" and "last"
4033 public static function splitName($name) {
4034 $name = trim($name);
4036 // Is the name longer than 64 characters? Then cut the rest of it.
4037 if (strlen($name) > 64) {
4038 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4039 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4041 $name = substr($name, 0, 64);
4045 // Take the first word as first name
4046 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4047 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4048 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4049 return ['first' => $first, 'last' => $last];
4052 // Take the last word as last name
4053 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4054 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4056 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4057 return ['first' => $first, 'last' => $last];
4060 // Take the first 32 characters if there is no space in the first 32 characters
4061 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4062 $first = substr($name, 0, 32);
4063 $last = substr($name, 32);
4064 return ['first' => $first, 'last' => $last];
4067 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4068 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4070 // Check if the last name is longer than 32 characters
4071 if (strlen($last) > 32) {
4072 if (strpos($last, ' ') <= 32) {
4073 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4075 $last = substr($last, 0, 32);
4079 return ['first' => $first, 'last' => $last];
4083 * @brief Create profile data
4085 * @param int $uid The user id
4087 * @return array The profile data
4088 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4090 private static function createProfileData($uid)
4093 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4095 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4096 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4097 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4106 $handle = $profile["addr"];
4108 $split_name = self::splitName($profile['name']);
4109 $first = $split_name['first'];
4110 $last = $split_name['last'];
4112 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4113 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4114 $small = DI::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4115 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4121 if ($searchable === 'true') {
4124 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4125 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4129 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4132 $about = $profile['about'];
4133 $about = strip_tags(BBCode::convert($about));
4135 $location = Profile::formatLocation($profile);
4137 if ($profile['pub_keywords']) {
4138 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4139 $kw = str_replace(' ', ' ', $kw);
4140 $arr = explode(' ', $kw);
4142 for ($x = 0; $x < 5; $x ++) {
4143 if (!empty($arr[$x])) {
4144 $tags .= '#'. trim($arr[$x]) .' ';
4149 $tags = trim($tags);
4152 return ["author" => $handle,
4153 "first_name" => $first,
4154 "last_name" => $last,
4155 "image_url" => $large,
4156 "image_url_medium" => $medium,
4157 "image_url_small" => $small,
4159 "gender" => $profile['gender'],
4161 "location" => $location,
4162 "searchable" => $searchable,
4164 "tag_string" => $tags];
4168 * @brief Sends profile data
4170 * @param int $uid The user id
4171 * @param bool $recips optional, default false
4173 * @throws \Exception
4175 public static function sendProfile($uid, $recips = false)
4181 $owner = User::getOwnerDataById($uid);
4188 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4189 AND `uid` = %d AND `rel` != %d",
4190 DBA::escape(Protocol::DIASPORA),
4192 intval(Contact::SHARING)
4200 $message = self::createProfileData($uid);
4202 // @ToDo Split this into single worker jobs
4203 foreach ($recips as $recip) {
4204 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4205 self::buildAndTransmit($owner, $recip, "profile", $message);
4210 * @brief Creates the signature for likes that are created on our system
4212 * @param integer $uid The user of that comment
4213 * @param array $item Item array
4215 * @return array Signed content
4216 * @throws \Exception
4218 public static function createLikeSignature($uid, array $item)
4220 $owner = User::getOwnerDataById($uid);
4221 if (empty($owner)) {
4222 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4226 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4230 $message = self::constructLike($item, $owner);
4231 if ($message === false) {
4235 $message["author_signature"] = self::signature($owner, $message);
4241 * @brief Creates the signature for Comments that are created on our system
4243 * @param integer $uid The user of that comment
4244 * @param array $item Item array
4246 * @return array Signed content
4247 * @throws \Exception
4249 public static function createCommentSignature($uid, array $item)
4251 $owner = User::getOwnerDataById($uid);
4252 if (empty($owner)) {
4253 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4257 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4258 $item['thr-parent'] = $item['parent-uri'];
4260 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4261 if (!DBA::isResult($parent)) {
4265 $item['parent-uri'] = $parent['parent-uri'];
4267 $message = self::constructComment($item, $owner);
4268 if ($message === false) {
4272 $message["author_signature"] = self::signature($owner, $message);