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\Profile;
31 use Friendica\Model\User;
32 use Friendica\Network\Probe;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Map;
36 use Friendica\Util\Network;
37 use Friendica\Util\Strings;
38 use Friendica\Util\XML;
42 * @brief This class contain functions to create and send Diaspora XML files
48 * @brief Return a list of relay servers
50 * The list contains not only the official relays but also servers that we serve directly
52 * @param integer $item_id The id of the item that is sent
53 * @param array $contacts The previously fetched contacts
55 * @return array of relay servers
56 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
58 public static function relayList($item_id, array $contacts = [])
62 // Fetching relay servers
63 $serverdata = Config::get("system", "relay_server");
65 if (!empty($serverdata)) {
66 $servers = explode(",", $serverdata);
67 foreach ($servers as $server) {
68 $serverlist[$server] = trim($server);
72 if (Config::get("system", "relay_directly", false)) {
73 // We distribute our stuff based on the parent to ensure that the thread will be complete
74 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
75 if (!DBA::isResult($parent)) {
79 // Servers that want to get all content
80 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
81 while ($server = DBA::fetch($servers)) {
82 $serverlist[$server['url']] = $server['url'];
85 // All tags of the current post
86 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
87 $tags = DBA::select('term', ['term'], $condition);
89 while ($tag = DBA::fetch($tags)) {
90 $taglist[] = $tag['term'];
93 // All servers who wants content with this tag
95 if (!empty($taglist)) {
96 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
97 while ($server = DBA::fetch($tagserver)) {
98 $tagserverlist[] = $server['gserver-id'];
102 // All adresses with the given id
103 if (!empty($tagserverlist)) {
104 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
105 while ($server = DBA::fetch($servers)) {
106 $serverlist[$server['url']] = $server['url'];
111 // Now we are collecting all relay contacts
112 foreach ($serverlist as $server_url) {
113 // We don't send messages to ourselves
114 if (Strings::compareLink($server_url, System::baseUrl())) {
117 $contact = self::getRelayContact($server_url);
118 if (is_bool($contact)) {
123 foreach ($contacts as $entry) {
124 if ($entry['batch'] == $contact['batch']) {
130 $contacts[] = $contact;
138 * @brief Return a contact for a given server address or creates a dummy entry
140 * @param string $server_url The url of the server
141 * @return array with the contact
144 private static function getRelayContact($server_url)
146 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
148 // Fetch the relay contact
149 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
150 'contact-type' => Contact::TYPE_RELAY];
151 $contact = DBA::selectFirst('contact', $fields, $condition);
153 if (DBA::isResult($contact)) {
154 if ($contact['archive'] || $contact['blocked']) {
159 self::setRelayContact($server_url);
161 $contact = DBA::selectFirst('contact', $fields, $condition);
162 if (DBA::isResult($contact)) {
167 // It should never happen that we arrive here
172 * @brief Update or insert a relay contact
174 * @param string $server_url The url of the server
175 * @param array $network_fields Optional network specific fields
178 public static function setRelayContact($server_url, array $network_fields = [])
180 $fields = ['created' => DateTimeFormat::utcNow(),
181 'name' => 'relay', 'nick' => 'relay',
182 'url' => $server_url, 'network' => Protocol::DIASPORA,
183 'batch' => $server_url . '/receive/public',
184 'rel' => Contact::FOLLOWER, 'blocked' => false,
185 'pending' => false, 'writable' => true];
187 $fields = array_merge($fields, $network_fields);
189 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
190 'contact-type' => Contact::TYPE_RELAY];
192 if (DBA::exists('contact', $condition)) {
193 unset($fields['created']);
196 DBA::update('contact', $fields, $condition, true);
200 * @brief Return a list of participating contacts for a thread
202 * This is used for the participation feature.
203 * One of the parameters is a contact array.
204 * This is done to avoid duplicates.
206 * @param integer $thread The id of the thread
207 * @param array $contacts The previously fetched contacts
209 * @return array of relay servers
212 public static function participantsForThread($thread, array $contacts)
214 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
215 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
216 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
217 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
218 WHERE `participation`.`iid` = ?", $thread);
220 while ($contact = DBA::fetch($r)) {
221 if (!empty($contact['fnetwork'])) {
222 $contact['network'] = $contact['fnetwork'];
224 unset($contact['fnetwork']);
226 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
227 $contact['batch'] = $contact['fbatch'];
229 unset($contact['fbatch']);
232 foreach ($contacts as $entry) {
233 if ($entry['batch'] == $contact['batch']) {
239 $contacts[] = $contact;
248 * @brief repairs a signature that was double encoded
250 * The function is unused at the moment. It was copied from the old implementation.
252 * @param string $signature The signature
253 * @param string $handle The handle of the signature owner
254 * @param integer $level This value is only set inside this function to avoid endless loops
256 * @return string the repaired signature
259 private static function repairSignature($signature, $handle = "", $level = 1)
261 if ($signature == "") {
265 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
266 $signature = base64_decode($signature);
267 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
269 // Do a recursive call to be able to fix even multiple levels
271 $signature = self::repairSignature($signature, $handle, ++$level);
279 * @brief verify the envelope and return the verified data
281 * @param string $envelope The magic envelope
283 * @return string verified data
284 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
285 * @throws \ImagickException
287 private static function verifyMagicEnvelope($envelope)
289 $basedom = XML::parseString($envelope);
291 if (!is_object($basedom)) {
292 Logger::log("Envelope is no XML file");
296 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
298 if (sizeof($children) == 0) {
299 Logger::log("XML has no children");
305 $data = Strings::base64UrlDecode($children->data);
306 $type = $children->data->attributes()->type[0];
308 $encoding = $children->encoding;
310 $alg = $children->alg;
312 $sig = Strings::base64UrlDecode($children->sig);
313 $key_id = $children->sig->attributes()->key_id[0];
315 $handle = Strings::base64UrlDecode($key_id);
318 $b64url_data = Strings::base64UrlEncode($data);
319 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
321 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
324 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
328 $key = self::key($handle);
330 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
334 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
336 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
344 * @brief encrypts data via AES
346 * @param string $key The AES key
347 * @param string $iv The IV (is used for CBC encoding)
348 * @param string $data The data that is to be encrypted
350 * @return string encrypted data
352 private static function aesEncrypt($key, $iv, $data)
354 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
358 * @brief decrypts data via AES
360 * @param string $key The AES key
361 * @param string $iv The IV (is used for CBC encoding)
362 * @param string $encrypted The encrypted data
364 * @return string decrypted data
366 private static function aesDecrypt($key, $iv, $encrypted)
368 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
372 * @brief: Decodes incoming Diaspora message in the new format
374 * @param array $importer Array of the importer user
375 * @param string $raw raw post message
376 * @param boolean $no_exit Don't do an http exit on error
379 * 'message' -> decoded Diaspora XML message
380 * 'author' -> author diaspora handle
381 * 'key' -> author public key (converted to pkcs#8)
382 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
383 * @throws \ImagickException
385 public static function decodeRaw(array $importer, $raw, $no_exit = false)
387 $data = json_decode($raw);
389 // Is it a private post? Then decrypt the outer Salmon
390 if (is_object($data)) {
391 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
392 $ciphertext = base64_decode($data->encrypted_magic_envelope);
394 $outer_key_bundle = '';
395 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
396 $j_outer_key_bundle = json_decode($outer_key_bundle);
398 if (!is_object($j_outer_key_bundle)) {
399 Logger::log('Outer Salmon did not verify. Discarding.');
403 throw new \Friendica\Network\HTTPException\BadRequestException();
407 $outer_iv = base64_decode($j_outer_key_bundle->iv);
408 $outer_key = base64_decode($j_outer_key_bundle->key);
410 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
415 $basedom = XML::parseString($xml);
417 if (!is_object($basedom)) {
418 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
422 throw new \Friendica\Network\HTTPException\BadRequestException();
426 $base = $basedom->children(NAMESPACE_SALMON_ME);
428 // Not sure if this cleaning is needed
429 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
431 // Build the signed data
432 $type = $base->data[0]->attributes()->type[0];
433 $encoding = $base->encoding;
435 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
437 // This is the signature
438 $signature = Strings::base64UrlDecode($base->sig);
440 // Get the senders' public key
441 $key_id = $base->sig[0]->attributes()->key_id[0];
442 $author_addr = base64_decode($key_id);
443 if ($author_addr == '') {
444 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
448 throw new \Friendica\Network\HTTPException\BadRequestException();
452 $key = self::key($author_addr);
454 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
458 throw new \Friendica\Network\HTTPException\BadRequestException();
462 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
464 Logger::log('Message did not verify. Discarding.');
468 throw new \Friendica\Network\HTTPException\BadRequestException();
472 return ['message' => (string)Strings::base64UrlDecode($base->data),
473 'author' => XML::unescape($author_addr),
474 'key' => (string)$key];
478 * @brief: Decodes incoming Diaspora message in the deprecated format
480 * @param array $importer Array of the importer user
481 * @param string $xml urldecoded Diaspora salmon
484 * 'message' -> decoded Diaspora XML message
485 * 'author' -> author diaspora handle
486 * 'key' -> author public key (converted to pkcs#8)
487 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
488 * @throws \ImagickException
490 public static function decode(array $importer, $xml)
493 $basedom = XML::parseString($xml);
495 if (!is_object($basedom)) {
496 Logger::log("XML is not parseable.");
499 $children = $basedom->children('https://joindiaspora.com/protocol');
501 $inner_aes_key = null;
504 if ($children->header) {
506 $author_link = str_replace('acct:', '', $children->header->author_id);
508 // This happens with posts from a relais
510 Logger::log("This is no private post in the old format", Logger::DEBUG);
514 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
516 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
517 $ciphertext = base64_decode($encrypted_header->ciphertext);
519 $outer_key_bundle = '';
520 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
522 $j_outer_key_bundle = json_decode($outer_key_bundle);
524 $outer_iv = base64_decode($j_outer_key_bundle->iv);
525 $outer_key = base64_decode($j_outer_key_bundle->key);
527 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
529 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
530 $idom = XML::parseString($decrypted);
532 $inner_iv = base64_decode($idom->iv);
533 $inner_aes_key = base64_decode($idom->aes_key);
535 $author_link = str_replace('acct:', '', $idom->author_id);
538 $dom = $basedom->children(NAMESPACE_SALMON_ME);
540 // figure out where in the DOM tree our data is hiding
543 if ($dom->provenance->data) {
544 $base = $dom->provenance;
545 } elseif ($dom->env->data) {
547 } elseif ($dom->data) {
552 Logger::log('unable to locate salmon data in xml');
553 throw new \Friendica\Network\HTTPException\BadRequestException();
557 // Stash the signature away for now. We have to find their key or it won't be good for anything.
558 $signature = Strings::base64UrlDecode($base->sig);
562 // strip whitespace so our data element will return to one big base64 blob
563 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
566 // stash away some other stuff for later
568 $type = $base->data[0]->attributes()->type[0];
569 $keyhash = $base->sig[0]->attributes()->keyhash[0];
570 $encoding = $base->encoding;
574 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
578 $data = Strings::base64UrlDecode($data);
582 $inner_decrypted = $data;
584 // Decode the encrypted blob
585 $inner_encrypted = base64_decode($data);
586 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
590 Logger::log('Could not retrieve author URI.');
591 throw new \Friendica\Network\HTTPException\BadRequestException();
593 // Once we have the author URI, go to the web and try to find their public key
594 // (first this will look it up locally if it is in the fcontact cache)
595 // This will also convert diaspora public key from pkcs#1 to pkcs#8
597 Logger::log('Fetching key for '.$author_link);
598 $key = self::key($author_link);
601 Logger::log('Could not retrieve author key.');
602 throw new \Friendica\Network\HTTPException\BadRequestException();
605 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
608 Logger::log('Message did not verify. Discarding.');
609 throw new \Friendica\Network\HTTPException\BadRequestException();
612 Logger::log('Message verified.');
614 return ['message' => (string)$inner_decrypted,
615 'author' => XML::unescape($author_link),
616 'key' => (string)$key];
621 * @brief Dispatches public messages and find the fitting receivers
623 * @param array $msg The post that will be dispatched
625 * @return int The message id of the generated message, "true" or "false" if there was an error
626 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
627 * @throws \ImagickException
629 public static function dispatchPublic($msg)
631 $enabled = intval(Config::get("system", "diaspora_enabled"));
633 Logger::log("diaspora is disabled");
637 if (!($fields = self::validPosting($msg))) {
638 Logger::log("Invalid posting");
642 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
643 $success = self::dispatch($importer, $msg, $fields);
649 * @brief Dispatches the different message types to the different functions
651 * @param array $importer Array of the importer user
652 * @param array $msg The post that will be dispatched
653 * @param SimpleXMLElement $fields SimpleXML object that contains the message
655 * @return int The message id of the generated message, "true" or "false" if there was an error
656 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
657 * @throws \ImagickException
659 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
661 // The sender is the handle of the contact that sent the message.
662 // This will often be different with relayed messages (for example "like" and "comment")
663 $sender = $msg["author"];
665 // This is only needed for private postings since this is already done for public ones before
666 if (is_null($fields)) {
668 if (!($fields = self::validPosting($msg))) {
669 Logger::log("Invalid posting");
676 $type = $fields->getName();
678 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
681 case "account_migration":
683 Logger::log('Message with type ' . $type . ' is not private, quitting.');
686 return self::receiveAccountMigration($importer, $fields);
688 case "account_deletion":
689 return self::receiveAccountDeletion($fields);
692 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
696 Logger::log('Message with type ' . $type . ' is not private, quitting.');
699 return self::receiveContactRequest($importer, $fields);
703 Logger::log('Message with type ' . $type . ' is not private, quitting.');
706 return self::receiveConversation($importer, $msg, $fields);
709 return self::receiveLike($importer, $sender, $fields);
713 Logger::log('Message with type ' . $type . ' is not private, quitting.');
716 return self::receiveMessage($importer, $fields);
718 case "participation":
720 Logger::log('Message with type ' . $type . ' is not private, quitting.');
723 return self::receiveParticipation($importer, $fields);
725 case "photo": // Not implemented
726 return self::receivePhoto($importer, $fields);
728 case "poll_participation": // Not implemented
729 return self::receivePollParticipation($importer, $fields);
733 Logger::log('Message with type ' . $type . ' is not private, quitting.');
736 return self::receiveProfile($importer, $fields);
739 return self::receiveReshare($importer, $fields, $msg["message"]);
742 return self::receiveRetraction($importer, $sender, $fields);
744 case "status_message":
745 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
748 Logger::log("Unknown message type ".$type);
754 * @brief Checks if a posting is valid and fetches the data fields.
756 * This function does not only check the signature.
757 * It also does the conversion between the old and the new diaspora format.
759 * @param array $msg Array with the XML, the sender handle and the sender signature
761 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
762 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
763 * @throws \ImagickException
765 private static function validPosting($msg)
767 $data = XML::parseString($msg["message"]);
769 if (!is_object($data)) {
770 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
774 // Is this the new or the old version?
775 if ($data->getName() == "XML") {
777 foreach ($data->post->children() as $child) {
785 $type = $element->getName();
788 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
790 // All retractions are handled identically from now on.
791 // In the new version there will only be "retraction".
792 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
793 $type = "retraction";
795 if ($type == "request") {
799 $fields = new SimpleXMLElement("<".$type."/>");
802 $author_signature = null;
803 $parent_author_signature = null;
805 foreach ($element->children() as $fieldname => $entry) {
807 // Translation for the old XML structure
808 if ($fieldname == "diaspora_handle") {
809 $fieldname = "author";
811 if ($fieldname == "participant_handles") {
812 $fieldname = "participants";
814 if (in_array($type, ["like", "participation"])) {
815 if ($fieldname == "target_type") {
816 $fieldname = "parent_type";
819 if ($fieldname == "sender_handle") {
820 $fieldname = "author";
822 if ($fieldname == "recipient_handle") {
823 $fieldname = "recipient";
825 if ($fieldname == "root_diaspora_id") {
826 $fieldname = "root_author";
828 if ($type == "status_message") {
829 if ($fieldname == "raw_message") {
833 if ($type == "retraction") {
834 if ($fieldname == "post_guid") {
835 $fieldname = "target_guid";
837 if ($fieldname == "type") {
838 $fieldname = "target_type";
843 if (($fieldname == "author_signature") && ($entry != "")) {
844 $author_signature = base64_decode($entry);
845 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
846 $parent_author_signature = base64_decode($entry);
847 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
848 if ($signed_data != "") {
852 $signed_data .= $entry;
854 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
855 || ($orig_type == "relayable_retraction")
857 XML::copy($entry, $fields, $fieldname);
861 // This is something that shouldn't happen at all.
862 if (in_array($type, ["status_message", "reshare", "profile"])) {
863 if ($msg["author"] != $fields->author) {
864 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
869 // Only some message types have signatures. So we quit here for the other types.
870 if (!in_array($type, ["comment", "like"])) {
873 // No author_signature? This is a must, so we quit.
874 if (!isset($author_signature)) {
875 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
879 if (isset($parent_author_signature)) {
880 $key = self::key($msg["author"]);
882 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
886 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
887 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);
892 $key = self::key($fields->author);
894 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
898 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
899 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);
907 * @brief Fetches the public key for a given handle
909 * @param string $handle The handle
911 * @return string The public key
912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
913 * @throws \ImagickException
915 private static function key($handle)
917 $handle = strval($handle);
919 Logger::log("Fetching diaspora key for: ".$handle);
921 $r = self::personByHandle($handle);
930 * @brief Fetches data for a given handle
932 * @param string $handle The handle
934 * @return array the queried data
935 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
936 * @throws \ImagickException
938 public static function personByHandle($handle)
942 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
943 if (DBA::isResult($person)) {
944 Logger::debug("In cache " . print_r($person, true));
946 // update record occasionally so it doesn't get stale
947 $d = strtotime($person["updated"]." +00:00");
948 if ($d < strtotime("now - 14 days")) {
952 if ($person["guid"] == "") {
957 if (!DBA::isResult($person) || $update) {
958 Logger::log("create or refresh", Logger::DEBUG);
959 $r = Probe::uri($handle, Protocol::DIASPORA);
961 // Note that Friendica contacts will return a "Diaspora person"
962 // if Diaspora connectivity is enabled on their server
963 if ($r && ($r["network"] === Protocol::DIASPORA)) {
964 self::updateFContact($r);
966 // Fetch the updated or added contact
967 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
968 if (!DBA::isResult($person)) {
979 * @brief Updates the fcontact table
981 * @param array $arr The fcontact data
984 private static function updateFContact($arr)
986 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
987 'request' => $arr["request"], 'nick' => $arr["nick"],
988 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
989 'batch' => $arr["batch"], 'notify' => $arr["notify"],
990 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
991 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
992 'updated' => DateTimeFormat::utcNow()];
994 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
996 DBA::update('fcontact', $fields, $condition, true);
1000 * @brief get a handle (user@domain.tld) from a given contact id
1002 * @param int $contact_id The id in the contact table
1003 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1005 * @return string the handle
1006 * @throws \Exception
1008 private static function handleFromContact($contact_id, $pcontact_id = 0)
1012 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1014 if ($pcontact_id != 0) {
1015 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1017 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1018 return strtolower($contact["addr"]);
1023 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1027 if (DBA::isResult($r)) {
1030 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1032 if ($contact['addr'] != "") {
1033 $handle = $contact['addr'];
1035 $baseurl_start = strpos($contact['url'], '://') + 3;
1036 // allows installations in a subdirectory--not sure how Diaspora will handle
1037 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1038 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1039 $handle = $contact['nick'].'@'.$baseurl;
1043 return strtolower($handle);
1047 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1050 * @param mixed $fcontact_guid Hexadecimal string guid
1052 * @return string the contact url or null
1053 * @throws \Exception
1055 public static function urlFromContactGuid($fcontact_guid)
1057 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1060 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1061 DBA::escape(Protocol::DIASPORA),
1062 DBA::escape($fcontact_guid)
1065 if (DBA::isResult($r)) {
1066 return $r[0]['url'];
1073 * @brief Get a contact id for a given handle
1075 * @todo Move to Friendica\Model\Contact
1077 * @param int $uid The user id
1078 * @param string $handle The handle in the format user@domain.tld
1080 * @return array Contact data
1081 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1082 * @throws \ImagickException
1084 private static function contactByHandle($uid, $handle)
1086 $cid = Contact::getIdForURL($handle, $uid);
1088 $handle_parts = explode("@", $handle);
1089 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1090 $cid = Contact::getIdForURL($nurl_sql, $uid);
1094 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1098 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1099 if (!DBA::isResult($contact)) {
1100 // This here shouldn't happen at all
1101 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1109 * @brief Check if posting is allowed for this contact
1111 * @param array $importer Array of the importer user
1112 * @param array $contact The contact that is checked
1113 * @param bool $is_comment Is the check for a comment?
1115 * @return bool is the contact allowed to post?
1117 private static function postAllow(array $importer, array $contact, $is_comment = false)
1120 * Perhaps we were already sharing with this person. Now they're sharing with us.
1121 * That makes us friends.
1122 * Normally this should have handled by getting a request - but this could get lost
1124 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1125 // It is not removed by now. Possibly the code is needed?
1126 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1129 // array('rel' => Contact::FRIEND, 'writable' => true),
1130 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1133 // $contact["rel"] = Contact::FRIEND;
1134 // Logger::log("defining user ".$contact["nick"]." as friend");
1137 // Contact server is blocked
1138 if (Network::isUrlBlocked($contact['url'])) {
1140 // We don't seem to like that person
1141 } elseif ($contact["blocked"]) {
1142 // Maybe blocked, don't accept.
1144 // We are following this person?
1145 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1146 // Yes, then it is fine.
1148 // Is it a post to a community?
1149 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1152 // Is the message a global user or a comment?
1153 } elseif (($importer["uid"] == 0) || $is_comment) {
1154 // Messages for the global users and comments are always accepted
1162 * @brief Fetches the contact id for a handle and checks if posting is allowed
1164 * @param array $importer Array of the importer user
1165 * @param string $handle The checked handle in the format user@domain.tld
1166 * @param bool $is_comment Is the check for a comment?
1168 * @return array The contact data
1169 * @throws \Exception
1171 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1173 $contact = self::contactByHandle($importer["uid"], $handle);
1175 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1176 // If a contact isn't found, we accept it anyway if it is a comment
1177 if ($is_comment && ($importer["uid"] != 0)) {
1178 return self::contactByHandle(0, $handle);
1179 } elseif ($is_comment) {
1186 if (!self::postAllow($importer, $contact, $is_comment)) {
1187 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1194 * @brief Does the message already exists on the system?
1196 * @param int $uid The user id
1197 * @param string $guid The guid of the message
1199 * @return int|bool message id if the message already was stored into the system - or false.
1200 * @throws \Exception
1202 private static function messageExists($uid, $guid)
1204 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1205 if (DBA::isResult($item)) {
1206 Logger::log("message ".$guid." already exists for user ".$uid);
1214 * @brief Checks for links to posts in a message
1216 * @param array $item The item array
1219 private static function fetchGuid(array $item)
1221 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1222 preg_replace_callback(
1224 function ($match) use ($item) {
1225 self::fetchGuidSub($match, $item);
1230 preg_replace_callback(
1231 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1232 function ($match) use ($item) {
1233 self::fetchGuidSub($match, $item);
1240 * @brief Checks for relative /people/* links in an item body to match local
1241 * contacts or prepends the remote host taken from the author link.
1243 * @param string $body The item body to replace links from
1244 * @param string $author_link The author link for missing local contact fallback
1246 * @return string the replaced string
1248 public static function replacePeopleGuid($body, $author_link)
1250 $return = preg_replace_callback(
1251 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1252 function ($match) use ($author_link) {
1254 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1255 // 1 => '0123456789abcdef'
1257 $handle = self::urlFromContactGuid($match[1]);
1260 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1262 // No local match, restoring absolute remote URL from author scheme and host
1263 $author_url = parse_url($author_link);
1264 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1276 * @brief sub function of "fetchGuid" which checks for links in messages
1278 * @param array $match array containing a link that has to be checked for a message link
1279 * @param array $item The item array
1281 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1282 * @throws \ImagickException
1284 private static function fetchGuidSub($match, $item)
1286 if (!self::storeByGuid($match[1], $item["author-link"])) {
1287 self::storeByGuid($match[1], $item["owner-link"]);
1292 * @brief Fetches an item with a given guid from a given server
1294 * @param string $guid the message guid
1295 * @param string $server The server address
1296 * @param int $uid The user id of the user
1298 * @return int the message id of the stored message or false
1299 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1300 * @throws \ImagickException
1302 private static function storeByGuid($guid, $server, $uid = 0)
1304 $serverparts = parse_url($server);
1306 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1310 $server = $serverparts["scheme"]."://".$serverparts["host"];
1312 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1314 $msg = self::message($guid, $server);
1320 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1322 // Now call the dispatcher
1323 return self::dispatchPublic($msg);
1327 * @brief Fetches a message from a server
1329 * @param string $guid message guid
1330 * @param string $server The url of the server
1331 * @param int $level Endless loop prevention
1334 * 'message' => The message XML
1335 * 'author' => The author handle
1336 * 'key' => The public key of the author
1337 * @throws \Exception
1339 private static function message($guid, $server, $level = 0)
1345 // This will work for new Diaspora servers and Friendica servers from 3.5
1346 $source_url = $server."/fetch/post/".urlencode($guid);
1348 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1350 $envelope = Network::fetchUrl($source_url);
1352 Logger::log("Envelope was fetched.", Logger::DEBUG);
1353 $x = self::verifyMagicEnvelope($envelope);
1355 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1357 Logger::log("Envelope was verified.", Logger::DEBUG);
1367 $source_xml = XML::parseString($x);
1369 if (!is_object($source_xml)) {
1373 if ($source_xml->post->reshare) {
1374 // Reshare of a reshare - old Diaspora version
1375 Logger::log("Message is a reshare", Logger::DEBUG);
1376 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1377 } elseif ($source_xml->getName() == "reshare") {
1378 // Reshare of a reshare - new Diaspora version
1379 Logger::log("Message is a new reshare", Logger::DEBUG);
1380 return self::message($source_xml->root_guid, $server, ++$level);
1385 // Fetch the author - for the old and the new Diaspora version
1386 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1387 $author = (string)$source_xml->post->status_message->diaspora_handle;
1388 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1389 $author = (string)$source_xml->author;
1392 // If this isn't a "status_message" then quit
1394 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1398 $msg = ["message" => $x, "author" => $author];
1400 $msg["key"] = self::key($msg["author"]);
1406 * @brief Fetches the item record of a given guid
1408 * @param int $uid The user id
1409 * @param string $guid message guid
1410 * @param string $author The handle of the item
1411 * @param array $contact The contact of the item owner
1413 * @return array the item record
1414 * @throws \Exception
1416 private static function parentItem($uid, $guid, $author, array $contact)
1418 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1419 'author-name', 'author-link', 'author-avatar',
1420 'owner-name', 'owner-link', 'owner-avatar'];
1421 $condition = ['uid' => $uid, 'guid' => $guid];
1422 $item = Item::selectFirst($fields, $condition);
1424 if (!DBA::isResult($item)) {
1425 $person = self::personByHandle($author);
1426 $result = self::storeByGuid($guid, $person["url"], $uid);
1428 // We don't have an url for items that arrived at the public dispatcher
1429 if (!$result && !empty($contact["url"])) {
1430 $result = self::storeByGuid($guid, $contact["url"], $uid);
1434 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1436 $item = Item::selectFirst($fields, $condition);
1440 if (!DBA::isResult($item)) {
1441 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1444 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1450 * @brief returns contact details
1452 * @param array $def_contact The default contact if the person isn't found
1453 * @param array $person The record of the person
1454 * @param int $uid The user id
1457 * 'cid' => contact id
1458 * 'network' => network type
1459 * @throws \Exception
1461 private static function authorContactByUrl($def_contact, $person, $uid)
1463 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1464 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1465 if (DBA::isResult($contact)) {
1466 $cid = $contact["id"];
1467 $network = $contact["network"];
1469 $cid = $def_contact["id"];
1470 $network = Protocol::DIASPORA;
1473 return ["cid" => $cid, "network" => $network];
1477 * @brief Is the profile a hubzilla profile?
1479 * @param string $url The profile link
1481 * @return bool is it a hubzilla server?
1483 public static function isRedmatrix($url)
1485 return(strstr($url, "/channel/"));
1489 * @brief Generate a post link with a given handle and message guid
1491 * @param string $addr The user handle
1492 * @param string $guid message guid
1493 * @param string $parent_guid optional parent guid
1495 * @return string the post link
1496 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1497 * @throws \ImagickException
1499 private static function plink($addr, $guid, $parent_guid = '')
1501 $contact = Contact::getDetailsByAddr($addr);
1505 if ($parent_guid != '') {
1506 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1508 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1512 if ($contact["network"] == Protocol::DFRN) {
1513 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1516 if (self::isRedmatrix($contact["url"])) {
1517 return $contact["url"] . "/?f=&mid=" . $guid;
1520 if ($parent_guid != '') {
1521 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1523 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1528 * @brief Receives account migration
1530 * @param array $importer Array of the importer user
1531 * @param object $data The message object
1533 * @return bool Success
1534 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1535 * @throws \ImagickException
1537 private static function receiveAccountMigration(array $importer, $data)
1539 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1540 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1541 $signature = Strings::escapeTags(XML::unescape($data->signature));
1543 $contact = self::contactByHandle($importer["uid"], $old_handle);
1545 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1549 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1552 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1553 $key = self::key($old_handle);
1554 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1555 Logger::log('No valid signature for migration.');
1559 // Update the profile
1560 self::receiveProfile($importer, $data->profile);
1562 // change the technical stuff in contact and gcontact
1563 $data = Probe::uri($new_handle);
1564 if ($data['network'] == Protocol::PHANTOM) {
1565 Logger::log('Account for '.$new_handle." couldn't be probed.");
1569 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1570 'name' => $data['name'], 'nick' => $data['nick'],
1571 'addr' => $data['addr'], 'batch' => $data['batch'],
1572 'notify' => $data['notify'], 'poll' => $data['poll'],
1573 'network' => $data['network']];
1575 DBA::update('contact', $fields, ['addr' => $old_handle]);
1577 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1578 'name' => $data['name'], 'nick' => $data['nick'],
1579 'addr' => $data['addr'], 'connect' => $data['addr'],
1580 'notify' => $data['notify'], 'photo' => $data['photo'],
1581 'server_url' => $data['baseurl'], 'network' => $data['network']];
1583 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1585 Logger::log('Contacts are updated.');
1591 * @brief Processes an account deletion
1593 * @param object $data The message object
1595 * @return bool Success
1596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1598 private static function receiveAccountDeletion($data)
1600 $author = Strings::escapeTags(XML::unescape($data->author));
1602 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1603 while ($contact = DBA::fetch($contacts)) {
1604 Contact::remove($contact["id"]);
1607 DBA::delete('gcontact', ['addr' => $author]);
1609 Logger::log('Removed contacts for ' . $author);
1615 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1617 * @param string $author Author handle
1618 * @param string $guid Message guid
1619 * @param boolean $onlyfound Only return uri when found in the database
1621 * @return string The constructed uri or the one from our database
1622 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1623 * @throws \ImagickException
1625 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1627 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1628 if (DBA::isResult($item)) {
1629 return $item["uri"];
1630 } elseif (!$onlyfound) {
1631 $person = self::personByHandle($author);
1633 $parts = parse_url($person['url']);
1634 unset($parts['path']);
1635 $host_url = Network::unparseURL($parts);
1637 return $host_url . '/objects/' . $guid;
1644 * @brief Fetch the guid from our database with a given uri
1646 * @param string $uri Message uri
1647 * @param string $uid Author handle
1649 * @return string The post guid
1650 * @throws \Exception
1652 private static function getGuidFromUri($uri, $uid)
1654 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1655 if (DBA::isResult($item)) {
1656 return $item["guid"];
1663 * @brief Find the best importer for a comment, like, ...
1665 * @param string $guid The guid of the item
1667 * @return array|boolean the origin owner of that post - or false
1668 * @throws \Exception
1670 private static function importerForGuid($guid)
1672 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1673 if (DBA::isResult($item)) {
1674 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1675 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1676 if (DBA::isResult($contact)) {
1684 * @brief Processes an incoming comment
1686 * @param array $importer Array of the importer user
1687 * @param string $sender The sender of the message
1688 * @param object $data The message object
1689 * @param string $xml The original XML of the message
1691 * @return int The message id of the generated comment or "false" if there was an error
1692 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1693 * @throws \ImagickException
1695 private static function receiveComment(array $importer, $sender, $data, $xml)
1697 $author = Strings::escapeTags(XML::unescape($data->author));
1698 $guid = Strings::escapeTags(XML::unescape($data->guid));
1699 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1700 $text = XML::unescape($data->text);
1702 if (isset($data->created_at)) {
1703 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1705 $created_at = DateTimeFormat::utcNow();
1708 if (isset($data->thread_parent_guid)) {
1709 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1710 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1715 $contact = self::allowedContactByHandle($importer, $sender, true);
1720 $message_id = self::messageExists($importer["uid"], $guid);
1725 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1726 if (!$parent_item) {
1730 $person = self::personByHandle($author);
1731 if (!is_array($person)) {
1732 Logger::log("unable to find author details");
1736 // Fetch the contact id - if we know this contact
1737 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1741 $datarray["uid"] = $importer["uid"];
1742 $datarray["contact-id"] = $author_contact["cid"];
1743 $datarray["network"] = $author_contact["network"];
1745 $datarray["author-link"] = $person["url"];
1746 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1748 $datarray["owner-link"] = $contact["url"];
1749 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1751 $datarray["guid"] = $guid;
1752 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1754 $datarray["verb"] = ACTIVITY_POST;
1755 $datarray["gravity"] = GRAVITY_COMMENT;
1757 if ($thr_uri != "") {
1758 $datarray["parent-uri"] = $thr_uri;
1760 $datarray["parent-uri"] = $parent_item["uri"];
1763 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1765 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1766 $datarray["source"] = $xml;
1768 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1770 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1772 $body = Markdown::toBBCode($text);
1774 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1776 self::fetchGuid($datarray);
1778 // If we are the origin of the parent we store the original data.
1779 // We notify our followers during the item storage.
1780 if ($parent_item["origin"]) {
1781 $datarray['diaspora_signed_text'] = json_encode($data);
1784 $message_id = Item::insert($datarray);
1786 if ($message_id <= 0) {
1791 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1792 if ($datarray['uid'] == 0) {
1793 Item::distribute($message_id, json_encode($data));
1801 * @brief processes and stores private messages
1803 * @param array $importer Array of the importer user
1804 * @param array $contact The contact of the message
1805 * @param object $data The message object
1806 * @param array $msg Array of the processed message, author handle and key
1807 * @param object $mesg The private message
1808 * @param array $conversation The conversation record to which this message belongs
1810 * @return bool "true" if it was successful
1811 * @throws \Exception
1813 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1815 $author = Strings::escapeTags(XML::unescape($data->author));
1816 $guid = Strings::escapeTags(XML::unescape($data->guid));
1817 $subject = Strings::escapeTags(XML::unescape($data->subject));
1819 // "diaspora_handle" is the element name from the old version
1820 // "author" is the element name from the new version
1821 if ($mesg->author) {
1822 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1823 } elseif ($mesg->diaspora_handle) {
1824 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1829 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1830 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1831 $msg_text = XML::unescape($mesg->text);
1832 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1834 if ($msg_conversation_guid != $guid) {
1835 Logger::log("message conversation guid does not belong to the current conversation.");
1839 $body = Markdown::toBBCode($msg_text);
1840 $message_uri = $msg_author.":".$msg_guid;
1842 $person = self::personByHandle($msg_author);
1846 if (DBA::exists('mail', ['guid' => $msg_guid, 'uid' => $importer["uid"]])) {
1847 Logger::log("duplicate message already delivered.", Logger::DEBUG);
1851 DBA::insert('mail', [
1852 'uid' => $importer['uid'],
1853 'guid' => $msg_guid,
1854 'convid' => $conversation['id'],
1855 'from-name' => $person['name'],
1856 'from-photo' => $person['photo'],
1857 'from-url' => $person['url'],
1858 'contact-id' => $contact['id'],
1859 'title' => $subject,
1863 'uri' => $message_uri,
1864 'parent-uri' => $author . ':' . $guid,
1865 'created' => $msg_created_at
1868 $message_id = DBA::lastInsertId();
1872 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1875 "type" => NOTIFY_MAIL,
1876 "notify_flags" => $importer["notify-flags"],
1877 "language" => $importer["language"],
1878 "to_name" => $importer["username"],
1879 "to_email" => $importer["email"],
1880 "uid" => $importer["uid"],
1881 "item" => ["id" => $message_id, "title" => $subject, "subject" => $subject, "body" => $body],
1882 "parent" => $conversation["id"],
1883 "source_name" => $person["name"],
1884 "source_link" => $person["url"],
1885 "source_photo" => $person["photo"],
1886 "verb" => ACTIVITY_POST,
1894 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1896 * @param array $importer Array of the importer user
1897 * @param array $msg Array of the processed message, author handle and key
1898 * @param object $data The message object
1900 * @return bool Success
1901 * @throws \Exception
1903 private static function receiveConversation(array $importer, $msg, $data)
1905 $author = Strings::escapeTags(XML::unescape($data->author));
1906 $guid = Strings::escapeTags(XML::unescape($data->guid));
1907 $subject = Strings::escapeTags(XML::unescape($data->subject));
1908 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1909 $participants = Strings::escapeTags(XML::unescape($data->participants));
1911 $messages = $data->message;
1913 if (!count($messages)) {
1914 Logger::log("empty conversation");
1918 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1923 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1924 if (!DBA::isResult($conversation)) {
1926 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1927 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1928 intval($importer["uid"]),
1930 DBA::escape($author),
1931 DBA::escape($created_at),
1932 DBA::escape(DateTimeFormat::utcNow()),
1933 DBA::escape($subject),
1934 DBA::escape($participants)
1937 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1940 if (!$conversation) {
1941 Logger::log("unable to create conversation.");
1945 foreach ($messages as $mesg) {
1946 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1953 * @brief Processes "like" messages
1955 * @param array $importer Array of the importer user
1956 * @param string $sender The sender of the message
1957 * @param object $data The message object
1959 * @return int The message id of the generated like or "false" if there was an error
1960 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1961 * @throws \ImagickException
1963 private static function receiveLike(array $importer, $sender, $data)
1965 $author = Strings::escapeTags(XML::unescape($data->author));
1966 $guid = Strings::escapeTags(XML::unescape($data->guid));
1967 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1968 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1969 $positive = Strings::escapeTags(XML::unescape($data->positive));
1971 // likes on comments aren't supported by Diaspora - only on posts
1972 // But maybe this will be supported in the future, so we will accept it.
1973 if (!in_array($parent_type, ["Post", "Comment"])) {
1977 $contact = self::allowedContactByHandle($importer, $sender, true);
1982 $message_id = self::messageExists($importer["uid"], $guid);
1987 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1988 if (!$parent_item) {
1992 $person = self::personByHandle($author);
1993 if (!is_array($person)) {
1994 Logger::log("unable to find author details");
1998 // Fetch the contact id - if we know this contact
1999 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2001 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2002 // We would accept this anyhow.
2003 if ($positive == "true") {
2004 $verb = ACTIVITY_LIKE;
2006 $verb = ACTIVITY_DISLIKE;
2011 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2013 $datarray["uid"] = $importer["uid"];
2014 $datarray["contact-id"] = $author_contact["cid"];
2015 $datarray["network"] = $author_contact["network"];
2017 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2018 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2020 $datarray["guid"] = $guid;
2021 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2023 $datarray["verb"] = $verb;
2024 $datarray["gravity"] = GRAVITY_ACTIVITY;
2025 $datarray["parent-uri"] = $parent_item["uri"];
2027 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2029 $datarray["body"] = $verb;
2031 // Diaspora doesn't provide a date for likes
2032 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2034 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2035 if ($parent_item["id"] != $parent_item["parent"]) {
2036 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2037 $origin = $toplevel["origin"];
2039 $origin = $parent_item["origin"];
2042 // If we are the origin of the parent we store the original data.
2043 // We notify our followers during the item storage.
2045 $datarray['diaspora_signed_text'] = json_encode($data);
2048 $message_id = Item::insert($datarray);
2050 if ($message_id <= 0) {
2055 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2056 if ($datarray['uid'] == 0) {
2057 Item::distribute($message_id, json_encode($data));
2065 * @brief Processes private messages
2067 * @param array $importer Array of the importer user
2068 * @param object $data The message object
2070 * @return bool Success?
2071 * @throws \Exception
2073 private static function receiveMessage(array $importer, $data)
2075 $author = Strings::escapeTags(XML::unescape($data->author));
2076 $guid = Strings::escapeTags(XML::unescape($data->guid));
2077 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2078 $text = XML::unescape($data->text);
2079 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2081 $contact = self::allowedContactByHandle($importer, $author, true);
2086 $conversation = null;
2088 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2089 $conversation = DBA::selectFirst('conv', [], $condition);
2091 if (!DBA::isResult($conversation)) {
2092 Logger::log("conversation not available.");
2096 $message_uri = $author.":".$guid;
2098 $person = self::personByHandle($author);
2100 Logger::log("unable to find author details");
2104 $body = Markdown::toBBCode($text);
2106 $body = self::replacePeopleGuid($body, $person["url"]);
2110 if (DBA::exists('mail', ['guid' => $guid, 'uid' => $importer["uid"]])) {
2111 Logger::log("duplicate message already delivered.", Logger::DEBUG);
2115 DBA::insert('mail', [
2116 'uid' => $importer['uid'],
2118 'convid' => $conversation['id'],
2119 'from-name' => $person['name'],
2120 'from-photo' => $person['photo'],
2121 'from-url' => $person['url'],
2122 'contact-id' => $contact['id'],
2123 'title' => $conversation['subject'],
2127 'uri' => $message_uri,
2128 'parent-uri' => $author.":".$conversation['guid'],
2129 'created' => $created_at
2132 $message_id = DBA::lastInsertId();
2136 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2139 "type" => NOTIFY_MAIL,
2140 "notify_flags" => $importer["notify-flags"],
2141 "language" => $importer["language"],
2142 "to_name" => $importer["username"],
2143 "to_email" => $importer["email"],
2144 "uid" => $importer["uid"],
2145 "item" => ["id" => $message_id, "title" => $conversation["subject"], "subject" => $conversation["subject"], "body" => $body],
2146 "parent" => $conversation["id"],
2147 "source_name" => $person["name"],
2148 "source_link" => $person["url"],
2149 "source_photo" => $person["photo"],
2150 "verb" => ACTIVITY_POST,
2158 * @brief Processes participations - unsupported by now
2160 * @param array $importer Array of the importer user
2161 * @param object $data The message object
2163 * @return bool always true
2164 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2165 * @throws \ImagickException
2167 private static function receiveParticipation(array $importer, $data)
2169 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2170 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2172 $contact_id = Contact::getIdForURL($author);
2174 Logger::log('Contact not found: '.$author);
2178 $person = self::personByHandle($author);
2179 if (!is_array($person)) {
2180 Logger::log("Person not found: ".$author);
2184 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2185 if (!DBA::isResult($item)) {
2186 Logger::log('Item not found, no origin or private: '.$parent_guid);
2190 $author_parts = explode('@', $author);
2191 if (isset($author_parts[1])) {
2192 $server = $author_parts[1];
2194 // Should never happen
2198 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2200 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2201 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2204 // Send all existing comments and likes to the requesting server
2205 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2206 while ($comment = Item::fetch($comments)) {
2207 if ($comment['id'] == $comment['parent']) {
2210 if ($comment['verb'] == ACTIVITY_POST) {
2211 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2213 $cmd = $comment['self'] ? 'like' : 'comment-import';
2215 Logger::log("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, Logger::DEBUG);
2216 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2218 DBA::close($comments);
2224 * @brief Processes photos - unneeded
2226 * @param array $importer Array of the importer user
2227 * @param object $data The message object
2229 * @return bool always true
2231 private static function receivePhoto(array $importer, $data)
2233 // There doesn't seem to be a reason for this function,
2234 // since the photo data is transmitted in the status message as well
2239 * @brief Processes poll participations - unssupported
2241 * @param array $importer Array of the importer user
2242 * @param object $data The message object
2244 * @return bool always true
2246 private static function receivePollParticipation(array $importer, $data)
2248 // We don't support polls by now
2253 * @brief Processes incoming profile updates
2255 * @param array $importer Array of the importer user
2256 * @param object $data The message object
2258 * @return bool Success
2259 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2260 * @throws \ImagickException
2262 private static function receiveProfile(array $importer, $data)
2264 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2266 $contact = self::contactByHandle($importer["uid"], $author);
2271 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2272 $image_url = XML::unescape($data->image_url);
2273 $birthday = XML::unescape($data->birthday);
2274 $gender = XML::unescape($data->gender);
2275 $about = Markdown::toBBCode(XML::unescape($data->bio));
2276 $location = Markdown::toBBCode(XML::unescape($data->location));
2277 $searchable = (XML::unescape($data->searchable) == "true");
2278 $nsfw = (XML::unescape($data->nsfw) == "true");
2279 $tags = XML::unescape($data->tag_string);
2281 $tags = explode("#", $tags);
2284 foreach ($tags as $tag) {
2285 $tag = trim(strtolower($tag));
2291 $keywords = implode(", ", $keywords);
2293 $handle_parts = explode("@", $author);
2294 $nick = $handle_parts[0];
2297 $name = $handle_parts[0];
2300 if (preg_match("|^https?://|", $image_url) === 0) {
2301 $image_url = "http://".$handle_parts[1].$image_url;
2304 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2306 // Generic birthday. We don't know the timezone. The year is irrelevant.
2308 $birthday = str_replace("1000", "1901", $birthday);
2310 if ($birthday != "") {
2311 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2314 // this is to prevent multiple birthday notifications in a single year
2315 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2317 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2318 $birthday = $contact["bd"];
2321 $fields = ['name' => $name, 'location' => $location,
2322 'name-date' => DateTimeFormat::utcNow(),
2323 'about' => $about, 'gender' => $gender,
2324 'addr' => $author, 'nick' => $nick,
2325 'keywords' => $keywords];
2327 if (!empty($birthday)) {
2328 $fields['bd'] = $birthday;
2331 DBA::update('contact', $fields, ['id' => $contact['id']]);
2333 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2334 "photo" => $image_url, "name" => $name, "location" => $location,
2335 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2336 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2337 "hide" => !$searchable, "nsfw" => $nsfw];
2339 $gcid = GContact::update($gcontact);
2341 GContact::link($gcid, $importer["uid"], $contact["id"]);
2343 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2349 * @brief Processes incoming friend requests
2351 * @param array $importer Array of the importer user
2352 * @param array $contact The contact that send the request
2354 * @throws \Exception
2356 private static function receiveRequestMakeFriend(array $importer, array $contact)
2358 if ($contact["rel"] == Contact::SHARING) {
2361 ['rel' => Contact::FRIEND, 'writable' => true],
2362 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2368 * @brief Processes incoming sharing notification
2370 * @param array $importer Array of the importer user
2371 * @param object $data The message object
2373 * @return bool Success
2374 * @throws \Exception
2376 private static function receiveContactRequest(array $importer, $data)
2378 $author = XML::unescape($data->author);
2379 $recipient = XML::unescape($data->recipient);
2381 if (!$author || !$recipient) {
2385 // the current protocol version doesn't know these fields
2386 // That means that we will assume their existance
2387 if (isset($data->following)) {
2388 $following = (XML::unescape($data->following) == "true");
2393 if (isset($data->sharing)) {
2394 $sharing = (XML::unescape($data->sharing) == "true");
2399 $contact = self::contactByHandle($importer["uid"], $author);
2401 // perhaps we were already sharing with this person. Now they're sharing with us.
2402 // That makes us friends.
2405 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2406 self::receiveRequestMakeFriend($importer, $contact);
2408 // refetch the contact array
2409 $contact = self::contactByHandle($importer["uid"], $author);
2411 // If we are now friends, we are sending a share message.
2412 // Normally we needn't to do so, but the first message could have been vanished.
2413 if (in_array($contact["rel"], [Contact::FRIEND])) {
2414 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2415 if (DBA::isResult($user)) {
2416 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2417 self::sendShare($user, $contact);
2422 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2423 Contact::removeFollower($importer, $contact);
2428 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2429 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2431 } elseif (!$following && !$sharing) {
2432 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2434 } elseif (!$following && $sharing) {
2435 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2436 } elseif ($following && $sharing) {
2437 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2438 } elseif ($following && !$sharing) {
2439 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2442 $ret = self::personByHandle($author);
2444 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2445 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2449 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2452 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2453 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2454 intval($importer["uid"]),
2455 DBA::escape($ret["network"]),
2456 DBA::escape($ret["addr"]),
2457 DateTimeFormat::utcNow(),
2458 DBA::escape($ret["url"]),
2459 DBA::escape(Strings::normaliseLink($ret["url"])),
2460 DBA::escape($batch),
2461 DBA::escape($ret["name"]),
2462 DBA::escape($ret["nick"]),
2463 DBA::escape($ret["photo"]),
2464 DBA::escape($ret["pubkey"]),
2465 DBA::escape($ret["notify"]),
2466 DBA::escape($ret["poll"]),
2471 // find the contact record we just created
2473 $contact_record = self::contactByHandle($importer["uid"], $author);
2475 if (!$contact_record) {
2476 Logger::log("unable to locate newly created contact record.");
2480 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2482 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2484 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2486 if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
2487 Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2489 $hash = Strings::getRandomHex().(string)time(); // Generate a confirm_key
2492 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2493 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2494 intval($importer["uid"]),
2495 intval($contact_record["id"]),
2498 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2500 DBA::escape(DateTimeFormat::utcNow())
2503 // automatic friend approval
2505 Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2507 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2510 * technically they are sharing with us (Contact::SHARING),
2511 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2512 * we are going to change the relationship and make them a follower.
2514 if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
2515 $new_relation = Contact::FRIEND;
2516 } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
2517 $new_relation = Contact::SHARING;
2519 $new_relation = Contact::FOLLOWER;
2523 "UPDATE `contact` SET `rel` = %d,
2531 intval($new_relation),
2532 DBA::escape(DateTimeFormat::utcNow()),
2533 DBA::escape(DateTimeFormat::utcNow()),
2534 intval($contact_record["id"])
2537 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2538 if (DBA::isResult($user)) {
2539 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2540 self::sendShare($user, $contact_record);
2542 // Send the profile data, maybe it weren't transmitted before
2543 self::sendProfile($importer["uid"], [$contact_record]);
2551 * @brief Fetches a message with a given guid
2553 * @param string $guid message guid
2554 * @param string $orig_author handle of the original post
2555 * @return array The fetched item
2556 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2557 * @throws \ImagickException
2559 public static function originalItem($guid, $orig_author)
2562 Logger::log('Empty guid. Quitting.');
2566 // Do we already have this item?
2567 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2568 'author-name', 'author-link', 'author-avatar'];
2569 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2570 $item = Item::selectFirst($fields, $condition);
2572 if (DBA::isResult($item)) {
2573 Logger::log("reshared message ".$guid." already exists on system.");
2575 // Maybe it is already a reshared item?
2576 // Then refetch the content, if it is a reshare from a reshare.
2577 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2578 if (self::isReshare($item["body"], true)) {
2580 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2581 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2583 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2585 // Add OEmbed and other information to the body
2586 $item["body"] = add_page_info_to_body($item["body"], false, true);
2594 if (!DBA::isResult($item)) {
2595 if (empty($orig_author)) {
2596 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2600 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2601 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2602 $stored = self::storeByGuid($guid, $server);
2605 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2606 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2607 $stored = self::storeByGuid($guid, $server);
2611 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2612 'author-name', 'author-link', 'author-avatar'];
2613 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2614 $item = Item::selectFirst($fields, $condition);
2616 if (DBA::isResult($item)) {
2617 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2618 if (self::isReshare($item["body"], false)) {
2619 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2620 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2631 * @brief Stores a reshare activity
2633 * @param array $item Array of reshare post
2634 * @param integer $parent_message_id Id of the parent post
2635 * @param string $guid GUID string of reshare action
2636 * @param string $author Author handle
2638 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2640 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2644 $datarray['uid'] = $item['uid'];
2645 $datarray['contact-id'] = $item['contact-id'];
2646 $datarray['network'] = $item['network'];
2648 $datarray['author-link'] = $item['author-link'];
2649 $datarray['author-id'] = $item['author-id'];
2651 $datarray['owner-link'] = $datarray['author-link'];
2652 $datarray['owner-id'] = $datarray['author-id'];
2654 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2655 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2656 $datarray['parent-uri'] = $parent['uri'];
2658 $datarray['verb'] = $datarray['body'] = ACTIVITY2_ANNOUNCE;
2659 $datarray['gravity'] = GRAVITY_ACTIVITY;
2660 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
2662 $datarray['protocol'] = $item['protocol'];
2664 $datarray['plink'] = self::plink($author, $datarray['guid']);
2665 $datarray['private'] = $item['private'];
2666 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2668 $message_id = Item::insert($datarray);
2671 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2672 if ($datarray['uid'] == 0) {
2673 Item::distribute($message_id);
2679 * @brief Processes a reshare message
2681 * @param array $importer Array of the importer user
2682 * @param object $data The message object
2683 * @param string $xml The original XML of the message
2685 * @return int the message id
2686 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2687 * @throws \ImagickException
2689 private static function receiveReshare(array $importer, $data, $xml)
2691 $author = Strings::escapeTags(XML::unescape($data->author));
2692 $guid = Strings::escapeTags(XML::unescape($data->guid));
2693 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2694 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2695 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2696 /// @todo handle unprocessed property "provider_display_name"
2697 $public = Strings::escapeTags(XML::unescape($data->public));
2699 $contact = self::allowedContactByHandle($importer, $author, false);
2704 $message_id = self::messageExists($importer["uid"], $guid);
2709 $original_item = self::originalItem($root_guid, $root_author);
2710 if (!$original_item) {
2714 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2718 $datarray["uid"] = $importer["uid"];
2719 $datarray["contact-id"] = $contact["id"];
2720 $datarray["network"] = Protocol::DIASPORA;
2722 $datarray["author-link"] = $contact["url"];
2723 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2725 $datarray["owner-link"] = $datarray["author-link"];
2726 $datarray["owner-id"] = $datarray["author-id"];
2728 $datarray["guid"] = $guid;
2729 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2731 $datarray["verb"] = ACTIVITY_POST;
2732 $datarray["gravity"] = GRAVITY_PARENT;
2734 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2735 $datarray["source"] = $xml;
2737 $prefix = share_header(
2738 $original_item["author-name"],
2739 $original_item["author-link"],
2740 $original_item["author-avatar"],
2741 $original_item["guid"],
2742 $original_item["created"],
2745 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2747 $datarray["tag"] = $original_item["tag"];
2748 $datarray["app"] = $original_item["app"];
2750 $datarray["plink"] = self::plink($author, $guid);
2751 $datarray["private"] = (($public == "false") ? 1 : 0);
2752 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2754 $datarray["object-type"] = $original_item["object-type"];
2756 self::fetchGuid($datarray);
2757 $message_id = Item::insert($datarray);
2759 self::sendParticipation($contact, $datarray);
2761 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2762 if ($root_message_id) {
2763 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2767 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2768 if ($datarray['uid'] == 0) {
2769 Item::distribute($message_id);
2778 * @brief Processes retractions
2780 * @param array $importer Array of the importer user
2781 * @param array $contact The contact of the item owner
2782 * @param object $data The message object
2784 * @return bool success
2785 * @throws \Exception
2787 private static function itemRetraction(array $importer, array $contact, $data)
2789 $author = Strings::escapeTags(XML::unescape($data->author));
2790 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2791 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2793 $person = self::personByHandle($author);
2794 if (!is_array($person)) {
2795 Logger::log("unable to find author detail for ".$author);
2799 if (empty($contact["url"])) {
2800 $contact["url"] = $person["url"];
2803 // Fetch items that are about to be deleted
2804 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2806 // When we receive a public retraction, we delete every item that we find.
2807 if ($importer['uid'] == 0) {
2808 $condition = ['guid' => $target_guid, 'deleted' => false];
2810 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2813 $r = Item::select($fields, $condition);
2814 if (!DBA::isResult($r)) {
2815 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2819 while ($item = Item::fetch($r)) {
2820 if (strstr($item['file'], '[')) {
2821 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2825 // Fetch the parent item
2826 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2828 // Only delete it if the parent author really fits
2829 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2830 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2834 Item::delete(['id' => $item['id']]);
2836 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2843 * @brief Receives retraction messages
2845 * @param array $importer Array of the importer user
2846 * @param string $sender The sender of the message
2847 * @param object $data The message object
2849 * @return bool Success
2850 * @throws \Exception
2852 private static function receiveRetraction(array $importer, $sender, $data)
2854 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2856 $contact = self::contactByHandle($importer["uid"], $sender);
2857 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2858 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2866 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2868 switch ($target_type) {
2873 case "StatusMessage":
2874 return self::itemRetraction($importer, $contact, $data);
2876 case "PollParticipation":
2878 // Currently unsupported
2882 Logger::log("Unknown target type ".$target_type);
2889 * @brief Receives status messages
2891 * @param array $importer Array of the importer user
2892 * @param SimpleXMLElement $data The message object
2893 * @param string $xml The original XML of the message
2895 * @return int The message id of the newly created item
2896 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2897 * @throws \ImagickException
2899 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2901 $author = Strings::escapeTags(XML::unescape($data->author));
2902 $guid = Strings::escapeTags(XML::unescape($data->guid));
2903 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2904 $public = Strings::escapeTags(XML::unescape($data->public));
2905 $text = XML::unescape($data->text);
2906 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2908 $contact = self::allowedContactByHandle($importer, $author, false);
2913 $message_id = self::messageExists($importer["uid"], $guid);
2919 if ($data->location) {
2920 foreach ($data->location->children() as $fieldname => $data) {
2921 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2925 $body = Markdown::toBBCode($text);
2929 // Attach embedded pictures to the body
2931 foreach ($data->photo as $photo) {
2932 $body = "[img]".XML::unescape($photo->remote_photo_path).
2933 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2936 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2938 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2940 // Add OEmbed and other information to the body
2941 if (!self::isRedmatrix($contact["url"])) {
2942 $body = add_page_info_to_body($body, false, true);
2946 /// @todo enable support for polls
2947 //if ($data->poll) {
2948 // foreach ($data->poll AS $poll)
2953 /// @todo enable support for events
2955 $datarray["uid"] = $importer["uid"];
2956 $datarray["contact-id"] = $contact["id"];
2957 $datarray["network"] = Protocol::DIASPORA;
2959 $datarray["author-link"] = $contact["url"];
2960 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2962 $datarray["owner-link"] = $datarray["author-link"];
2963 $datarray["owner-id"] = $datarray["author-id"];
2965 $datarray["guid"] = $guid;
2966 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2968 $datarray["verb"] = ACTIVITY_POST;
2969 $datarray["gravity"] = GRAVITY_PARENT;
2971 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2972 $datarray["source"] = $xml;
2974 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2976 if ($provider_display_name != "") {
2977 $datarray["app"] = $provider_display_name;
2980 $datarray["plink"] = self::plink($author, $guid);
2981 $datarray["private"] = (($public == "false") ? 1 : 0);
2982 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2984 if (isset($address["address"])) {
2985 $datarray["location"] = $address["address"];
2988 if (isset($address["lat"]) && isset($address["lng"])) {
2989 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2992 self::fetchGuid($datarray);
2993 $message_id = Item::insert($datarray);
2995 self::sendParticipation($contact, $datarray);
2998 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2999 if ($datarray['uid'] == 0) {
3000 Item::distribute($message_id);
3008 /* ************************************************************************************** *
3009 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3010 * ************************************************************************************** */
3013 * @brief returnes the handle of a contact
3015 * @param array $contact contact array
3017 * @return string the handle in the format user@domain.tld
3018 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3020 private static function myHandle(array $contact)
3022 if (!empty($contact["addr"])) {
3023 return $contact["addr"];
3026 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3027 // So - just in case - we build the the address here.
3028 if ($contact["nickname"] != "") {
3029 $nick = $contact["nickname"];
3031 $nick = $contact["nick"];
3034 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3039 * @brief Creates the data for a private message in the new format
3041 * @param string $msg The message that is to be transmitted
3042 * @param array $user The record of the sender
3043 * @param array $contact Target of the communication
3044 * @param string $prvkey The private key of the sender
3045 * @param string $pubkey The public key of the receiver
3047 * @return string The encrypted data
3048 * @throws \Exception
3050 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3052 Logger::log("Message: ".$msg, Logger::DATA);
3054 // without a public key nothing will work
3056 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3060 $aes_key = openssl_random_pseudo_bytes(32);
3061 $b_aes_key = base64_encode($aes_key);
3062 $iv = openssl_random_pseudo_bytes(16);
3063 $b_iv = base64_encode($iv);
3065 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3067 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3069 $encrypted_key_bundle = "";
3070 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3072 $json_object = json_encode(
3073 ["aes_key" => base64_encode($encrypted_key_bundle),
3074 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3077 return $json_object;
3081 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3083 * @param string $msg The message that is to be transmitted
3084 * @param array $user The record of the sender
3086 * @return string The envelope
3087 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3089 public static function buildMagicEnvelope($msg, array $user)
3091 $b64url_data = Strings::base64UrlEncode($msg);
3092 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3094 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3095 $type = "application/xml";
3096 $encoding = "base64url";
3097 $alg = "RSA-SHA256";
3098 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3100 // Fallback if the private key wasn't transmitted in the expected field
3101 if ($user['uprvkey'] == "") {
3102 $user['uprvkey'] = $user['prvkey'];
3105 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3106 $sig = Strings::base64UrlEncode($signature);
3108 $xmldata = ["me:env" => ["me:data" => $data,
3109 "@attributes" => ["type" => $type],
3110 "me:encoding" => $encoding,
3113 "@attributes2" => ["key_id" => $key_id]]];
3115 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3117 return XML::fromArray($xmldata, $xml, false, $namespaces);
3121 * @brief Create the envelope for a message
3123 * @param string $msg The message that is to be transmitted
3124 * @param array $user The record of the sender
3125 * @param array $contact Target of the communication
3126 * @param string $prvkey The private key of the sender
3127 * @param string $pubkey The public key of the receiver
3128 * @param bool $public Is the message public?
3130 * @return string The message that will be transmitted to other servers
3131 * @throws \Exception
3133 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3135 // The message is put into an envelope with the sender's signature
3136 $envelope = self::buildMagicEnvelope($msg, $user);
3138 // Private messages are put into a second envelope, encrypted with the receivers public key
3140 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3147 * @brief Creates a signature for a message
3149 * @param array $owner the array of the owner of the message
3150 * @param array $message The message that is to be signed
3152 * @return string The signature
3154 private static function signature($owner, $message)
3157 unset($sigmsg["author_signature"]);
3158 unset($sigmsg["parent_author_signature"]);
3160 $signed_text = implode(";", $sigmsg);
3162 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3166 * @brief Transmit a message to a target server
3168 * @param array $owner the array of the item owner
3169 * @param array $contact Target of the communication
3170 * @param string $envelope The message that is to be transmitted
3171 * @param bool $public_batch Is it a public post?
3172 * @param string $guid message guid
3173 * @param bool $no_defer Don't defer a failing delivery
3175 * @return int Result of the transmission
3176 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3177 * @throws \ImagickException
3179 public static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "", $no_defer = false)
3181 $enabled = intval(Config::get("system", "diaspora_enabled"));
3186 $logid = Strings::getRandomHex(4);
3188 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3190 // We always try to use the data from the fcontact table.
3191 // This is important for transmitting data to Friendica servers.
3192 if (!empty($contact['addr'])) {
3193 $fcontact = self::personByHandle($contact['addr']);
3194 if (!empty($fcontact)) {
3195 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3200 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3204 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3206 if (!intval(Config::get("system", "diaspora_test"))) {
3207 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3209 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3210 $return_code = $postResult->getReturnCode();
3212 Logger::log("test_mode");
3216 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3218 if (!$return_code || (($return_code == 503) && (stristr($postResult->getHeader(), "retry-after")))) {
3219 if (!$no_defer && !empty($contact['contact-type']) && ($contact['contact-type'] != Contact::TYPE_RELAY)) {
3220 Logger::info('defer message', ['log' => $logid, 'guid' => $guid, 'destination' => $dest_url]);
3221 // defer message for redelivery
3225 // The message could not be delivered. We mark the contact as "dead"
3226 Contact::markForArchival($contact);
3227 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3228 // We successfully delivered a message, the contact is alive
3229 Contact::unmarkForArchival($contact);
3232 return $return_code ? $return_code : -1;
3237 * @brief Build the post xml
3239 * @param string $type The message type
3240 * @param array $message The message data
3242 * @return string The post XML
3244 public static function buildPostXml($type, $message)
3246 $data = [$type => $message];
3248 return XML::fromArray($data, $xml);
3252 * @brief Builds and transmit messages
3254 * @param array $owner the array of the item owner
3255 * @param array $contact Target of the communication
3256 * @param string $type The message type
3257 * @param array $message The message data
3258 * @param bool $public_batch Is it a public post?
3259 * @param string $guid message guid
3260 * @param bool $no_defer Don't defer a failing delivery
3262 * @return int Result of the transmission
3263 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3264 * @throws \ImagickException
3266 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $no_defer = false)
3268 $msg = self::buildPostXml($type, $message);
3270 Logger::log('message: '.$msg, Logger::DATA);
3271 Logger::log('send guid '.$guid, Logger::DEBUG);
3273 // Fallback if the private key wasn't transmitted in the expected field
3274 if (empty($owner['uprvkey'])) {
3275 $owner['uprvkey'] = $owner['prvkey'];
3278 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3280 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid, $no_defer);
3282 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3284 return $return_code;
3288 * @brief sends a participation (Used to get all further updates)
3290 * @param array $contact Target of the communication
3291 * @param array $item Item array
3293 * @return int The result of the transmission
3294 * @throws \Exception
3296 private static function sendParticipation(array $contact, array $item)
3298 // Don't send notifications for private postings
3299 if ($item['private']) {
3303 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3305 $result = Cache::get($cachekey);
3306 if (!is_null($result)) {
3310 // Fetch some user id to have a valid handle to transmit the participation.
3311 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3312 // If the item belongs to a user, we take this user id.
3313 if ($item['uid'] == 0) {
3314 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3315 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3316 $owner = User::getOwnerDataById($first_user['uid']);
3318 $owner = User::getOwnerDataById($item['uid']);
3321 $author = self::myHandle($owner);
3323 $message = ["author" => $author,
3324 "guid" => System::createUUID(),
3325 "parent_type" => "Post",
3326 "parent_guid" => $item["guid"]];
3328 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3330 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3331 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3333 return self::buildAndTransmit($owner, $contact, "participation", $message);
3337 * @brief sends an account migration
3339 * @param array $owner the array of the item owner
3340 * @param array $contact Target of the communication
3341 * @param int $uid User ID
3343 * @return int The result of the transmission
3344 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3345 * @throws \ImagickException
3347 public static function sendAccountMigration(array $owner, array $contact, $uid)
3349 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3350 $profile = self::createProfileData($uid);
3352 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3353 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3355 $message = ["author" => $old_handle,
3356 "profile" => $profile,
3357 "signature" => $signature];
3359 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3361 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3365 * @brief Sends a "share" message
3367 * @param array $owner the array of the item owner
3368 * @param array $contact Target of the communication
3370 * @return int The result of the transmission
3371 * @throws \Exception
3373 public static function sendShare(array $owner, array $contact)
3376 * @todo support the different possible combinations of "following" and "sharing"
3377 * Currently, Diaspora only interprets the "sharing" field
3379 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3383 switch ($contact["rel"]) {
3384 case Contact::FRIEND:
3388 case Contact::SHARING:
3392 case Contact::FOLLOWER:
3398 $message = ["author" => self::myHandle($owner),
3399 "recipient" => $contact["addr"],
3400 "following" => "true",
3401 "sharing" => "true"];
3403 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3405 return self::buildAndTransmit($owner, $contact, "contact", $message);
3409 * @brief sends an "unshare"
3411 * @param array $owner the array of the item owner
3412 * @param array $contact Target of the communication
3414 * @return int The result of the transmission
3415 * @throws \Exception
3417 public static function sendUnshare(array $owner, array $contact)
3419 $message = ["author" => self::myHandle($owner),
3420 "recipient" => $contact["addr"],
3421 "following" => "false",
3422 "sharing" => "false"];
3424 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3426 return self::buildAndTransmit($owner, $contact, "contact", $message);
3430 * @brief Checks a message body if it is a reshare
3432 * @param string $body The message body that is to be check
3433 * @param bool $complete Should it be a complete check or a simple check?
3435 * @return array|bool Reshare details or "false" if no reshare
3436 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3437 * @throws \ImagickException
3439 public static function isReshare($body, $complete = true)
3441 $body = trim($body);
3443 // Skip if it isn't a pure repeated messages
3444 // Does it start with a share?
3445 if ((strpos($body, "[share") > 0) && $complete) {
3449 // Does it end with a share?
3450 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3454 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3455 // Skip if there is no shared message in there
3456 if ($body == $attributes) {
3460 // If we don't do the complete check we quit here
3463 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3464 if (!empty($matches[1])) {
3465 $guid = $matches[1];
3468 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3469 if (!empty($matches[1])) {
3470 $guid = $matches[1];
3473 if (($guid != "") && $complete) {
3474 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3475 $item = Item::selectFirst(['contact-id'], $condition);
3476 if (DBA::isResult($item)) {
3478 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3479 $ret["root_guid"] = $guid;
3481 } elseif ($complete) {
3482 // We are resharing something that isn't a DFRN or Diaspora post.
3483 // So we have to return "false" on "$complete" to not trigger a reshare.
3486 } elseif (($guid == "") && $complete) {
3490 $ret["root_guid"] = $guid;
3493 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3494 if (!empty($matches[1])) {
3495 $profile = $matches[1];
3498 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3499 if (!empty($matches[1])) {
3500 $profile = $matches[1];
3505 if ($profile != "") {
3506 if (Contact::getIdForURL($profile)) {
3507 $author = Contact::getDetailsByURL($profile);
3508 $ret["root_handle"] = $author['addr'];
3512 if (empty($ret) && !$complete) {
3520 * @brief Create an event array
3522 * @param integer $event_id The id of the event
3524 * @return array with event data
3525 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3527 private static function buildEvent($event_id)
3529 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3530 if (!DBA::isResult($r)) {
3538 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3539 if (!DBA::isResult($r)) {
3545 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3546 if (!DBA::isResult($r)) {
3552 $eventdata['author'] = self::myHandle($owner);
3554 if ($event['guid']) {
3555 $eventdata['guid'] = $event['guid'];
3558 $mask = DateTimeFormat::ATOM;
3560 /// @todo - establish "all day" events in Friendica
3561 $eventdata["all_day"] = "false";
3563 $eventdata['timezone'] = 'UTC';
3564 if (!$event['adjust'] && $user['timezone']) {
3565 $eventdata['timezone'] = $user['timezone'];
3568 if ($event['start']) {
3569 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3571 if ($event['finish'] && !$event['nofinish']) {
3572 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3574 if ($event['summary']) {
3575 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3577 if ($event['desc']) {
3578 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3580 if ($event['location']) {
3581 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3582 $coord = Map::getCoordinates($event['location']);
3585 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3586 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3587 $location["lat"] = $coord['lat'];
3588 $location["lng"] = $coord['lon'];
3590 $location["lat"] = 0;
3591 $location["lng"] = 0;
3593 $eventdata['location'] = $location;
3600 * @brief Create a post (status message or reshare)
3602 * @param array $item The item that will be exported
3603 * @param array $owner the array of the item owner
3606 * 'type' -> Message type ("status_message" or "reshare")
3607 * 'message' -> Array of XML elements of the status
3608 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3609 * @throws \ImagickException
3611 public static function buildStatus(array $item, array $owner)
3613 $cachekey = "diaspora:buildStatus:".$item['guid'];
3615 $result = Cache::get($cachekey);
3616 if (!is_null($result)) {
3620 $myaddr = self::myHandle($owner);
3622 $public = ($item["private"] ? "false" : "true");
3624 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3626 // Detect a share element and do a reshare
3627 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3628 $message = ["author" => $myaddr,
3629 "guid" => $item["guid"],
3630 "created_at" => $created,
3631 "root_author" => $ret["root_handle"],
3632 "root_guid" => $ret["root_guid"],
3633 "provider_display_name" => $item["app"],
3634 "public" => $public];
3638 $title = $item["title"];
3639 $body = $item["body"];
3641 if ($item['author-link'] != $item['owner-link']) {
3642 require_once 'mod/share.php';
3643 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3644 "", $item['created'], $item['plink']) . $body . '[/share]';
3647 // convert to markdown
3648 $body = html_entity_decode(BBCode::toMarkdown($body));
3651 if (strlen($title)) {
3652 $body = "## ".html_entity_decode($title)."\n\n".$body;
3655 if ($item["attach"]) {
3656 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3658 $body .= "\n".L10n::t("Attachments:")."\n";
3659 foreach ($matches as $mtch) {
3660 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3667 if ($item["location"] != "")
3668 $location["address"] = $item["location"];
3670 if ($item["coord"] != "") {
3671 $coord = explode(" ", $item["coord"]);
3672 $location["lat"] = $coord[0];
3673 $location["lng"] = $coord[1];
3676 $message = ["author" => $myaddr,
3677 "guid" => $item["guid"],
3678 "created_at" => $created,
3679 "public" => $public,
3681 "provider_display_name" => $item["app"],
3682 "location" => $location];
3684 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3685 if (!isset($location["lat"]) || !isset($location["lng"])) {
3686 unset($message["location"]);
3689 if ($item['event-id'] > 0) {
3690 $event = self::buildEvent($item['event-id']);
3691 if (count($event)) {
3692 $message['event'] = $event;
3694 if (!empty($event['location']['address']) &&
3695 !empty($event['location']['lat']) &&
3696 !empty($event['location']['lng'])) {
3697 $message['location'] = $event['location'];
3700 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3701 // $message['text'] = '';
3705 $type = "status_message";
3708 $msg = ["type" => $type, "message" => $message];
3710 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3715 private static function prependParentAuthorMention($body, $profile_url)
3717 $profile = Contact::getDetailsByURL($profile_url);
3718 if (!empty($profile['addr'])
3719 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3720 && !strstr($body, $profile['addr'])
3721 && !strstr($body, $profile_url)
3723 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3730 * @brief Sends a post
3732 * @param array $item The item that will be exported
3733 * @param array $owner the array of the item owner
3734 * @param array $contact Target of the communication
3735 * @param bool $public_batch Is it a public post?
3737 * @return int The result of the transmission
3738 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3739 * @throws \ImagickException
3741 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3743 $status = self::buildStatus($item, $owner);
3745 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3749 * @brief Creates a "like" object
3751 * @param array $item The item that will be exported
3752 * @param array $owner the array of the item owner
3754 * @return array The data for a "like"
3755 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3757 private static function constructLike(array $item, array $owner)
3759 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3760 if (!DBA::isResult($parent)) {
3764 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3766 if ($item['verb'] === ACTIVITY_LIKE) {
3768 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3769 $positive = "false";
3772 return(["author" => self::myHandle($owner),
3773 "guid" => $item["guid"],
3774 "parent_guid" => $parent["guid"],
3775 "parent_type" => $target_type,
3776 "positive" => $positive,
3777 "author_signature" => ""]);
3781 * @brief Creates an "EventParticipation" object
3783 * @param array $item The item that will be exported
3784 * @param array $owner the array of the item owner
3786 * @return array The data for an "EventParticipation"
3787 * @throws \Exception
3789 private static function constructAttend(array $item, array $owner)
3791 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3792 if (!DBA::isResult($parent)) {
3796 switch ($item['verb']) {
3797 case ACTIVITY_ATTEND:
3798 $attend_answer = 'accepted';
3800 case ACTIVITY_ATTENDNO:
3801 $attend_answer = 'declined';
3803 case ACTIVITY_ATTENDMAYBE:
3804 $attend_answer = 'tentative';
3807 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3811 return(["author" => self::myHandle($owner),
3812 "guid" => $item["guid"],
3813 "parent_guid" => $parent["guid"],
3814 "status" => $attend_answer,
3815 "author_signature" => ""]);
3819 * @brief Creates the object for a comment
3821 * @param array $item The item that will be exported
3822 * @param array $owner the array of the item owner
3824 * @return array|false The data for a comment
3825 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3827 private static function constructComment(array $item, array $owner)
3829 $cachekey = "diaspora:constructComment:".$item['guid'];
3831 $result = Cache::get($cachekey);
3832 if (!is_null($result)) {
3836 $toplevel_item = Item::selectFirst(['guid', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3837 if (!DBA::isResult($toplevel_item)) {
3838 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3842 $thread_parent_item = $toplevel_item;
3843 if ($item['thr-parent'] != $item['parent-uri']) {
3844 $thread_parent_item = Item::selectFirst(['guid', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3847 $body = $item["body"];
3849 if ((empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3850 && !Config::get('system', 'disable_implicit_mentions')
3852 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3855 $text = html_entity_decode(BBCode::toMarkdown($body));
3856 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3859 "author" => self::myHandle($owner),
3860 "guid" => $item["guid"],
3861 "created_at" => $created,
3862 "parent_guid" => $toplevel_item["guid"],
3864 "author_signature" => ""
3867 // Send the thread parent guid only if it is a threaded comment
3868 if ($item['thr-parent'] != $item['parent-uri']) {
3869 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3872 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3878 * @brief Send a like or a comment
3880 * @param array $item The item that will be exported
3881 * @param array $owner the array of the item owner
3882 * @param array $contact Target of the communication
3883 * @param bool $public_batch Is it a public post?
3885 * @return int The result of the transmission
3886 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3887 * @throws \ImagickException
3889 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3891 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3892 $message = self::constructAttend($item, $owner);
3893 $type = "event_participation";
3894 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3895 $message = self::constructLike($item, $owner);
3897 } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW])) {
3898 $message = self::constructComment($item, $owner);
3902 if (empty($message)) {
3906 $message["author_signature"] = self::signature($owner, $message);
3908 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3912 * @brief Creates a message from a signature record entry
3914 * @param array $item The item that will be exported
3915 * @return array The message
3917 private static function messageFromSignature(array $item)
3919 // Split the signed text
3920 $signed_parts = explode(";", $item['signed_text']);
3922 if ($item["deleted"]) {
3923 $message = ["author" => $item['signer'],
3924 "target_guid" => $signed_parts[0],
3925 "target_type" => $signed_parts[1]];
3926 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3927 $message = ["author" => $signed_parts[4],
3928 "guid" => $signed_parts[1],
3929 "parent_guid" => $signed_parts[3],
3930 "parent_type" => $signed_parts[2],
3931 "positive" => $signed_parts[0],
3932 "author_signature" => $item['signature'],
3933 "parent_author_signature" => ""];
3935 // Remove the comment guid
3936 $guid = array_shift($signed_parts);
3938 // Remove the parent guid
3939 $parent_guid = array_shift($signed_parts);
3941 // Remove the handle
3942 $handle = array_pop($signed_parts);
3945 "author" => $handle,
3947 "parent_guid" => $parent_guid,
3948 "text" => implode(";", $signed_parts),
3949 "author_signature" => $item['signature'],
3950 "parent_author_signature" => ""
3957 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3959 * @param array $item The item that will be exported
3960 * @param array $owner the array of the item owner
3961 * @param array $contact Target of the communication
3962 * @param bool $public_batch Is it a public post?
3964 * @return int The result of the transmission
3965 * @throws \Exception
3967 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3969 if ($item["deleted"]) {
3970 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3971 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3977 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3979 // Old way - is used by the internal Friendica functions
3980 /// @todo Change all signatur storing functions to the new format
3981 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
3982 $message = self::messageFromSignature($item);
3984 $msg = json_decode($item['signed_text'], true);
3987 if (is_array($msg)) {
3988 foreach ($msg as $field => $data) {
3989 if (!$item["deleted"]) {
3990 if ($field == "diaspora_handle") {
3993 if ($field == "target_type") {
3994 $field = "parent_type";
3998 $message[$field] = $data;
4001 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4005 $message["parent_author_signature"] = self::signature($owner, $message);
4007 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4009 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4013 * @brief Sends a retraction (deletion) of a message, like or comment
4015 * @param array $item The item that will be exported
4016 * @param array $owner the array of the item owner
4017 * @param array $contact Target of the communication
4018 * @param bool $public_batch Is it a public post?
4019 * @param bool $relay Is the retraction transmitted from a relay?
4021 * @return int The result of the transmission
4022 * @throws \Exception
4024 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4026 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4028 $msg_type = "retraction";
4030 if ($item['id'] == $item['parent']) {
4031 $target_type = "Post";
4032 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4033 $target_type = "Like";
4035 $target_type = "Comment";
4038 $message = ["author" => $itemaddr,
4039 "target_guid" => $item['guid'],
4040 "target_type" => $target_type];
4042 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4044 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4048 * @brief Sends a mail
4050 * @param array $item The item that will be exported
4051 * @param array $owner The owner
4052 * @param array $contact Target of the communication
4054 * @return int The result of the transmission
4055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4056 * @throws \ImagickException
4058 public static function sendMail(array $item, array $owner, array $contact)
4060 $myaddr = self::myHandle($owner);
4062 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4063 if (!DBA::isResult($cnv)) {
4064 Logger::log("conversation not found.");
4068 $body = BBCode::toMarkdown($item["body"]);
4069 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4072 "author" => $myaddr,
4073 "guid" => $item["guid"],
4074 "conversation_guid" => $cnv["guid"],
4076 "created_at" => $created,
4079 if ($item["reply"]) {
4084 "author" => $cnv["creator"],
4085 "guid" => $cnv["guid"],
4086 "subject" => $cnv["subject"],
4087 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4088 "participants" => $cnv["recips"],
4092 $type = "conversation";
4095 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4099 * @brief Split a name into first name and last name
4101 * @param string $name The name
4103 * @return array The array with "first" and "last"
4105 public static function splitName($name) {
4106 $name = trim($name);
4108 // Is the name longer than 64 characters? Then cut the rest of it.
4109 if (strlen($name) > 64) {
4110 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4111 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4113 $name = substr($name, 0, 64);
4117 // Take the first word as first name
4118 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4119 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4120 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4121 return ['first' => $first, 'last' => $last];
4124 // Take the last word as last name
4125 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4126 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4128 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4129 return ['first' => $first, 'last' => $last];
4132 // Take the first 32 characters if there is no space in the first 32 characters
4133 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4134 $first = substr($name, 0, 32);
4135 $last = substr($name, 32);
4136 return ['first' => $first, 'last' => $last];
4139 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4140 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4142 // Check if the last name is longer than 32 characters
4143 if (strlen($last) > 32) {
4144 if (strpos($last, ' ') <= 32) {
4145 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4147 $last = substr($last, 0, 32);
4151 return ['first' => $first, 'last' => $last];
4155 * @brief Create profile data
4157 * @param int $uid The user id
4159 * @return array The profile data
4160 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4162 private static function createProfileData($uid)
4165 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4167 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4168 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4169 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4178 $handle = $profile["addr"];
4180 $split_name = self::splitName($profile['name']);
4181 $first = $split_name['first'];
4182 $last = $split_name['last'];
4184 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4185 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4186 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4187 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4193 if ($searchable === 'true') {
4196 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4197 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4201 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4204 $about = $profile['about'];
4205 $about = strip_tags(BBCode::convert($about));
4207 $location = Profile::formatLocation($profile);
4209 if ($profile['pub_keywords']) {
4210 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4211 $kw = str_replace(' ', ' ', $kw);
4212 $arr = explode(' ', $kw);
4214 for ($x = 0; $x < 5; $x ++) {
4215 if (!empty($arr[$x])) {
4216 $tags .= '#'. trim($arr[$x]) .' ';
4221 $tags = trim($tags);
4224 return ["author" => $handle,
4225 "first_name" => $first,
4226 "last_name" => $last,
4227 "image_url" => $large,
4228 "image_url_medium" => $medium,
4229 "image_url_small" => $small,
4231 "gender" => $profile['gender'],
4233 "location" => $location,
4234 "searchable" => $searchable,
4236 "tag_string" => $tags];
4240 * @brief Sends profile data
4242 * @param int $uid The user id
4243 * @param bool $recips optional, default false
4245 * @throws \Exception
4247 public static function sendProfile($uid, $recips = false)
4253 $owner = User::getOwnerDataById($uid);
4260 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4261 AND `uid` = %d AND `rel` != %d",
4262 DBA::escape(Protocol::DIASPORA),
4264 intval(Contact::SHARING)
4272 $message = self::createProfileData($uid);
4274 foreach ($recips as $recip) {
4275 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4276 self::buildAndTransmit($owner, $recip, "profile", $message, false, '', true);
4281 * @brief Creates the signature for likes that are created on our system
4283 * @param integer $uid The user of that comment
4284 * @param array $item Item array
4286 * @return array Signed content
4287 * @throws \Exception
4289 public static function createLikeSignature($uid, array $item)
4291 $owner = User::getOwnerDataById($uid);
4292 if (empty($owner)) {
4293 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4297 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4301 $message = self::constructLike($item, $owner);
4302 if ($message === false) {
4306 $message["author_signature"] = self::signature($owner, $message);
4312 * @brief Creates the signature for Comments that are created on our system
4314 * @param integer $uid The user of that comment
4315 * @param array $item Item array
4317 * @return array Signed content
4318 * @throws \Exception
4320 public static function createCommentSignature($uid, array $item)
4322 $owner = User::getOwnerDataById($uid);
4323 if (empty($owner)) {
4324 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4328 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4329 $item['thr-parent'] = $item['parent-uri'];
4331 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4332 if (!DBA::isResult($parent)) {
4336 $item['parent-uri'] = $parent['parent-uri'];
4338 $message = self::constructComment($item, $owner);
4339 if ($message === false) {
4343 $message["author_signature"] = self::signature($owner, $message);