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;
17 use Friendica\Core\Config;
18 use Friendica\Core\L10n;
19 use Friendica\Core\Logger;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Conversation;
27 use Friendica\Model\GContact;
28 use Friendica\Model\Group;
29 use Friendica\Model\Item;
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 * @brief Return a list of relay servers
52 * The list contains not only the official relays but also servers that we serve directly
54 * @param integer $item_id The id of the item that is sent
55 * @param array $contacts The previously fetched contacts
57 * @return array of relay servers
58 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
60 public static function relayList($item_id, array $contacts = [])
64 // Fetching relay servers
65 $serverdata = Config::get("system", "relay_server");
67 if (!empty($serverdata)) {
68 $servers = explode(",", $serverdata);
69 foreach ($servers as $server) {
70 $serverlist[$server] = trim($server);
74 if (Config::get("system", "relay_directly", false)) {
75 // We distribute our stuff based on the parent to ensure that the thread will be complete
76 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
77 if (!DBA::isResult($parent)) {
81 // Servers that want to get all content
82 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
83 while ($server = DBA::fetch($servers)) {
84 $serverlist[$server['url']] = $server['url'];
87 // All tags of the current post
88 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
89 $tags = DBA::select('term', ['term'], $condition);
91 while ($tag = DBA::fetch($tags)) {
92 $taglist[] = $tag['term'];
95 // All servers who wants content with this tag
97 if (!empty($taglist)) {
98 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
99 while ($server = DBA::fetch($tagserver)) {
100 $tagserverlist[] = $server['gserver-id'];
104 // All adresses with the given id
105 if (!empty($tagserverlist)) {
106 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
107 while ($server = DBA::fetch($servers)) {
108 $serverlist[$server['url']] = $server['url'];
113 // Now we are collecting all relay contacts
114 foreach ($serverlist as $server_url) {
115 // We don't send messages to ourselves
116 if (Strings::compareLink($server_url, System::baseUrl())) {
119 $contact = self::getRelayContact($server_url);
120 if (is_bool($contact)) {
125 foreach ($contacts as $entry) {
126 if ($entry['batch'] == $contact['batch']) {
132 $contacts[] = $contact;
140 * @brief Return a contact for a given server address or creates a dummy entry
142 * @param string $server_url The url of the server
143 * @return array with the contact
146 private static function getRelayContact($server_url)
148 $fields = ['batch', 'id', 'name', 'network', 'protocol', 'archive', 'blocked'];
150 // Fetch the relay contact
151 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
152 'contact-type' => Contact::TYPE_RELAY];
153 $contact = DBA::selectFirst('contact', $fields, $condition);
155 if (DBA::isResult($contact)) {
156 if ($contact['archive'] || $contact['blocked']) {
161 self::setRelayContact($server_url);
163 $contact = DBA::selectFirst('contact', $fields, $condition);
164 if (DBA::isResult($contact)) {
169 // It should never happen that we arrive here
174 * @brief Update or insert a relay contact
176 * @param string $server_url The url of the server
177 * @param array $network_fields Optional network specific fields
180 public static function setRelayContact($server_url, array $network_fields = [])
182 $fields = ['created' => DateTimeFormat::utcNow(),
183 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
184 'nurl' => Strings::normaliseLink($server_url),
185 'network' => Protocol::DIASPORA, 'uid' => 0,
186 'batch' => $server_url . '/receive/public',
187 'rel' => Contact::FOLLOWER, 'blocked' => false,
188 'pending' => false, 'writable' => true,
189 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
191 $fields = array_merge($fields, $network_fields);
193 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
194 $old = DBA::selectFirst('contact', [], $condition);
195 if (DBA::isResult($old)) {
196 unset($fields['created']);
197 $condition = ['id' => $old['id']];
199 Logger::info('Update relay contact', ['fields' => $fields, 'condition' => $condition]);
200 DBA::update('contact', $fields, $condition, $old);
202 Logger::info('Create relay contact', ['fields' => $fields]);
203 DBA::insert('contact', $fields);
208 * @brief Return a list of participating contacts for a thread
210 * This is used for the participation feature.
211 * One of the parameters is a contact array.
212 * This is done to avoid duplicates.
214 * @param integer $thread The id of the thread
215 * @param array $contacts The previously fetched contacts
217 * @return array of relay servers
220 public static function participantsForThread($thread, array $contacts)
222 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`, `contact`.`protocol`,
223 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
224 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
225 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
226 WHERE `participation`.`iid` = ?", $thread);
228 while ($contact = DBA::fetch($r)) {
229 if (!empty($contact['fnetwork'])) {
230 $contact['network'] = $contact['fnetwork'];
232 unset($contact['fnetwork']);
234 if (empty($contact['protocol'])) {
235 $contact['protocol'] = $contact['network'];
238 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
239 $contact['batch'] = $contact['fbatch'];
241 unset($contact['fbatch']);
244 foreach ($contacts as $entry) {
245 if ($entry['batch'] == $contact['batch']) {
251 $contacts[] = $contact;
260 * @brief repairs a signature that was double encoded
262 * The function is unused at the moment. It was copied from the old implementation.
264 * @param string $signature The signature
265 * @param string $handle The handle of the signature owner
266 * @param integer $level This value is only set inside this function to avoid endless loops
268 * @return string the repaired signature
271 private static function repairSignature($signature, $handle = "", $level = 1)
273 if ($signature == "") {
277 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
278 $signature = base64_decode($signature);
279 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
281 // Do a recursive call to be able to fix even multiple levels
283 $signature = self::repairSignature($signature, $handle, ++$level);
291 * @brief verify the envelope and return the verified data
293 * @param string $envelope The magic envelope
295 * @return string verified data
296 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 * @throws \ImagickException
299 private static function verifyMagicEnvelope($envelope)
301 $basedom = XML::parseString($envelope);
303 if (!is_object($basedom)) {
304 Logger::log("Envelope is no XML file");
308 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
310 if (sizeof($children) == 0) {
311 Logger::log("XML has no children");
317 $data = Strings::base64UrlDecode($children->data);
318 $type = $children->data->attributes()->type[0];
320 $encoding = $children->encoding;
322 $alg = $children->alg;
324 $sig = Strings::base64UrlDecode($children->sig);
325 $key_id = $children->sig->attributes()->key_id[0];
327 $handle = Strings::base64UrlDecode($key_id);
330 $b64url_data = Strings::base64UrlEncode($data);
331 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
333 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
336 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
340 $key = self::key($handle);
342 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
346 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
348 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
356 * @brief encrypts data via AES
358 * @param string $key The AES key
359 * @param string $iv The IV (is used for CBC encoding)
360 * @param string $data The data that is to be encrypted
362 * @return string encrypted data
364 private static function aesEncrypt($key, $iv, $data)
366 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
370 * @brief decrypts data via AES
372 * @param string $key The AES key
373 * @param string $iv The IV (is used for CBC encoding)
374 * @param string $encrypted The encrypted data
376 * @return string decrypted data
378 private static function aesDecrypt($key, $iv, $encrypted)
380 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
384 * @brief: Decodes incoming Diaspora message in the new format
386 * @param array $importer Array of the importer user
387 * @param string $raw raw post message
388 * @param boolean $no_exit Don't do an http exit on error
391 * 'message' -> decoded Diaspora XML message
392 * 'author' -> author diaspora handle
393 * 'key' -> author public key (converted to pkcs#8)
394 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
395 * @throws \ImagickException
397 public static function decodeRaw(array $importer, $raw, $no_exit = false)
399 $data = json_decode($raw);
401 // Is it a private post? Then decrypt the outer Salmon
402 if (is_object($data)) {
403 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
404 $ciphertext = base64_decode($data->encrypted_magic_envelope);
406 $outer_key_bundle = '';
407 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
408 $j_outer_key_bundle = json_decode($outer_key_bundle);
410 if (!is_object($j_outer_key_bundle)) {
411 Logger::log('Outer Salmon did not verify. Discarding.');
415 throw new \Friendica\Network\HTTPException\BadRequestException();
419 $outer_iv = base64_decode($j_outer_key_bundle->iv);
420 $outer_key = base64_decode($j_outer_key_bundle->key);
422 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
427 $basedom = XML::parseString($xml);
429 if (!is_object($basedom)) {
430 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
434 throw new \Friendica\Network\HTTPException\BadRequestException();
438 $base = $basedom->children(NAMESPACE_SALMON_ME);
440 // Not sure if this cleaning is needed
441 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
443 // Build the signed data
444 $type = $base->data[0]->attributes()->type[0];
445 $encoding = $base->encoding;
447 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
449 // This is the signature
450 $signature = Strings::base64UrlDecode($base->sig);
452 // Get the senders' public key
453 $key_id = $base->sig[0]->attributes()->key_id[0];
454 $author_addr = base64_decode($key_id);
455 if ($author_addr == '') {
456 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
460 throw new \Friendica\Network\HTTPException\BadRequestException();
464 $key = self::key($author_addr);
466 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
470 throw new \Friendica\Network\HTTPException\BadRequestException();
474 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
476 Logger::log('Message did not verify. Discarding.');
480 throw new \Friendica\Network\HTTPException\BadRequestException();
484 return ['message' => (string)Strings::base64UrlDecode($base->data),
485 'author' => XML::unescape($author_addr),
486 'key' => (string)$key];
490 * @brief: Decodes incoming Diaspora message in the deprecated format
492 * @param array $importer Array of the importer user
493 * @param string $xml urldecoded Diaspora salmon
496 * 'message' -> decoded Diaspora XML message
497 * 'author' -> author diaspora handle
498 * 'key' -> author public key (converted to pkcs#8)
499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
500 * @throws \ImagickException
502 public static function decode(array $importer, $xml)
505 $basedom = XML::parseString($xml);
507 if (!is_object($basedom)) {
508 Logger::log("XML is not parseable.");
511 $children = $basedom->children('https://joindiaspora.com/protocol');
513 $inner_aes_key = null;
516 if ($children->header) {
518 $author_link = str_replace('acct:', '', $children->header->author_id);
520 // This happens with posts from a relais
522 Logger::log("This is no private post in the old format", Logger::DEBUG);
526 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
528 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
529 $ciphertext = base64_decode($encrypted_header->ciphertext);
531 $outer_key_bundle = '';
532 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
534 $j_outer_key_bundle = json_decode($outer_key_bundle);
536 $outer_iv = base64_decode($j_outer_key_bundle->iv);
537 $outer_key = base64_decode($j_outer_key_bundle->key);
539 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
541 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
542 $idom = XML::parseString($decrypted);
544 $inner_iv = base64_decode($idom->iv);
545 $inner_aes_key = base64_decode($idom->aes_key);
547 $author_link = str_replace('acct:', '', $idom->author_id);
550 $dom = $basedom->children(NAMESPACE_SALMON_ME);
552 // figure out where in the DOM tree our data is hiding
555 if ($dom->provenance->data) {
556 $base = $dom->provenance;
557 } elseif ($dom->env->data) {
559 } elseif ($dom->data) {
564 Logger::log('unable to locate salmon data in xml');
565 throw new \Friendica\Network\HTTPException\BadRequestException();
569 // Stash the signature away for now. We have to find their key or it won't be good for anything.
570 $signature = Strings::base64UrlDecode($base->sig);
574 // strip whitespace so our data element will return to one big base64 blob
575 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
578 // stash away some other stuff for later
580 $type = $base->data[0]->attributes()->type[0];
581 $keyhash = $base->sig[0]->attributes()->keyhash[0];
582 $encoding = $base->encoding;
586 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
590 $data = Strings::base64UrlDecode($data);
594 $inner_decrypted = $data;
596 // Decode the encrypted blob
597 $inner_encrypted = base64_decode($data);
598 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
602 Logger::log('Could not retrieve author URI.');
603 throw new \Friendica\Network\HTTPException\BadRequestException();
605 // Once we have the author URI, go to the web and try to find their public key
606 // (first this will look it up locally if it is in the fcontact cache)
607 // This will also convert diaspora public key from pkcs#1 to pkcs#8
609 Logger::log('Fetching key for '.$author_link);
610 $key = self::key($author_link);
613 Logger::log('Could not retrieve author key.');
614 throw new \Friendica\Network\HTTPException\BadRequestException();
617 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
620 Logger::log('Message did not verify. Discarding.');
621 throw new \Friendica\Network\HTTPException\BadRequestException();
624 Logger::log('Message verified.');
626 return ['message' => (string)$inner_decrypted,
627 'author' => XML::unescape($author_link),
628 'key' => (string)$key];
633 * @brief Dispatches public messages and find the fitting receivers
635 * @param array $msg The post that will be dispatched
637 * @return int The message id of the generated message, "true" or "false" if there was an error
638 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
639 * @throws \ImagickException
641 public static function dispatchPublic($msg)
643 $enabled = intval(Config::get("system", "diaspora_enabled"));
645 Logger::log("diaspora is disabled");
649 if (!($fields = self::validPosting($msg))) {
650 Logger::log("Invalid posting");
654 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
655 $success = self::dispatch($importer, $msg, $fields);
661 * @brief Dispatches the different message types to the different functions
663 * @param array $importer Array of the importer user
664 * @param array $msg The post that will be dispatched
665 * @param SimpleXMLElement $fields SimpleXML object that contains the message
667 * @return int The message id of the generated message, "true" or "false" if there was an error
668 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
669 * @throws \ImagickException
671 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
673 // The sender is the handle of the contact that sent the message.
674 // This will often be different with relayed messages (for example "like" and "comment")
675 $sender = $msg["author"];
677 // This is only needed for private postings since this is already done for public ones before
678 if (is_null($fields)) {
680 if (!($fields = self::validPosting($msg))) {
681 Logger::log("Invalid posting");
688 $type = $fields->getName();
690 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
693 case "account_migration":
695 Logger::log('Message with type ' . $type . ' is not private, quitting.');
698 return self::receiveAccountMigration($importer, $fields);
700 case "account_deletion":
701 return self::receiveAccountDeletion($fields);
704 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
708 Logger::log('Message with type ' . $type . ' is not private, quitting.');
711 return self::receiveContactRequest($importer, $fields);
715 Logger::log('Message with type ' . $type . ' is not private, quitting.');
718 return self::receiveConversation($importer, $msg, $fields);
721 return self::receiveLike($importer, $sender, $fields);
725 Logger::log('Message with type ' . $type . ' is not private, quitting.');
728 return self::receiveMessage($importer, $fields);
730 case "participation":
732 Logger::log('Message with type ' . $type . ' is not private, quitting.');
735 return self::receiveParticipation($importer, $fields);
737 case "photo": // Not implemented
738 return self::receivePhoto($importer, $fields);
740 case "poll_participation": // Not implemented
741 return self::receivePollParticipation($importer, $fields);
745 Logger::log('Message with type ' . $type . ' is not private, quitting.');
748 return self::receiveProfile($importer, $fields);
751 return self::receiveReshare($importer, $fields, $msg["message"]);
754 return self::receiveRetraction($importer, $sender, $fields);
756 case "status_message":
757 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
760 Logger::log("Unknown message type ".$type);
766 * @brief Checks if a posting is valid and fetches the data fields.
768 * This function does not only check the signature.
769 * It also does the conversion between the old and the new diaspora format.
771 * @param array $msg Array with the XML, the sender handle and the sender signature
773 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
774 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
775 * @throws \ImagickException
777 private static function validPosting($msg)
779 $data = XML::parseString($msg["message"]);
781 if (!is_object($data)) {
782 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
786 // Is this the new or the old version?
787 if ($data->getName() == "XML") {
789 foreach ($data->post->children() as $child) {
797 $type = $element->getName();
800 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
802 // All retractions are handled identically from now on.
803 // In the new version there will only be "retraction".
804 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
805 $type = "retraction";
807 if ($type == "request") {
811 $fields = new SimpleXMLElement("<".$type."/>");
814 $author_signature = null;
815 $parent_author_signature = null;
817 foreach ($element->children() as $fieldname => $entry) {
819 // Translation for the old XML structure
820 if ($fieldname == "diaspora_handle") {
821 $fieldname = "author";
823 if ($fieldname == "participant_handles") {
824 $fieldname = "participants";
826 if (in_array($type, ["like", "participation"])) {
827 if ($fieldname == "target_type") {
828 $fieldname = "parent_type";
831 if ($fieldname == "sender_handle") {
832 $fieldname = "author";
834 if ($fieldname == "recipient_handle") {
835 $fieldname = "recipient";
837 if ($fieldname == "root_diaspora_id") {
838 $fieldname = "root_author";
840 if ($type == "status_message") {
841 if ($fieldname == "raw_message") {
845 if ($type == "retraction") {
846 if ($fieldname == "post_guid") {
847 $fieldname = "target_guid";
849 if ($fieldname == "type") {
850 $fieldname = "target_type";
855 if (($fieldname == "author_signature") && ($entry != "")) {
856 $author_signature = base64_decode($entry);
857 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
858 $parent_author_signature = base64_decode($entry);
859 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
860 if ($signed_data != "") {
864 $signed_data .= $entry;
866 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
867 || ($orig_type == "relayable_retraction")
869 XML::copy($entry, $fields, $fieldname);
873 // This is something that shouldn't happen at all.
874 if (in_array($type, ["status_message", "reshare", "profile"])) {
875 if ($msg["author"] != $fields->author) {
876 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
881 // Only some message types have signatures. So we quit here for the other types.
882 if (!in_array($type, ["comment", "like"])) {
885 // No author_signature? This is a must, so we quit.
886 if (!isset($author_signature)) {
887 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
891 if (isset($parent_author_signature)) {
892 $key = self::key($msg["author"]);
894 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
898 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
899 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);
904 $key = self::key($fields->author);
906 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
910 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
911 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);
919 * @brief Fetches the public key for a given handle
921 * @param string $handle The handle
923 * @return string The public key
924 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
925 * @throws \ImagickException
927 private static function key($handle)
929 $handle = strval($handle);
931 Logger::log("Fetching diaspora key for: ".$handle);
933 $r = self::personByHandle($handle);
942 * @brief Fetches data for a given handle
944 * @param string $handle The handle
946 * @return array the queried data
947 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
948 * @throws \ImagickException
950 public static function personByHandle($handle)
954 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
955 if (DBA::isResult($person)) {
956 Logger::debug("In cache " . print_r($person, true));
958 // update record occasionally so it doesn't get stale
959 $d = strtotime($person["updated"]." +00:00");
960 if ($d < strtotime("now - 14 days")) {
964 if ($person["guid"] == "") {
969 if (!DBA::isResult($person) || $update) {
970 Logger::log("create or refresh", Logger::DEBUG);
971 $r = Probe::uri($handle, Protocol::DIASPORA);
973 // Note that Friendica contacts will return a "Diaspora person"
974 // if Diaspora connectivity is enabled on their server
975 if ($r && ($r["network"] === Protocol::DIASPORA)) {
976 self::updateFContact($r);
978 // Fetch the updated or added contact
979 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
980 if (!DBA::isResult($person)) {
991 * @brief Updates the fcontact table
993 * @param array $arr The fcontact data
996 private static function updateFContact($arr)
998 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
999 'request' => $arr["request"], 'nick' => $arr["nick"],
1000 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
1001 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1002 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1003 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1004 'updated' => DateTimeFormat::utcNow()];
1006 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1008 DBA::update('fcontact', $fields, $condition, true);
1012 * @brief get a handle (user@domain.tld) from a given contact id
1014 * @param int $contact_id The id in the contact table
1015 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1017 * @return string the handle
1018 * @throws \Exception
1020 private static function handleFromContact($contact_id, $pcontact_id = 0)
1024 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1026 if ($pcontact_id != 0) {
1027 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1029 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1030 return strtolower($contact["addr"]);
1035 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1039 if (DBA::isResult($r)) {
1042 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1044 if ($contact['addr'] != "") {
1045 $handle = $contact['addr'];
1047 $baseurl_start = strpos($contact['url'], '://') + 3;
1048 // allows installations in a subdirectory--not sure how Diaspora will handle
1049 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1050 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1051 $handle = $contact['nick'].'@'.$baseurl;
1055 return strtolower($handle);
1059 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1062 * @param mixed $fcontact_guid Hexadecimal string guid
1064 * @return string the contact url or null
1065 * @throws \Exception
1067 public static function urlFromContactGuid($fcontact_guid)
1069 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1072 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1073 DBA::escape(Protocol::DIASPORA),
1074 DBA::escape($fcontact_guid)
1077 if (DBA::isResult($r)) {
1078 return $r[0]['url'];
1085 * @brief Get a contact id for a given handle
1087 * @todo Move to Friendica\Model\Contact
1089 * @param int $uid The user id
1090 * @param string $handle The handle in the format user@domain.tld
1092 * @return array Contact data
1093 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1094 * @throws \ImagickException
1096 private static function contactByHandle($uid, $handle)
1098 $cid = Contact::getIdForURL($handle, $uid);
1100 $handle_parts = explode("@", $handle);
1101 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1102 $cid = Contact::getIdForURL($nurl_sql, $uid);
1106 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1110 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1111 if (!DBA::isResult($contact)) {
1112 // This here shouldn't happen at all
1113 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1121 * @brief Check if posting is allowed for this contact
1123 * @param array $importer Array of the importer user
1124 * @param array $contact The contact that is checked
1125 * @param bool $is_comment Is the check for a comment?
1127 * @return bool is the contact allowed to post?
1129 private static function postAllow(array $importer, array $contact, $is_comment = false)
1132 * Perhaps we were already sharing with this person. Now they're sharing with us.
1133 * That makes us friends.
1134 * Normally this should have handled by getting a request - but this could get lost
1136 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1137 // It is not removed by now. Possibly the code is needed?
1138 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1141 // array('rel' => Contact::FRIEND, 'writable' => true),
1142 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1145 // $contact["rel"] = Contact::FRIEND;
1146 // Logger::log("defining user ".$contact["nick"]." as friend");
1149 // Contact server is blocked
1150 if (Network::isUrlBlocked($contact['url'])) {
1152 // We don't seem to like that person
1153 } elseif ($contact["blocked"]) {
1154 // Maybe blocked, don't accept.
1156 // We are following this person?
1157 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1158 // Yes, then it is fine.
1160 // Is it a post to a community?
1161 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1164 // Is the message a global user or a comment?
1165 } elseif (($importer["uid"] == 0) || $is_comment) {
1166 // Messages for the global users and comments are always accepted
1174 * @brief Fetches the contact id for a handle and checks if posting is allowed
1176 * @param array $importer Array of the importer user
1177 * @param string $handle The checked handle in the format user@domain.tld
1178 * @param bool $is_comment Is the check for a comment?
1180 * @return array The contact data
1181 * @throws \Exception
1183 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1185 $contact = self::contactByHandle($importer["uid"], $handle);
1187 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1188 // If a contact isn't found, we accept it anyway if it is a comment
1189 if ($is_comment && ($importer["uid"] != 0)) {
1190 return self::contactByHandle(0, $handle);
1191 } elseif ($is_comment) {
1198 if (!self::postAllow($importer, $contact, $is_comment)) {
1199 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1206 * @brief Does the message already exists on the system?
1208 * @param int $uid The user id
1209 * @param string $guid The guid of the message
1211 * @return int|bool message id if the message already was stored into the system - or false.
1212 * @throws \Exception
1214 private static function messageExists($uid, $guid)
1216 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1217 if (DBA::isResult($item)) {
1218 Logger::log("message ".$guid." already exists for user ".$uid);
1226 * @brief Checks for links to posts in a message
1228 * @param array $item The item array
1231 private static function fetchGuid(array $item)
1233 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1234 preg_replace_callback(
1236 function ($match) use ($item) {
1237 self::fetchGuidSub($match, $item);
1242 preg_replace_callback(
1243 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1244 function ($match) use ($item) {
1245 self::fetchGuidSub($match, $item);
1252 * @brief Checks for relative /people/* links in an item body to match local
1253 * contacts or prepends the remote host taken from the author link.
1255 * @param string $body The item body to replace links from
1256 * @param string $author_link The author link for missing local contact fallback
1258 * @return string the replaced string
1260 public static function replacePeopleGuid($body, $author_link)
1262 $return = preg_replace_callback(
1263 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1264 function ($match) use ($author_link) {
1266 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1267 // 1 => '0123456789abcdef'
1269 $handle = self::urlFromContactGuid($match[1]);
1272 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1274 // No local match, restoring absolute remote URL from author scheme and host
1275 $author_url = parse_url($author_link);
1276 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1288 * @brief sub function of "fetchGuid" which checks for links in messages
1290 * @param array $match array containing a link that has to be checked for a message link
1291 * @param array $item The item array
1293 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1294 * @throws \ImagickException
1296 private static function fetchGuidSub($match, $item)
1298 if (!self::storeByGuid($match[1], $item["author-link"])) {
1299 self::storeByGuid($match[1], $item["owner-link"]);
1304 * @brief Fetches an item with a given guid from a given server
1306 * @param string $guid the message guid
1307 * @param string $server The server address
1308 * @param int $uid The user id of the user
1310 * @return int the message id of the stored message or false
1311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1312 * @throws \ImagickException
1314 private static function storeByGuid($guid, $server, $uid = 0)
1316 $serverparts = parse_url($server);
1318 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1322 $server = $serverparts["scheme"]."://".$serverparts["host"];
1324 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1326 $msg = self::message($guid, $server);
1332 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1334 // Now call the dispatcher
1335 return self::dispatchPublic($msg);
1339 * @brief Fetches a message from a server
1341 * @param string $guid message guid
1342 * @param string $server The url of the server
1343 * @param int $level Endless loop prevention
1346 * 'message' => The message XML
1347 * 'author' => The author handle
1348 * 'key' => The public key of the author
1349 * @throws \Exception
1351 private static function message($guid, $server, $level = 0)
1357 // This will work for new Diaspora servers and Friendica servers from 3.5
1358 $source_url = $server."/fetch/post/".urlencode($guid);
1360 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1362 $envelope = Network::fetchUrl($source_url);
1364 Logger::log("Envelope was fetched.", Logger::DEBUG);
1365 $x = self::verifyMagicEnvelope($envelope);
1367 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1369 Logger::log("Envelope was verified.", Logger::DEBUG);
1379 $source_xml = XML::parseString($x);
1381 if (!is_object($source_xml)) {
1385 if ($source_xml->post->reshare) {
1386 // Reshare of a reshare - old Diaspora version
1387 Logger::log("Message is a reshare", Logger::DEBUG);
1388 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1389 } elseif ($source_xml->getName() == "reshare") {
1390 // Reshare of a reshare - new Diaspora version
1391 Logger::log("Message is a new reshare", Logger::DEBUG);
1392 return self::message($source_xml->root_guid, $server, ++$level);
1397 // Fetch the author - for the old and the new Diaspora version
1398 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1399 $author = (string)$source_xml->post->status_message->diaspora_handle;
1400 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1401 $author = (string)$source_xml->author;
1404 // If this isn't a "status_message" then quit
1406 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1410 $msg = ["message" => $x, "author" => $author];
1412 $msg["key"] = self::key($msg["author"]);
1418 * @brief Fetches the item record of a given guid
1420 * @param int $uid The user id
1421 * @param string $guid message guid
1422 * @param string $author The handle of the item
1423 * @param array $contact The contact of the item owner
1425 * @return array the item record
1426 * @throws \Exception
1428 private static function parentItem($uid, $guid, $author, array $contact)
1430 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1431 'author-name', 'author-link', 'author-avatar',
1432 'owner-name', 'owner-link', 'owner-avatar'];
1433 $condition = ['uid' => $uid, 'guid' => $guid];
1434 $item = Item::selectFirst($fields, $condition);
1436 if (!DBA::isResult($item)) {
1437 $person = self::personByHandle($author);
1438 $result = self::storeByGuid($guid, $person["url"], $uid);
1440 // We don't have an url for items that arrived at the public dispatcher
1441 if (!$result && !empty($contact["url"])) {
1442 $result = self::storeByGuid($guid, $contact["url"], $uid);
1446 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1448 $item = Item::selectFirst($fields, $condition);
1452 if (!DBA::isResult($item)) {
1453 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1456 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1462 * @brief returns contact details
1464 * @param array $def_contact The default contact if the person isn't found
1465 * @param array $person The record of the person
1466 * @param int $uid The user id
1469 * 'cid' => contact id
1470 * 'network' => network type
1471 * @throws \Exception
1473 private static function authorContactByUrl($def_contact, $person, $uid)
1475 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1476 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1477 if (DBA::isResult($contact)) {
1478 $cid = $contact["id"];
1479 $network = $contact["network"];
1481 $cid = $def_contact["id"];
1482 $network = Protocol::DIASPORA;
1485 return ["cid" => $cid, "network" => $network];
1489 * @brief Is the profile a hubzilla profile?
1491 * @param string $url The profile link
1493 * @return bool is it a hubzilla server?
1495 public static function isRedmatrix($url)
1497 return(strstr($url, "/channel/"));
1501 * @brief Generate a post link with a given handle and message guid
1503 * @param string $addr The user handle
1504 * @param string $guid message guid
1505 * @param string $parent_guid optional parent guid
1507 * @return string the post link
1508 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1509 * @throws \ImagickException
1511 private static function plink($addr, $guid, $parent_guid = '')
1513 $contact = Contact::getDetailsByAddr($addr);
1517 if ($parent_guid != '') {
1518 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1520 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1524 if ($contact["network"] == Protocol::DFRN) {
1525 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1528 if (self::isRedmatrix($contact["url"])) {
1529 return $contact["url"] . "/?f=&mid=" . $guid;
1532 if ($parent_guid != '') {
1533 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1535 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1540 * @brief Receives account migration
1542 * @param array $importer Array of the importer user
1543 * @param object $data The message object
1545 * @return bool Success
1546 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1547 * @throws \ImagickException
1549 private static function receiveAccountMigration(array $importer, $data)
1551 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1552 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1553 $signature = Strings::escapeTags(XML::unescape($data->signature));
1555 $contact = self::contactByHandle($importer["uid"], $old_handle);
1557 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1561 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1564 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1565 $key = self::key($old_handle);
1566 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1567 Logger::log('No valid signature for migration.');
1571 // Update the profile
1572 self::receiveProfile($importer, $data->profile);
1574 // change the technical stuff in contact and gcontact
1575 $data = Probe::uri($new_handle);
1576 if ($data['network'] == Protocol::PHANTOM) {
1577 Logger::log('Account for '.$new_handle." couldn't be probed.");
1581 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1582 'name' => $data['name'], 'nick' => $data['nick'],
1583 'addr' => $data['addr'], 'batch' => $data['batch'],
1584 'notify' => $data['notify'], 'poll' => $data['poll'],
1585 'network' => $data['network']];
1587 DBA::update('contact', $fields, ['addr' => $old_handle]);
1589 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1590 'name' => $data['name'], 'nick' => $data['nick'],
1591 'addr' => $data['addr'], 'connect' => $data['addr'],
1592 'notify' => $data['notify'], 'photo' => $data['photo'],
1593 'server_url' => $data['baseurl'], 'network' => $data['network']];
1595 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1597 Logger::log('Contacts are updated.');
1603 * @brief Processes an account deletion
1605 * @param object $data The message object
1607 * @return bool Success
1608 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1610 private static function receiveAccountDeletion($data)
1612 $author = Strings::escapeTags(XML::unescape($data->author));
1614 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1615 while ($contact = DBA::fetch($contacts)) {
1616 Contact::remove($contact["id"]);
1619 DBA::delete('gcontact', ['addr' => $author]);
1621 Logger::log('Removed contacts for ' . $author);
1627 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1629 * @param string $author Author handle
1630 * @param string $guid Message guid
1631 * @param boolean $onlyfound Only return uri when found in the database
1633 * @return string The constructed uri or the one from our database
1634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1635 * @throws \ImagickException
1637 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1639 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1640 if (DBA::isResult($item)) {
1641 return $item["uri"];
1642 } elseif (!$onlyfound) {
1643 $person = self::personByHandle($author);
1645 $parts = parse_url($person['url']);
1646 unset($parts['path']);
1647 $host_url = Network::unparseURL($parts);
1649 return $host_url . '/objects/' . $guid;
1656 * @brief Fetch the guid from our database with a given uri
1658 * @param string $uri Message uri
1659 * @param string $uid Author handle
1661 * @return string The post guid
1662 * @throws \Exception
1664 private static function getGuidFromUri($uri, $uid)
1666 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1667 if (DBA::isResult($item)) {
1668 return $item["guid"];
1675 * @brief Find the best importer for a comment, like, ...
1677 * @param string $guid The guid of the item
1679 * @return array|boolean the origin owner of that post - or false
1680 * @throws \Exception
1682 private static function importerForGuid($guid)
1684 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1685 if (DBA::isResult($item)) {
1686 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1687 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1688 if (DBA::isResult($contact)) {
1696 * @brief Processes an incoming comment
1698 * @param array $importer Array of the importer user
1699 * @param string $sender The sender of the message
1700 * @param object $data The message object
1701 * @param string $xml The original XML of the message
1703 * @return int The message id of the generated comment or "false" if there was an error
1704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1705 * @throws \ImagickException
1707 private static function receiveComment(array $importer, $sender, $data, $xml)
1709 $author = Strings::escapeTags(XML::unescape($data->author));
1710 $guid = Strings::escapeTags(XML::unescape($data->guid));
1711 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1712 $text = XML::unescape($data->text);
1714 if (isset($data->created_at)) {
1715 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1717 $created_at = DateTimeFormat::utcNow();
1720 if (isset($data->thread_parent_guid)) {
1721 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1722 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1727 $contact = self::allowedContactByHandle($importer, $sender, true);
1732 $message_id = self::messageExists($importer["uid"], $guid);
1737 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1738 if (!$parent_item) {
1742 $person = self::personByHandle($author);
1743 if (!is_array($person)) {
1744 Logger::log("unable to find author details");
1748 // Fetch the contact id - if we know this contact
1749 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1753 $datarray["uid"] = $importer["uid"];
1754 $datarray["contact-id"] = $author_contact["cid"];
1755 $datarray["network"] = $author_contact["network"];
1757 $datarray["author-link"] = $person["url"];
1758 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1760 $datarray["owner-link"] = $contact["url"];
1761 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1763 $datarray["guid"] = $guid;
1764 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1766 $datarray["verb"] = ACTIVITY_POST;
1767 $datarray["gravity"] = GRAVITY_COMMENT;
1769 if ($thr_uri != "") {
1770 $datarray["parent-uri"] = $thr_uri;
1772 $datarray["parent-uri"] = $parent_item["uri"];
1775 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1777 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1778 $datarray["source"] = $xml;
1780 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1782 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1784 $body = Markdown::toBBCode($text);
1786 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1788 self::fetchGuid($datarray);
1790 // If we are the origin of the parent we store the original data.
1791 // We notify our followers during the item storage.
1792 if ($parent_item["origin"]) {
1793 $datarray['diaspora_signed_text'] = json_encode($data);
1796 $message_id = Item::insert($datarray);
1798 if ($message_id <= 0) {
1803 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1804 if ($datarray['uid'] == 0) {
1805 Item::distribute($message_id, json_encode($data));
1813 * @brief processes and stores private messages
1815 * @param array $importer Array of the importer user
1816 * @param array $contact The contact of the message
1817 * @param object $data The message object
1818 * @param array $msg Array of the processed message, author handle and key
1819 * @param object $mesg The private message
1820 * @param array $conversation The conversation record to which this message belongs
1822 * @return bool "true" if it was successful
1823 * @throws \Exception
1825 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1827 $author = Strings::escapeTags(XML::unescape($data->author));
1828 $guid = Strings::escapeTags(XML::unescape($data->guid));
1829 $subject = Strings::escapeTags(XML::unescape($data->subject));
1831 // "diaspora_handle" is the element name from the old version
1832 // "author" is the element name from the new version
1833 if ($mesg->author) {
1834 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1835 } elseif ($mesg->diaspora_handle) {
1836 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1841 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1842 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1843 $msg_text = XML::unescape($mesg->text);
1844 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1846 if ($msg_conversation_guid != $guid) {
1847 Logger::log("message conversation guid does not belong to the current conversation.");
1851 $body = Markdown::toBBCode($msg_text);
1852 $message_uri = $msg_author.":".$msg_guid;
1854 $person = self::personByHandle($msg_author);
1856 return Mail::insert([
1857 'uid' => $importer['uid'],
1858 'guid' => $msg_guid,
1859 'convid' => $conversation['id'],
1860 'from-name' => $person['name'],
1861 'from-photo' => $person['photo'],
1862 'from-url' => $person['url'],
1863 'contact-id' => $contact['id'],
1864 'title' => $subject,
1866 'uri' => $message_uri,
1867 'parent-uri' => $author . ':' . $guid,
1868 'created' => $msg_created_at
1873 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1875 * @param array $importer Array of the importer user
1876 * @param array $msg Array of the processed message, author handle and key
1877 * @param object $data The message object
1879 * @return bool Success
1880 * @throws \Exception
1882 private static function receiveConversation(array $importer, $msg, $data)
1884 $author = Strings::escapeTags(XML::unescape($data->author));
1885 $guid = Strings::escapeTags(XML::unescape($data->guid));
1886 $subject = Strings::escapeTags(XML::unescape($data->subject));
1887 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1888 $participants = Strings::escapeTags(XML::unescape($data->participants));
1890 $messages = $data->message;
1892 if (!count($messages)) {
1893 Logger::log("empty conversation");
1897 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1902 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1903 if (!DBA::isResult($conversation)) {
1905 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1906 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1907 intval($importer["uid"]),
1909 DBA::escape($author),
1910 DBA::escape($created_at),
1911 DBA::escape(DateTimeFormat::utcNow()),
1912 DBA::escape($subject),
1913 DBA::escape($participants)
1916 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1919 if (!$conversation) {
1920 Logger::log("unable to create conversation.");
1924 foreach ($messages as $mesg) {
1925 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1932 * @brief Processes "like" messages
1934 * @param array $importer Array of the importer user
1935 * @param string $sender The sender of the message
1936 * @param object $data The message object
1938 * @return int The message id of the generated like or "false" if there was an error
1939 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1940 * @throws \ImagickException
1942 private static function receiveLike(array $importer, $sender, $data)
1944 $author = Strings::escapeTags(XML::unescape($data->author));
1945 $guid = Strings::escapeTags(XML::unescape($data->guid));
1946 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1947 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1948 $positive = Strings::escapeTags(XML::unescape($data->positive));
1950 // likes on comments aren't supported by Diaspora - only on posts
1951 // But maybe this will be supported in the future, so we will accept it.
1952 if (!in_array($parent_type, ["Post", "Comment"])) {
1956 $contact = self::allowedContactByHandle($importer, $sender, true);
1961 $message_id = self::messageExists($importer["uid"], $guid);
1966 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1967 if (!$parent_item) {
1971 $person = self::personByHandle($author);
1972 if (!is_array($person)) {
1973 Logger::log("unable to find author details");
1977 // Fetch the contact id - if we know this contact
1978 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1980 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1981 // We would accept this anyhow.
1982 if ($positive == "true") {
1983 $verb = ACTIVITY_LIKE;
1985 $verb = ACTIVITY_DISLIKE;
1990 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1992 $datarray["uid"] = $importer["uid"];
1993 $datarray["contact-id"] = $author_contact["cid"];
1994 $datarray["network"] = $author_contact["network"];
1996 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1997 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1999 $datarray["guid"] = $guid;
2000 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2002 $datarray["verb"] = $verb;
2003 $datarray["gravity"] = GRAVITY_ACTIVITY;
2004 $datarray["parent-uri"] = $parent_item["uri"];
2006 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2008 $datarray["body"] = $verb;
2010 // Diaspora doesn't provide a date for likes
2011 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2013 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2014 if ($parent_item["id"] != $parent_item["parent"]) {
2015 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2016 $origin = $toplevel["origin"];
2018 $origin = $parent_item["origin"];
2021 // If we are the origin of the parent we store the original data.
2022 // We notify our followers during the item storage.
2024 $datarray['diaspora_signed_text'] = json_encode($data);
2027 $message_id = Item::insert($datarray);
2029 if ($message_id <= 0) {
2034 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2035 if ($datarray['uid'] == 0) {
2036 Item::distribute($message_id, json_encode($data));
2044 * @brief Processes private messages
2046 * @param array $importer Array of the importer user
2047 * @param object $data The message object
2049 * @return bool Success?
2050 * @throws \Exception
2052 private static function receiveMessage(array $importer, $data)
2054 $author = Strings::escapeTags(XML::unescape($data->author));
2055 $guid = Strings::escapeTags(XML::unescape($data->guid));
2056 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2057 $text = XML::unescape($data->text);
2058 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2060 $contact = self::allowedContactByHandle($importer, $author, true);
2065 $conversation = null;
2067 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2068 $conversation = DBA::selectFirst('conv', [], $condition);
2070 if (!DBA::isResult($conversation)) {
2071 Logger::log("conversation not available.");
2075 $message_uri = $author.":".$guid;
2077 $person = self::personByHandle($author);
2079 Logger::log("unable to find author details");
2083 $body = Markdown::toBBCode($text);
2085 $body = self::replacePeopleGuid($body, $person["url"]);
2087 return Mail::insert([
2088 'uid' => $importer['uid'],
2090 'convid' => $conversation['id'],
2091 'from-name' => $person['name'],
2092 'from-photo' => $person['photo'],
2093 'from-url' => $person['url'],
2094 'contact-id' => $contact['id'],
2095 'title' => $conversation['subject'],
2098 'uri' => $message_uri,
2099 'parent-uri' => $author.":".$conversation['guid'],
2100 'created' => $created_at
2105 * @brief Processes participations - unsupported by now
2107 * @param array $importer Array of the importer user
2108 * @param object $data The message object
2110 * @return bool always true
2111 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2112 * @throws \ImagickException
2114 private static function receiveParticipation(array $importer, $data)
2116 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2117 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2119 $contact_id = Contact::getIdForURL($author);
2121 Logger::log('Contact not found: '.$author);
2125 $person = self::personByHandle($author);
2126 if (!is_array($person)) {
2127 Logger::log("Person not found: ".$author);
2131 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2132 if (!DBA::isResult($item)) {
2133 Logger::log('Item not found, no origin or private: '.$parent_guid);
2137 $author_parts = explode('@', $author);
2138 if (isset($author_parts[1])) {
2139 $server = $author_parts[1];
2141 // Should never happen
2145 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2147 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2148 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2151 // Send all existing comments and likes to the requesting server
2152 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2153 while ($comment = Item::fetch($comments)) {
2154 if ($comment['id'] == $comment['parent']) {
2158 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2159 Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $contact_id);
2161 DBA::close($comments);
2167 * @brief Processes photos - unneeded
2169 * @param array $importer Array of the importer user
2170 * @param object $data The message object
2172 * @return bool always true
2174 private static function receivePhoto(array $importer, $data)
2176 // There doesn't seem to be a reason for this function,
2177 // since the photo data is transmitted in the status message as well
2182 * @brief Processes poll participations - unssupported
2184 * @param array $importer Array of the importer user
2185 * @param object $data The message object
2187 * @return bool always true
2189 private static function receivePollParticipation(array $importer, $data)
2191 // We don't support polls by now
2196 * @brief Processes incoming profile updates
2198 * @param array $importer Array of the importer user
2199 * @param object $data The message object
2201 * @return bool Success
2202 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2203 * @throws \ImagickException
2205 private static function receiveProfile(array $importer, $data)
2207 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2209 $contact = self::contactByHandle($importer["uid"], $author);
2214 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2215 $image_url = XML::unescape($data->image_url);
2216 $birthday = XML::unescape($data->birthday);
2217 $gender = XML::unescape($data->gender);
2218 $about = Markdown::toBBCode(XML::unescape($data->bio));
2219 $location = Markdown::toBBCode(XML::unescape($data->location));
2220 $searchable = (XML::unescape($data->searchable) == "true");
2221 $nsfw = (XML::unescape($data->nsfw) == "true");
2222 $tags = XML::unescape($data->tag_string);
2224 $tags = explode("#", $tags);
2227 foreach ($tags as $tag) {
2228 $tag = trim(strtolower($tag));
2234 $keywords = implode(", ", $keywords);
2236 $handle_parts = explode("@", $author);
2237 $nick = $handle_parts[0];
2240 $name = $handle_parts[0];
2243 if (preg_match("|^https?://|", $image_url) === 0) {
2244 $image_url = "http://".$handle_parts[1].$image_url;
2247 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2249 // Generic birthday. We don't know the timezone. The year is irrelevant.
2251 $birthday = str_replace("1000", "1901", $birthday);
2253 if ($birthday != "") {
2254 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2257 // this is to prevent multiple birthday notifications in a single year
2258 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2260 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2261 $birthday = $contact["bd"];
2264 $fields = ['name' => $name, 'location' => $location,
2265 'name-date' => DateTimeFormat::utcNow(),
2266 'about' => $about, 'gender' => $gender,
2267 'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2268 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2270 if (!empty($birthday)) {
2271 $fields['bd'] = $birthday;
2274 DBA::update('contact', $fields, ['id' => $contact['id']]);
2276 // @todo Update the public contact, then update the gcontact from that
2278 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2279 "photo" => $image_url, "name" => $name, "location" => $location,
2280 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2281 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2282 "hide" => !$searchable, "nsfw" => $nsfw];
2284 $gcid = GContact::update($gcontact);
2286 GContact::link($gcid, $importer["uid"], $contact["id"]);
2288 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2294 * @brief Processes incoming friend requests
2296 * @param array $importer Array of the importer user
2297 * @param array $contact The contact that send the request
2299 * @throws \Exception
2301 private static function receiveRequestMakeFriend(array $importer, array $contact)
2303 if ($contact["rel"] == Contact::SHARING) {
2306 ['rel' => Contact::FRIEND, 'writable' => true],
2307 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2313 * @brief Processes incoming sharing notification
2315 * @param array $importer Array of the importer user
2316 * @param object $data The message object
2318 * @return bool Success
2319 * @throws \Exception
2321 private static function receiveContactRequest(array $importer, $data)
2323 $author = XML::unescape($data->author);
2324 $recipient = XML::unescape($data->recipient);
2326 if (!$author || !$recipient) {
2330 // the current protocol version doesn't know these fields
2331 // That means that we will assume their existance
2332 if (isset($data->following)) {
2333 $following = (XML::unescape($data->following) == "true");
2338 if (isset($data->sharing)) {
2339 $sharing = (XML::unescape($data->sharing) == "true");
2344 $contact = self::contactByHandle($importer["uid"], $author);
2346 // perhaps we were already sharing with this person. Now they're sharing with us.
2347 // That makes us friends.
2350 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2351 self::receiveRequestMakeFriend($importer, $contact);
2353 // refetch the contact array
2354 $contact = self::contactByHandle($importer["uid"], $author);
2356 // If we are now friends, we are sending a share message.
2357 // Normally we needn't to do so, but the first message could have been vanished.
2358 if (in_array($contact["rel"], [Contact::FRIEND])) {
2359 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2360 if (DBA::isResult($user)) {
2361 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2362 self::sendShare($user, $contact);
2367 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2368 Contact::removeFollower($importer, $contact);
2373 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2374 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2376 } elseif (!$following && !$sharing) {
2377 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2379 } elseif (!$following && $sharing) {
2380 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2381 } elseif ($following && $sharing) {
2382 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2383 } elseif ($following && !$sharing) {
2384 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2387 $ret = self::personByHandle($author);
2389 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2390 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2394 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2397 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2398 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2399 intval($importer["uid"]),
2400 DBA::escape($ret["network"]),
2401 DBA::escape($ret["addr"]),
2402 DateTimeFormat::utcNow(),
2403 DBA::escape($ret["url"]),
2404 DBA::escape(Strings::normaliseLink($ret["url"])),
2405 DBA::escape($batch),
2406 DBA::escape($ret["name"]),
2407 DBA::escape($ret["nick"]),
2408 DBA::escape($ret["photo"]),
2409 DBA::escape($ret["pubkey"]),
2410 DBA::escape($ret["notify"]),
2411 DBA::escape($ret["poll"]),
2416 // find the contact record we just created
2418 $contact_record = self::contactByHandle($importer["uid"], $author);
2420 if (!$contact_record) {
2421 Logger::log("unable to locate newly created contact record.");
2425 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2427 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2429 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2431 if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
2432 Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2434 $hash = Strings::getRandomHex().(string)time(); // Generate a confirm_key
2437 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2438 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2439 intval($importer["uid"]),
2440 intval($contact_record["id"]),
2443 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2445 DBA::escape(DateTimeFormat::utcNow())
2448 // automatic friend approval
2450 Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2452 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2455 * technically they are sharing with us (Contact::SHARING),
2456 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2457 * we are going to change the relationship and make them a follower.
2459 if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
2460 $new_relation = Contact::FRIEND;
2461 } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
2462 $new_relation = Contact::SHARING;
2464 $new_relation = Contact::FOLLOWER;
2468 "UPDATE `contact` SET `rel` = %d,
2476 intval($new_relation),
2477 DBA::escape(DateTimeFormat::utcNow()),
2478 DBA::escape(DateTimeFormat::utcNow()),
2479 intval($contact_record["id"])
2482 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2483 if (DBA::isResult($user)) {
2484 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2485 self::sendShare($user, $contact_record);
2487 // Send the profile data, maybe it weren't transmitted before
2488 self::sendProfile($importer["uid"], [$contact_record]);
2496 * @brief Fetches a message with a given guid
2498 * @param string $guid message guid
2499 * @param string $orig_author handle of the original post
2500 * @return array The fetched item
2501 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2502 * @throws \ImagickException
2504 public static function originalItem($guid, $orig_author)
2507 Logger::log('Empty guid. Quitting.');
2511 // Do we already have this item?
2512 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2513 'author-name', 'author-link', 'author-avatar'];
2514 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2515 $item = Item::selectFirst($fields, $condition);
2517 if (DBA::isResult($item)) {
2518 Logger::log("reshared message ".$guid." already exists on system.");
2520 // Maybe it is already a reshared item?
2521 // Then refetch the content, if it is a reshare from a reshare.
2522 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2523 if (self::isReshare($item["body"], true)) {
2525 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2526 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2528 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2530 // Add OEmbed and other information to the body
2531 $item["body"] = add_page_info_to_body($item["body"], false, true);
2539 if (!DBA::isResult($item)) {
2540 if (empty($orig_author)) {
2541 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2545 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2546 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2547 $stored = self::storeByGuid($guid, $server);
2550 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2551 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2552 $stored = self::storeByGuid($guid, $server);
2556 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2557 'author-name', 'author-link', 'author-avatar'];
2558 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2559 $item = Item::selectFirst($fields, $condition);
2561 if (DBA::isResult($item)) {
2562 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2563 if (self::isReshare($item["body"], false)) {
2564 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2565 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2576 * @brief Stores a reshare activity
2578 * @param array $item Array of reshare post
2579 * @param integer $parent_message_id Id of the parent post
2580 * @param string $guid GUID string of reshare action
2581 * @param string $author Author handle
2583 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2585 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2589 $datarray['uid'] = $item['uid'];
2590 $datarray['contact-id'] = $item['contact-id'];
2591 $datarray['network'] = $item['network'];
2593 $datarray['author-link'] = $item['author-link'];
2594 $datarray['author-id'] = $item['author-id'];
2596 $datarray['owner-link'] = $datarray['author-link'];
2597 $datarray['owner-id'] = $datarray['author-id'];
2599 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2600 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2601 $datarray['parent-uri'] = $parent['uri'];
2603 $datarray['verb'] = $datarray['body'] = ACTIVITY2_ANNOUNCE;
2604 $datarray['gravity'] = GRAVITY_ACTIVITY;
2605 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
2607 $datarray['protocol'] = $item['protocol'];
2609 $datarray['plink'] = self::plink($author, $datarray['guid']);
2610 $datarray['private'] = $item['private'];
2611 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2613 $message_id = Item::insert($datarray);
2616 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2617 if ($datarray['uid'] == 0) {
2618 Item::distribute($message_id);
2624 * @brief Processes a reshare message
2626 * @param array $importer Array of the importer user
2627 * @param object $data The message object
2628 * @param string $xml The original XML of the message
2630 * @return int the message id
2631 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2632 * @throws \ImagickException
2634 private static function receiveReshare(array $importer, $data, $xml)
2636 $author = Strings::escapeTags(XML::unescape($data->author));
2637 $guid = Strings::escapeTags(XML::unescape($data->guid));
2638 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2639 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2640 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2641 /// @todo handle unprocessed property "provider_display_name"
2642 $public = Strings::escapeTags(XML::unescape($data->public));
2644 $contact = self::allowedContactByHandle($importer, $author, false);
2649 $message_id = self::messageExists($importer["uid"], $guid);
2654 $original_item = self::originalItem($root_guid, $root_author);
2655 if (!$original_item) {
2659 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2663 $datarray["uid"] = $importer["uid"];
2664 $datarray["contact-id"] = $contact["id"];
2665 $datarray["network"] = Protocol::DIASPORA;
2667 $datarray["author-link"] = $contact["url"];
2668 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2670 $datarray["owner-link"] = $datarray["author-link"];
2671 $datarray["owner-id"] = $datarray["author-id"];
2673 $datarray["guid"] = $guid;
2674 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2676 $datarray["verb"] = ACTIVITY_POST;
2677 $datarray["gravity"] = GRAVITY_PARENT;
2679 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2680 $datarray["source"] = $xml;
2682 $prefix = share_header(
2683 $original_item["author-name"],
2684 $original_item["author-link"],
2685 $original_item["author-avatar"],
2686 $original_item["guid"],
2687 $original_item["created"],
2690 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2692 $datarray["tag"] = $original_item["tag"];
2693 $datarray["app"] = $original_item["app"];
2695 $datarray["plink"] = self::plink($author, $guid);
2696 $datarray["private"] = (($public == "false") ? 1 : 0);
2697 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2699 $datarray["object-type"] = $original_item["object-type"];
2701 self::fetchGuid($datarray);
2702 $message_id = Item::insert($datarray);
2704 self::sendParticipation($contact, $datarray);
2706 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2707 if ($root_message_id) {
2708 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2712 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2713 if ($datarray['uid'] == 0) {
2714 Item::distribute($message_id);
2723 * @brief Processes retractions
2725 * @param array $importer Array of the importer user
2726 * @param array $contact The contact of the item owner
2727 * @param object $data The message object
2729 * @return bool success
2730 * @throws \Exception
2732 private static function itemRetraction(array $importer, array $contact, $data)
2734 $author = Strings::escapeTags(XML::unescape($data->author));
2735 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2736 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2738 $person = self::personByHandle($author);
2739 if (!is_array($person)) {
2740 Logger::log("unable to find author detail for ".$author);
2744 if (empty($contact["url"])) {
2745 $contact["url"] = $person["url"];
2748 // Fetch items that are about to be deleted
2749 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2751 // When we receive a public retraction, we delete every item that we find.
2752 if ($importer['uid'] == 0) {
2753 $condition = ['guid' => $target_guid, 'deleted' => false];
2755 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2758 $r = Item::select($fields, $condition);
2759 if (!DBA::isResult($r)) {
2760 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2764 while ($item = Item::fetch($r)) {
2765 if (strstr($item['file'], '[')) {
2766 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2770 // Fetch the parent item
2771 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2773 // Only delete it if the parent author really fits
2774 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2775 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2779 Item::delete(['id' => $item['id']]);
2781 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2788 * @brief Receives retraction messages
2790 * @param array $importer Array of the importer user
2791 * @param string $sender The sender of the message
2792 * @param object $data The message object
2794 * @return bool Success
2795 * @throws \Exception
2797 private static function receiveRetraction(array $importer, $sender, $data)
2799 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2801 $contact = self::contactByHandle($importer["uid"], $sender);
2802 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2803 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2811 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2813 switch ($target_type) {
2818 case "StatusMessage":
2819 return self::itemRetraction($importer, $contact, $data);
2821 case "PollParticipation":
2823 // Currently unsupported
2827 Logger::log("Unknown target type ".$target_type);
2834 * @brief Receives status messages
2836 * @param array $importer Array of the importer user
2837 * @param SimpleXMLElement $data The message object
2838 * @param string $xml The original XML of the message
2840 * @return int The message id of the newly created item
2841 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2842 * @throws \ImagickException
2844 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2846 $author = Strings::escapeTags(XML::unescape($data->author));
2847 $guid = Strings::escapeTags(XML::unescape($data->guid));
2848 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2849 $public = Strings::escapeTags(XML::unescape($data->public));
2850 $text = XML::unescape($data->text);
2851 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2853 $contact = self::allowedContactByHandle($importer, $author, false);
2858 $message_id = self::messageExists($importer["uid"], $guid);
2864 if ($data->location) {
2865 foreach ($data->location->children() as $fieldname => $data) {
2866 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2870 $body = Markdown::toBBCode($text);
2874 // Attach embedded pictures to the body
2876 foreach ($data->photo as $photo) {
2877 $body = "[img]".XML::unescape($photo->remote_photo_path).
2878 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2881 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2883 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2885 // Add OEmbed and other information to the body
2886 if (!self::isRedmatrix($contact["url"])) {
2887 $body = add_page_info_to_body($body, false, true);
2891 /// @todo enable support for polls
2892 //if ($data->poll) {
2893 // foreach ($data->poll AS $poll)
2898 /// @todo enable support for events
2900 $datarray["uid"] = $importer["uid"];
2901 $datarray["contact-id"] = $contact["id"];
2902 $datarray["network"] = Protocol::DIASPORA;
2904 $datarray["author-link"] = $contact["url"];
2905 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2907 $datarray["owner-link"] = $datarray["author-link"];
2908 $datarray["owner-id"] = $datarray["author-id"];
2910 $datarray["guid"] = $guid;
2911 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2913 $datarray["verb"] = ACTIVITY_POST;
2914 $datarray["gravity"] = GRAVITY_PARENT;
2916 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2917 $datarray["source"] = $xml;
2919 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2921 if ($provider_display_name != "") {
2922 $datarray["app"] = $provider_display_name;
2925 $datarray["plink"] = self::plink($author, $guid);
2926 $datarray["private"] = (($public == "false") ? 1 : 0);
2927 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2929 if (isset($address["address"])) {
2930 $datarray["location"] = $address["address"];
2933 if (isset($address["lat"]) && isset($address["lng"])) {
2934 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2937 self::fetchGuid($datarray);
2938 $message_id = Item::insert($datarray);
2940 self::sendParticipation($contact, $datarray);
2943 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2944 if ($datarray['uid'] == 0) {
2945 Item::distribute($message_id);
2953 /* ************************************************************************************** *
2954 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2955 * ************************************************************************************** */
2958 * @brief returnes the handle of a contact
2960 * @param array $contact contact array
2962 * @return string the handle in the format user@domain.tld
2963 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2965 private static function myHandle(array $contact)
2967 if (!empty($contact["addr"])) {
2968 return $contact["addr"];
2971 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2972 // So - just in case - we build the the address here.
2973 if ($contact["nickname"] != "") {
2974 $nick = $contact["nickname"];
2976 $nick = $contact["nick"];
2979 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2984 * @brief Creates the data for a private message in the new format
2986 * @param string $msg The message that is to be transmitted
2987 * @param array $user The record of the sender
2988 * @param array $contact Target of the communication
2989 * @param string $prvkey The private key of the sender
2990 * @param string $pubkey The public key of the receiver
2992 * @return string The encrypted data
2993 * @throws \Exception
2995 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2997 Logger::log("Message: ".$msg, Logger::DATA);
2999 // without a public key nothing will work
3001 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3005 $aes_key = openssl_random_pseudo_bytes(32);
3006 $b_aes_key = base64_encode($aes_key);
3007 $iv = openssl_random_pseudo_bytes(16);
3008 $b_iv = base64_encode($iv);
3010 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3012 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3014 $encrypted_key_bundle = "";
3015 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3017 $json_object = json_encode(
3018 ["aes_key" => base64_encode($encrypted_key_bundle),
3019 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3022 return $json_object;
3026 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3028 * @param string $msg The message that is to be transmitted
3029 * @param array $user The record of the sender
3031 * @return string The envelope
3032 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3034 public static function buildMagicEnvelope($msg, array $user)
3036 $b64url_data = Strings::base64UrlEncode($msg);
3037 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3039 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3040 $type = "application/xml";
3041 $encoding = "base64url";
3042 $alg = "RSA-SHA256";
3043 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3045 // Fallback if the private key wasn't transmitted in the expected field
3046 if ($user['uprvkey'] == "") {
3047 $user['uprvkey'] = $user['prvkey'];
3050 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3051 $sig = Strings::base64UrlEncode($signature);
3053 $xmldata = ["me:env" => ["me:data" => $data,
3054 "@attributes" => ["type" => $type],
3055 "me:encoding" => $encoding,
3058 "@attributes2" => ["key_id" => $key_id]]];
3060 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3062 return XML::fromArray($xmldata, $xml, false, $namespaces);
3066 * @brief Create the envelope for a message
3068 * @param string $msg The message that is to be transmitted
3069 * @param array $user The record of the sender
3070 * @param array $contact Target of the communication
3071 * @param string $prvkey The private key of the sender
3072 * @param string $pubkey The public key of the receiver
3073 * @param bool $public Is the message public?
3075 * @return string The message that will be transmitted to other servers
3076 * @throws \Exception
3078 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3080 // The message is put into an envelope with the sender's signature
3081 $envelope = self::buildMagicEnvelope($msg, $user);
3083 // Private messages are put into a second envelope, encrypted with the receivers public key
3085 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3092 * @brief Creates a signature for a message
3094 * @param array $owner the array of the owner of the message
3095 * @param array $message The message that is to be signed
3097 * @return string The signature
3099 private static function signature($owner, $message)
3102 unset($sigmsg["author_signature"]);
3103 unset($sigmsg["parent_author_signature"]);
3105 $signed_text = implode(";", $sigmsg);
3107 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3111 * @brief Transmit a message to a target server
3113 * @param array $owner the array of the item owner
3114 * @param array $contact Target of the communication
3115 * @param string $envelope The message that is to be transmitted
3116 * @param bool $public_batch Is it a public post?
3117 * @param string $guid message guid
3119 * @return int Result of the transmission
3120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3121 * @throws \ImagickException
3123 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3125 $enabled = intval(Config::get("system", "diaspora_enabled"));
3130 $logid = Strings::getRandomHex(4);
3132 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3134 // We always try to use the data from the fcontact table.
3135 // This is important for transmitting data to Friendica servers.
3136 if (!empty($contact['addr'])) {
3137 $fcontact = self::personByHandle($contact['addr']);
3138 if (!empty($fcontact)) {
3139 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3144 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3148 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3150 if (!intval(Config::get("system", "diaspora_test"))) {
3151 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3153 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3154 $return_code = $postResult->getReturnCode();
3156 Logger::log("test_mode");
3160 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3162 return $return_code ? $return_code : -1;
3167 * @brief Build the post xml
3169 * @param string $type The message type
3170 * @param array $message The message data
3172 * @return string The post XML
3174 public static function buildPostXml($type, $message)
3176 $data = [$type => $message];
3178 return XML::fromArray($data, $xml);
3182 * @brief Builds and transmit messages
3184 * @param array $owner the array of the item owner
3185 * @param array $contact Target of the communication
3186 * @param string $type The message type
3187 * @param array $message The message data
3188 * @param bool $public_batch Is it a public post?
3189 * @param string $guid message guid
3191 * @return int Result of the transmission
3192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3193 * @throws \ImagickException
3195 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3197 $msg = self::buildPostXml($type, $message);
3199 Logger::log('message: '.$msg, Logger::DATA);
3200 Logger::log('send guid '.$guid, Logger::DEBUG);
3202 // Fallback if the private key wasn't transmitted in the expected field
3203 if (empty($owner['uprvkey'])) {
3204 $owner['uprvkey'] = $owner['prvkey'];
3207 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3209 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3211 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3213 return $return_code;
3217 * @brief sends a participation (Used to get all further updates)
3219 * @param array $contact Target of the communication
3220 * @param array $item Item array
3222 * @return int The result of the transmission
3223 * @throws \Exception
3225 private static function sendParticipation(array $contact, array $item)
3227 // Don't send notifications for private postings
3228 if ($item['private']) {
3232 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3234 $result = Cache::get($cachekey);
3235 if (!is_null($result)) {
3239 // Fetch some user id to have a valid handle to transmit the participation.
3240 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3241 // If the item belongs to a user, we take this user id.
3242 if ($item['uid'] == 0) {
3243 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3244 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3245 $owner = User::getOwnerDataById($first_user['uid']);
3247 $owner = User::getOwnerDataById($item['uid']);
3250 $author = self::myHandle($owner);
3252 $message = ["author" => $author,
3253 "guid" => System::createUUID(),
3254 "parent_type" => "Post",
3255 "parent_guid" => $item["guid"]];
3257 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3259 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3260 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3262 return self::buildAndTransmit($owner, $contact, "participation", $message);
3266 * @brief sends an account migration
3268 * @param array $owner the array of the item owner
3269 * @param array $contact Target of the communication
3270 * @param int $uid User ID
3272 * @return int The result of the transmission
3273 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3274 * @throws \ImagickException
3276 public static function sendAccountMigration(array $owner, array $contact, $uid)
3278 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3279 $profile = self::createProfileData($uid);
3281 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3282 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3284 $message = ["author" => $old_handle,
3285 "profile" => $profile,
3286 "signature" => $signature];
3288 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3290 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3294 * @brief Sends a "share" message
3296 * @param array $owner the array of the item owner
3297 * @param array $contact Target of the communication
3299 * @return int The result of the transmission
3300 * @throws \Exception
3302 public static function sendShare(array $owner, array $contact)
3305 * @todo support the different possible combinations of "following" and "sharing"
3306 * Currently, Diaspora only interprets the "sharing" field
3308 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3312 switch ($contact["rel"]) {
3313 case Contact::FRIEND:
3317 case Contact::SHARING:
3321 case Contact::FOLLOWER:
3327 $message = ["author" => self::myHandle($owner),
3328 "recipient" => $contact["addr"],
3329 "following" => "true",
3330 "sharing" => "true"];
3332 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3334 return self::buildAndTransmit($owner, $contact, "contact", $message);
3338 * @brief sends an "unshare"
3340 * @param array $owner the array of the item owner
3341 * @param array $contact Target of the communication
3343 * @return int The result of the transmission
3344 * @throws \Exception
3346 public static function sendUnshare(array $owner, array $contact)
3348 $message = ["author" => self::myHandle($owner),
3349 "recipient" => $contact["addr"],
3350 "following" => "false",
3351 "sharing" => "false"];
3353 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3355 return self::buildAndTransmit($owner, $contact, "contact", $message);
3359 * @brief Checks a message body if it is a reshare
3361 * @param string $body The message body that is to be check
3362 * @param bool $complete Should it be a complete check or a simple check?
3364 * @return array|bool Reshare details or "false" if no reshare
3365 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3366 * @throws \ImagickException
3368 public static function isReshare($body, $complete = true)
3370 $body = trim($body);
3372 // Skip if it isn't a pure repeated messages
3373 // Does it start with a share?
3374 if ((strpos($body, "[share") > 0) && $complete) {
3378 // Does it end with a share?
3379 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3383 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3384 // Skip if there is no shared message in there
3385 if ($body == $attributes) {
3389 // If we don't do the complete check we quit here
3392 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3393 if (!empty($matches[1])) {
3394 $guid = $matches[1];
3397 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3398 if (!empty($matches[1])) {
3399 $guid = $matches[1];
3402 if (($guid != "") && $complete) {
3403 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3404 $item = Item::selectFirst(['contact-id'], $condition);
3405 if (DBA::isResult($item)) {
3407 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3408 $ret["root_guid"] = $guid;
3410 } elseif ($complete) {
3411 // We are resharing something that isn't a DFRN or Diaspora post.
3412 // So we have to return "false" on "$complete" to not trigger a reshare.
3415 } elseif (($guid == "") && $complete) {
3419 $ret["root_guid"] = $guid;
3422 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3423 if (!empty($matches[1])) {
3424 $profile = $matches[1];
3427 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3428 if (!empty($matches[1])) {
3429 $profile = $matches[1];
3434 if ($profile != "") {
3435 if (Contact::getIdForURL($profile)) {
3436 $author = Contact::getDetailsByURL($profile);
3437 $ret["root_handle"] = $author['addr'];
3441 if (empty($ret) && !$complete) {
3449 * @brief Create an event array
3451 * @param integer $event_id The id of the event
3453 * @return array with event data
3454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3456 private static function buildEvent($event_id)
3458 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3459 if (!DBA::isResult($r)) {
3467 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3468 if (!DBA::isResult($r)) {
3474 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3475 if (!DBA::isResult($r)) {
3481 $eventdata['author'] = self::myHandle($owner);
3483 if ($event['guid']) {
3484 $eventdata['guid'] = $event['guid'];
3487 $mask = DateTimeFormat::ATOM;
3489 /// @todo - establish "all day" events in Friendica
3490 $eventdata["all_day"] = "false";
3492 $eventdata['timezone'] = 'UTC';
3493 if (!$event['adjust'] && $user['timezone']) {
3494 $eventdata['timezone'] = $user['timezone'];
3497 if ($event['start']) {
3498 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3500 if ($event['finish'] && !$event['nofinish']) {
3501 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3503 if ($event['summary']) {
3504 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3506 if ($event['desc']) {
3507 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3509 if ($event['location']) {
3510 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3511 $coord = Map::getCoordinates($event['location']);
3514 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3515 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3516 $location["lat"] = $coord['lat'];
3517 $location["lng"] = $coord['lon'];
3519 $location["lat"] = 0;
3520 $location["lng"] = 0;
3522 $eventdata['location'] = $location;
3529 * @brief Create a post (status message or reshare)
3531 * @param array $item The item that will be exported
3532 * @param array $owner the array of the item owner
3535 * 'type' -> Message type ("status_message" or "reshare")
3536 * 'message' -> Array of XML elements of the status
3537 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3538 * @throws \ImagickException
3540 public static function buildStatus(array $item, array $owner)
3542 $cachekey = "diaspora:buildStatus:".$item['guid'];
3544 $result = Cache::get($cachekey);
3545 if (!is_null($result)) {
3549 $myaddr = self::myHandle($owner);
3551 $public = ($item["private"] ? "false" : "true");
3553 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3554 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3556 // Detect a share element and do a reshare
3557 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3558 $message = ["author" => $myaddr,
3559 "guid" => $item["guid"],
3560 "created_at" => $created,
3561 "root_author" => $ret["root_handle"],
3562 "root_guid" => $ret["root_guid"],
3563 "provider_display_name" => $item["app"],
3564 "public" => $public];
3568 $title = $item["title"];
3569 $body = $item["body"];
3571 if ($item['author-link'] != $item['owner-link']) {
3572 require_once 'mod/share.php';
3573 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3574 "", $item['created'], $item['plink']) . $body . '[/share]';
3577 // convert to markdown
3578 $body = html_entity_decode(BBCode::toMarkdown($body));
3581 if (strlen($title)) {
3582 $body = "## ".html_entity_decode($title)."\n\n".$body;
3585 if ($item["attach"]) {
3586 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3588 $body .= "\n".L10n::t("Attachments:")."\n";
3589 foreach ($matches as $mtch) {
3590 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3597 if ($item["location"] != "")
3598 $location["address"] = $item["location"];
3600 if ($item["coord"] != "") {
3601 $coord = explode(" ", $item["coord"]);
3602 $location["lat"] = $coord[0];
3603 $location["lng"] = $coord[1];
3606 $message = ["author" => $myaddr,
3607 "guid" => $item["guid"],
3608 "created_at" => $created,
3609 "edited_at" => $edited,
3610 "public" => $public,
3612 "provider_display_name" => $item["app"],
3613 "location" => $location];
3615 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3616 if (!isset($location["lat"]) || !isset($location["lng"])) {
3617 unset($message["location"]);
3620 if ($item['event-id'] > 0) {
3621 $event = self::buildEvent($item['event-id']);
3622 if (count($event)) {
3623 $message['event'] = $event;
3625 if (!empty($event['location']['address']) &&
3626 !empty($event['location']['lat']) &&
3627 !empty($event['location']['lng'])) {
3628 $message['location'] = $event['location'];
3631 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3632 // $message['text'] = '';
3636 $type = "status_message";
3639 $msg = ["type" => $type, "message" => $message];
3641 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3646 private static function prependParentAuthorMention($body, $profile_url)
3648 $profile = Contact::getDetailsByURL($profile_url);
3649 if (!empty($profile['addr'])
3650 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3651 && !strstr($body, $profile['addr'])
3652 && !strstr($body, $profile_url)
3654 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3661 * @brief Sends a post
3663 * @param array $item The item that will be exported
3664 * @param array $owner the array of the item owner
3665 * @param array $contact Target of the communication
3666 * @param bool $public_batch Is it a public post?
3668 * @return int The result of the transmission
3669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3670 * @throws \ImagickException
3672 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3674 $status = self::buildStatus($item, $owner);
3676 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3680 * @brief Creates a "like" object
3682 * @param array $item The item that will be exported
3683 * @param array $owner the array of the item owner
3685 * @return array The data for a "like"
3686 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3688 private static function constructLike(array $item, array $owner)
3690 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3691 if (!DBA::isResult($parent)) {
3695 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3697 if ($item['verb'] === ACTIVITY_LIKE) {
3699 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3700 $positive = "false";
3703 return(["author" => self::myHandle($owner),
3704 "guid" => $item["guid"],
3705 "parent_guid" => $parent["guid"],
3706 "parent_type" => $target_type,
3707 "positive" => $positive,
3708 "author_signature" => ""]);
3712 * @brief Creates an "EventParticipation" object
3714 * @param array $item The item that will be exported
3715 * @param array $owner the array of the item owner
3717 * @return array The data for an "EventParticipation"
3718 * @throws \Exception
3720 private static function constructAttend(array $item, array $owner)
3722 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3723 if (!DBA::isResult($parent)) {
3727 switch ($item['verb']) {
3728 case ACTIVITY_ATTEND:
3729 $attend_answer = 'accepted';
3731 case ACTIVITY_ATTENDNO:
3732 $attend_answer = 'declined';
3734 case ACTIVITY_ATTENDMAYBE:
3735 $attend_answer = 'tentative';
3738 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3742 return(["author" => self::myHandle($owner),
3743 "guid" => $item["guid"],
3744 "parent_guid" => $parent["guid"],
3745 "status" => $attend_answer,
3746 "author_signature" => ""]);
3750 * @brief Creates the object for a comment
3752 * @param array $item The item that will be exported
3753 * @param array $owner the array of the item owner
3755 * @return array|false The data for a comment
3756 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3758 private static function constructComment(array $item, array $owner)
3760 $cachekey = "diaspora:constructComment:".$item['guid'];
3762 $result = Cache::get($cachekey);
3763 if (!is_null($result)) {
3767 $toplevel_item = Item::selectFirst(['guid', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3768 if (!DBA::isResult($toplevel_item)) {
3769 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3773 $thread_parent_item = $toplevel_item;
3774 if ($item['thr-parent'] != $item['parent-uri']) {
3775 $thread_parent_item = Item::selectFirst(['guid', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3778 $body = $item["body"];
3780 if ((empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3781 && !Config::get('system', 'disable_implicit_mentions')
3783 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3786 $text = html_entity_decode(BBCode::toMarkdown($body));
3787 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3788 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3791 "author" => self::myHandle($owner),
3792 "guid" => $item["guid"],
3793 "created_at" => $created,
3794 "edited_at" => $edited,
3795 "parent_guid" => $toplevel_item["guid"],
3797 "author_signature" => ""
3800 // Send the thread parent guid only if it is a threaded comment
3801 if ($item['thr-parent'] != $item['parent-uri']) {
3802 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3805 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3811 * @brief Send a like or a comment
3813 * @param array $item The item that will be exported
3814 * @param array $owner the array of the item owner
3815 * @param array $contact Target of the communication
3816 * @param bool $public_batch Is it a public post?
3818 * @return int The result of the transmission
3819 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3820 * @throws \ImagickException
3822 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3824 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3825 $message = self::constructAttend($item, $owner);
3826 $type = "event_participation";
3827 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3828 $message = self::constructLike($item, $owner);
3830 } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW, ACTIVITY_TAG])) {
3831 $message = self::constructComment($item, $owner);
3835 if (empty($message)) {
3839 $message["author_signature"] = self::signature($owner, $message);
3841 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3845 * @brief Creates a message from a signature record entry
3847 * @param array $item The item that will be exported
3848 * @return array The message
3850 private static function messageFromSignature(array $item)
3852 // Split the signed text
3853 $signed_parts = explode(";", $item['signed_text']);
3855 if ($item["deleted"]) {
3856 $message = ["author" => $item['signer'],
3857 "target_guid" => $signed_parts[0],
3858 "target_type" => $signed_parts[1]];
3859 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3860 $message = ["author" => $signed_parts[4],
3861 "guid" => $signed_parts[1],
3862 "parent_guid" => $signed_parts[3],
3863 "parent_type" => $signed_parts[2],
3864 "positive" => $signed_parts[0],
3865 "author_signature" => $item['signature'],
3866 "parent_author_signature" => ""];
3868 // Remove the comment guid
3869 $guid = array_shift($signed_parts);
3871 // Remove the parent guid
3872 $parent_guid = array_shift($signed_parts);
3874 // Remove the handle
3875 $handle = array_pop($signed_parts);
3878 "author" => $handle,
3880 "parent_guid" => $parent_guid,
3881 "text" => implode(";", $signed_parts),
3882 "author_signature" => $item['signature'],
3883 "parent_author_signature" => ""
3890 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3892 * @param array $item The item that will be exported
3893 * @param array $owner the array of the item owner
3894 * @param array $contact Target of the communication
3895 * @param bool $public_batch Is it a public post?
3897 * @return int The result of the transmission
3898 * @throws \Exception
3900 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3902 if ($item["deleted"]) {
3903 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3904 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3910 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3912 // Old way - is used by the internal Friendica functions
3913 /// @todo Change all signatur storing functions to the new format
3914 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
3915 $message = self::messageFromSignature($item);
3917 $msg = json_decode($item['signed_text'], true);
3920 if (is_array($msg)) {
3921 foreach ($msg as $field => $data) {
3922 if (!$item["deleted"]) {
3923 if ($field == "diaspora_handle") {
3926 if ($field == "target_type") {
3927 $field = "parent_type";
3931 $message[$field] = $data;
3934 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3938 $message["parent_author_signature"] = self::signature($owner, $message);
3940 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
3942 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3946 * @brief Sends a retraction (deletion) of a message, like or comment
3948 * @param array $item The item that will be exported
3949 * @param array $owner the array of the item owner
3950 * @param array $contact Target of the communication
3951 * @param bool $public_batch Is it a public post?
3952 * @param bool $relay Is the retraction transmitted from a relay?
3954 * @return int The result of the transmission
3955 * @throws \Exception
3957 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3959 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3961 $msg_type = "retraction";
3963 if ($item['id'] == $item['parent']) {
3964 $target_type = "Post";
3965 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3966 $target_type = "Like";
3968 $target_type = "Comment";
3971 $message = ["author" => $itemaddr,
3972 "target_guid" => $item['guid'],
3973 "target_type" => $target_type];
3975 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
3977 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3981 * @brief Sends a mail
3983 * @param array $item The item that will be exported
3984 * @param array $owner The owner
3985 * @param array $contact Target of the communication
3987 * @return int The result of the transmission
3988 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3989 * @throws \ImagickException
3991 public static function sendMail(array $item, array $owner, array $contact)
3993 $myaddr = self::myHandle($owner);
3995 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3996 if (!DBA::isResult($cnv)) {
3997 Logger::log("conversation not found.");
4001 $body = BBCode::toMarkdown($item["body"]);
4002 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4005 "author" => $myaddr,
4006 "guid" => $item["guid"],
4007 "conversation_guid" => $cnv["guid"],
4009 "created_at" => $created,
4012 if ($item["reply"]) {
4017 "author" => $cnv["creator"],
4018 "guid" => $cnv["guid"],
4019 "subject" => $cnv["subject"],
4020 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4021 "participants" => $cnv["recips"],
4025 $type = "conversation";
4028 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4032 * @brief Split a name into first name and last name
4034 * @param string $name The name
4036 * @return array The array with "first" and "last"
4038 public static function splitName($name) {
4039 $name = trim($name);
4041 // Is the name longer than 64 characters? Then cut the rest of it.
4042 if (strlen($name) > 64) {
4043 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4044 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4046 $name = substr($name, 0, 64);
4050 // Take the first word as first name
4051 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4052 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4053 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4054 return ['first' => $first, 'last' => $last];
4057 // Take the last word as last name
4058 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4059 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4061 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4062 return ['first' => $first, 'last' => $last];
4065 // Take the first 32 characters if there is no space in the first 32 characters
4066 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4067 $first = substr($name, 0, 32);
4068 $last = substr($name, 32);
4069 return ['first' => $first, 'last' => $last];
4072 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4073 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4075 // Check if the last name is longer than 32 characters
4076 if (strlen($last) > 32) {
4077 if (strpos($last, ' ') <= 32) {
4078 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4080 $last = substr($last, 0, 32);
4084 return ['first' => $first, 'last' => $last];
4088 * @brief Create profile data
4090 * @param int $uid The user id
4092 * @return array The profile data
4093 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4095 private static function createProfileData($uid)
4098 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4100 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4101 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4102 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4111 $handle = $profile["addr"];
4113 $split_name = self::splitName($profile['name']);
4114 $first = $split_name['first'];
4115 $last = $split_name['last'];
4117 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4118 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4119 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4120 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4126 if ($searchable === 'true') {
4129 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4130 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4134 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4137 $about = $profile['about'];
4138 $about = strip_tags(BBCode::convert($about));
4140 $location = Profile::formatLocation($profile);
4142 if ($profile['pub_keywords']) {
4143 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4144 $kw = str_replace(' ', ' ', $kw);
4145 $arr = explode(' ', $kw);
4147 for ($x = 0; $x < 5; $x ++) {
4148 if (!empty($arr[$x])) {
4149 $tags .= '#'. trim($arr[$x]) .' ';
4154 $tags = trim($tags);
4157 return ["author" => $handle,
4158 "first_name" => $first,
4159 "last_name" => $last,
4160 "image_url" => $large,
4161 "image_url_medium" => $medium,
4162 "image_url_small" => $small,
4164 "gender" => $profile['gender'],
4166 "location" => $location,
4167 "searchable" => $searchable,
4169 "tag_string" => $tags];
4173 * @brief Sends profile data
4175 * @param int $uid The user id
4176 * @param bool $recips optional, default false
4178 * @throws \Exception
4180 public static function sendProfile($uid, $recips = false)
4186 $owner = User::getOwnerDataById($uid);
4193 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4194 AND `uid` = %d AND `rel` != %d",
4195 DBA::escape(Protocol::DIASPORA),
4197 intval(Contact::SHARING)
4205 $message = self::createProfileData($uid);
4207 // @ToDo Split this into single worker jobs
4208 foreach ($recips as $recip) {
4209 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4210 self::buildAndTransmit($owner, $recip, "profile", $message);
4215 * @brief Creates the signature for likes that are created on our system
4217 * @param integer $uid The user of that comment
4218 * @param array $item Item array
4220 * @return array Signed content
4221 * @throws \Exception
4223 public static function createLikeSignature($uid, array $item)
4225 $owner = User::getOwnerDataById($uid);
4226 if (empty($owner)) {
4227 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4231 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4235 $message = self::constructLike($item, $owner);
4236 if ($message === false) {
4240 $message["author_signature"] = self::signature($owner, $message);
4246 * @brief Creates the signature for Comments that are created on our system
4248 * @param integer $uid The user of that comment
4249 * @param array $item Item array
4251 * @return array Signed content
4252 * @throws \Exception
4254 public static function createCommentSignature($uid, array $item)
4256 $owner = User::getOwnerDataById($uid);
4257 if (empty($owner)) {
4258 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4262 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4263 $item['thr-parent'] = $item['parent-uri'];
4265 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4266 if (!DBA::isResult($parent)) {
4270 $item['parent-uri'] = $parent['parent-uri'];
4272 $message = self::constructComment($item, $owner);
4273 if ($message === false) {
4277 $message["author_signature"] = self::signature($owner, $message);