3 * @file src/Protocol/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "validPosting" and interpret only the new protocol.
11 namespace Friendica\Protocol;
13 use Friendica\Content\Feature;
14 use Friendica\Content\Text\BBCode;
15 use Friendica\Content\Text\Markdown;
16 use Friendica\Core\Cache;
17 use Friendica\Core\Config;
18 use Friendica\Core\L10n;
19 use Friendica\Core\Logger;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Conversation;
27 use Friendica\Model\GContact;
28 use Friendica\Model\Group;
29 use Friendica\Model\Item;
30 use Friendica\Model\Mail;
31 use Friendica\Model\Profile;
32 use Friendica\Model\User;
33 use Friendica\Network\Probe;
34 use Friendica\Util\Crypto;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Map;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
39 use Friendica\Util\XML;
40 use Friendica\Worker\Delivery;
44 * @brief This class contain functions to create and send Diaspora XML files
50 * @brief Return a list of relay servers
52 * The list contains not only the official relays but also servers that we serve directly
54 * @param integer $item_id The id of the item that is sent
55 * @param array $contacts The previously fetched contacts
57 * @return array of relay servers
58 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
60 public static function relayList($item_id, array $contacts = [])
64 // Fetching relay servers
65 $serverdata = Config::get("system", "relay_server");
67 if (!empty($serverdata)) {
68 $servers = explode(",", $serverdata);
69 foreach ($servers as $server) {
70 $serverlist[$server] = trim($server);
74 if (Config::get("system", "relay_directly", false)) {
75 // We distribute our stuff based on the parent to ensure that the thread will be complete
76 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
77 if (!DBA::isResult($parent)) {
81 // Servers that want to get all content
82 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
83 while ($server = DBA::fetch($servers)) {
84 $serverlist[$server['url']] = $server['url'];
87 // All tags of the current post
88 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
89 $tags = DBA::select('term', ['term'], $condition);
91 while ($tag = DBA::fetch($tags)) {
92 $taglist[] = $tag['term'];
95 // All servers who wants content with this tag
97 if (!empty($taglist)) {
98 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
99 while ($server = DBA::fetch($tagserver)) {
100 $tagserverlist[] = $server['gserver-id'];
104 // All adresses with the given id
105 if (!empty($tagserverlist)) {
106 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
107 while ($server = DBA::fetch($servers)) {
108 $serverlist[$server['url']] = $server['url'];
113 // Now we are collecting all relay contacts
114 foreach ($serverlist as $server_url) {
115 // We don't send messages to ourselves
116 if (Strings::compareLink($server_url, System::baseUrl())) {
119 $contact = self::getRelayContact($server_url);
120 if (is_bool($contact)) {
125 foreach ($contacts as $entry) {
126 if ($entry['batch'] == $contact['batch']) {
132 $contacts[] = $contact;
140 * @brief Return a contact for a given server address or creates a dummy entry
142 * @param string $server_url The url of the server
143 * @return array with the contact
146 private static function getRelayContact($server_url)
148 $fields = ['batch', 'id', 'name', 'network', 'protocol', 'archive', 'blocked'];
150 // Fetch the relay contact
151 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
152 'contact-type' => Contact::TYPE_RELAY];
153 $contact = DBA::selectFirst('contact', $fields, $condition);
155 if (DBA::isResult($contact)) {
156 if ($contact['archive'] || $contact['blocked']) {
161 self::setRelayContact($server_url);
163 $contact = DBA::selectFirst('contact', $fields, $condition);
164 if (DBA::isResult($contact)) {
169 // It should never happen that we arrive here
174 * @brief Update or insert a relay contact
176 * @param string $server_url The url of the server
177 * @param array $network_fields Optional network specific fields
180 public static function setRelayContact($server_url, array $network_fields = [])
182 $fields = ['created' => DateTimeFormat::utcNow(),
183 'name' => 'relay', 'nick' => 'relay',
184 'url' => $server_url, 'network' => Protocol::DIASPORA,
185 'batch' => $server_url . '/receive/public',
186 'rel' => Contact::FOLLOWER, 'blocked' => false,
187 'pending' => false, 'writable' => true];
189 $fields = array_merge($fields, $network_fields);
191 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
192 'contact-type' => Contact::TYPE_RELAY];
194 if (DBA::exists('contact', $condition)) {
195 unset($fields['created']);
198 DBA::update('contact', $fields, $condition, true);
202 * @brief Return a list of participating contacts for a thread
204 * This is used for the participation feature.
205 * One of the parameters is a contact array.
206 * This is done to avoid duplicates.
208 * @param integer $thread The id of the thread
209 * @param array $contacts The previously fetched contacts
211 * @return array of relay servers
214 public static function participantsForThread($thread, array $contacts)
216 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`, `contact`.`protocol`,
217 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
218 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
219 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
220 WHERE `participation`.`iid` = ?", $thread);
222 while ($contact = DBA::fetch($r)) {
223 if (!empty($contact['fnetwork'])) {
224 $contact['network'] = $contact['fnetwork'];
226 unset($contact['fnetwork']);
228 if (empty($contact['protocol'])) {
229 $contact['protocol'] = $contact['network'];
232 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
233 $contact['batch'] = $contact['fbatch'];
235 unset($contact['fbatch']);
238 foreach ($contacts as $entry) {
239 if ($entry['batch'] == $contact['batch']) {
245 $contacts[] = $contact;
254 * @brief repairs a signature that was double encoded
256 * The function is unused at the moment. It was copied from the old implementation.
258 * @param string $signature The signature
259 * @param string $handle The handle of the signature owner
260 * @param integer $level This value is only set inside this function to avoid endless loops
262 * @return string the repaired signature
265 private static function repairSignature($signature, $handle = "", $level = 1)
267 if ($signature == "") {
271 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
272 $signature = base64_decode($signature);
273 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
275 // Do a recursive call to be able to fix even multiple levels
277 $signature = self::repairSignature($signature, $handle, ++$level);
285 * @brief verify the envelope and return the verified data
287 * @param string $envelope The magic envelope
289 * @return string verified data
290 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
291 * @throws \ImagickException
293 private static function verifyMagicEnvelope($envelope)
295 $basedom = XML::parseString($envelope);
297 if (!is_object($basedom)) {
298 Logger::log("Envelope is no XML file");
302 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
304 if (sizeof($children) == 0) {
305 Logger::log("XML has no children");
311 $data = Strings::base64UrlDecode($children->data);
312 $type = $children->data->attributes()->type[0];
314 $encoding = $children->encoding;
316 $alg = $children->alg;
318 $sig = Strings::base64UrlDecode($children->sig);
319 $key_id = $children->sig->attributes()->key_id[0];
321 $handle = Strings::base64UrlDecode($key_id);
324 $b64url_data = Strings::base64UrlEncode($data);
325 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
327 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
330 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
334 $key = self::key($handle);
336 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
340 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
342 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
350 * @brief encrypts data via AES
352 * @param string $key The AES key
353 * @param string $iv The IV (is used for CBC encoding)
354 * @param string $data The data that is to be encrypted
356 * @return string encrypted data
358 private static function aesEncrypt($key, $iv, $data)
360 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
364 * @brief decrypts data via AES
366 * @param string $key The AES key
367 * @param string $iv The IV (is used for CBC encoding)
368 * @param string $encrypted The encrypted data
370 * @return string decrypted data
372 private static function aesDecrypt($key, $iv, $encrypted)
374 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
378 * @brief: Decodes incoming Diaspora message in the new format
380 * @param array $importer Array of the importer user
381 * @param string $raw raw post message
382 * @param boolean $no_exit Don't do an http exit on error
385 * 'message' -> decoded Diaspora XML message
386 * 'author' -> author diaspora handle
387 * 'key' -> author public key (converted to pkcs#8)
388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
389 * @throws \ImagickException
391 public static function decodeRaw(array $importer, $raw, $no_exit = false)
393 $data = json_decode($raw);
395 // Is it a private post? Then decrypt the outer Salmon
396 if (is_object($data)) {
397 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
398 $ciphertext = base64_decode($data->encrypted_magic_envelope);
400 $outer_key_bundle = '';
401 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
402 $j_outer_key_bundle = json_decode($outer_key_bundle);
404 if (!is_object($j_outer_key_bundle)) {
405 Logger::log('Outer Salmon did not verify. Discarding.');
409 throw new \Friendica\Network\HTTPException\BadRequestException();
413 $outer_iv = base64_decode($j_outer_key_bundle->iv);
414 $outer_key = base64_decode($j_outer_key_bundle->key);
416 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
421 $basedom = XML::parseString($xml);
423 if (!is_object($basedom)) {
424 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
428 throw new \Friendica\Network\HTTPException\BadRequestException();
432 $base = $basedom->children(NAMESPACE_SALMON_ME);
434 // Not sure if this cleaning is needed
435 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
437 // Build the signed data
438 $type = $base->data[0]->attributes()->type[0];
439 $encoding = $base->encoding;
441 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
443 // This is the signature
444 $signature = Strings::base64UrlDecode($base->sig);
446 // Get the senders' public key
447 $key_id = $base->sig[0]->attributes()->key_id[0];
448 $author_addr = base64_decode($key_id);
449 if ($author_addr == '') {
450 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
454 throw new \Friendica\Network\HTTPException\BadRequestException();
458 $key = self::key($author_addr);
460 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
464 throw new \Friendica\Network\HTTPException\BadRequestException();
468 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
470 Logger::log('Message did not verify. Discarding.');
474 throw new \Friendica\Network\HTTPException\BadRequestException();
478 return ['message' => (string)Strings::base64UrlDecode($base->data),
479 'author' => XML::unescape($author_addr),
480 'key' => (string)$key];
484 * @brief: Decodes incoming Diaspora message in the deprecated format
486 * @param array $importer Array of the importer user
487 * @param string $xml urldecoded Diaspora salmon
490 * 'message' -> decoded Diaspora XML message
491 * 'author' -> author diaspora handle
492 * 'key' -> author public key (converted to pkcs#8)
493 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
494 * @throws \ImagickException
496 public static function decode(array $importer, $xml)
499 $basedom = XML::parseString($xml);
501 if (!is_object($basedom)) {
502 Logger::log("XML is not parseable.");
505 $children = $basedom->children('https://joindiaspora.com/protocol');
507 $inner_aes_key = null;
510 if ($children->header) {
512 $author_link = str_replace('acct:', '', $children->header->author_id);
514 // This happens with posts from a relais
516 Logger::log("This is no private post in the old format", Logger::DEBUG);
520 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
522 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
523 $ciphertext = base64_decode($encrypted_header->ciphertext);
525 $outer_key_bundle = '';
526 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
528 $j_outer_key_bundle = json_decode($outer_key_bundle);
530 $outer_iv = base64_decode($j_outer_key_bundle->iv);
531 $outer_key = base64_decode($j_outer_key_bundle->key);
533 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
535 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
536 $idom = XML::parseString($decrypted);
538 $inner_iv = base64_decode($idom->iv);
539 $inner_aes_key = base64_decode($idom->aes_key);
541 $author_link = str_replace('acct:', '', $idom->author_id);
544 $dom = $basedom->children(NAMESPACE_SALMON_ME);
546 // figure out where in the DOM tree our data is hiding
549 if ($dom->provenance->data) {
550 $base = $dom->provenance;
551 } elseif ($dom->env->data) {
553 } elseif ($dom->data) {
558 Logger::log('unable to locate salmon data in xml');
559 throw new \Friendica\Network\HTTPException\BadRequestException();
563 // Stash the signature away for now. We have to find their key or it won't be good for anything.
564 $signature = Strings::base64UrlDecode($base->sig);
568 // strip whitespace so our data element will return to one big base64 blob
569 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
572 // stash away some other stuff for later
574 $type = $base->data[0]->attributes()->type[0];
575 $keyhash = $base->sig[0]->attributes()->keyhash[0];
576 $encoding = $base->encoding;
580 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
584 $data = Strings::base64UrlDecode($data);
588 $inner_decrypted = $data;
590 // Decode the encrypted blob
591 $inner_encrypted = base64_decode($data);
592 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
596 Logger::log('Could not retrieve author URI.');
597 throw new \Friendica\Network\HTTPException\BadRequestException();
599 // Once we have the author URI, go to the web and try to find their public key
600 // (first this will look it up locally if it is in the fcontact cache)
601 // This will also convert diaspora public key from pkcs#1 to pkcs#8
603 Logger::log('Fetching key for '.$author_link);
604 $key = self::key($author_link);
607 Logger::log('Could not retrieve author key.');
608 throw new \Friendica\Network\HTTPException\BadRequestException();
611 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
614 Logger::log('Message did not verify. Discarding.');
615 throw new \Friendica\Network\HTTPException\BadRequestException();
618 Logger::log('Message verified.');
620 return ['message' => (string)$inner_decrypted,
621 'author' => XML::unescape($author_link),
622 'key' => (string)$key];
627 * @brief Dispatches public messages and find the fitting receivers
629 * @param array $msg The post that will be dispatched
631 * @return int The message id of the generated message, "true" or "false" if there was an error
632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
633 * @throws \ImagickException
635 public static function dispatchPublic($msg)
637 $enabled = intval(Config::get("system", "diaspora_enabled"));
639 Logger::log("diaspora is disabled");
643 if (!($fields = self::validPosting($msg))) {
644 Logger::log("Invalid posting");
648 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
649 $success = self::dispatch($importer, $msg, $fields);
655 * @brief Dispatches the different message types to the different functions
657 * @param array $importer Array of the importer user
658 * @param array $msg The post that will be dispatched
659 * @param SimpleXMLElement $fields SimpleXML object that contains the message
661 * @return int The message id of the generated message, "true" or "false" if there was an error
662 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
663 * @throws \ImagickException
665 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
667 // The sender is the handle of the contact that sent the message.
668 // This will often be different with relayed messages (for example "like" and "comment")
669 $sender = $msg["author"];
671 // This is only needed for private postings since this is already done for public ones before
672 if (is_null($fields)) {
674 if (!($fields = self::validPosting($msg))) {
675 Logger::log("Invalid posting");
682 $type = $fields->getName();
684 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
687 case "account_migration":
689 Logger::log('Message with type ' . $type . ' is not private, quitting.');
692 return self::receiveAccountMigration($importer, $fields);
694 case "account_deletion":
695 return self::receiveAccountDeletion($fields);
698 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
702 Logger::log('Message with type ' . $type . ' is not private, quitting.');
705 return self::receiveContactRequest($importer, $fields);
709 Logger::log('Message with type ' . $type . ' is not private, quitting.');
712 return self::receiveConversation($importer, $msg, $fields);
715 return self::receiveLike($importer, $sender, $fields);
719 Logger::log('Message with type ' . $type . ' is not private, quitting.');
722 return self::receiveMessage($importer, $fields);
724 case "participation":
726 Logger::log('Message with type ' . $type . ' is not private, quitting.');
729 return self::receiveParticipation($importer, $fields);
731 case "photo": // Not implemented
732 return self::receivePhoto($importer, $fields);
734 case "poll_participation": // Not implemented
735 return self::receivePollParticipation($importer, $fields);
739 Logger::log('Message with type ' . $type . ' is not private, quitting.');
742 return self::receiveProfile($importer, $fields);
745 return self::receiveReshare($importer, $fields, $msg["message"]);
748 return self::receiveRetraction($importer, $sender, $fields);
750 case "status_message":
751 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
754 Logger::log("Unknown message type ".$type);
760 * @brief Checks if a posting is valid and fetches the data fields.
762 * This function does not only check the signature.
763 * It also does the conversion between the old and the new diaspora format.
765 * @param array $msg Array with the XML, the sender handle and the sender signature
767 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
768 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
769 * @throws \ImagickException
771 private static function validPosting($msg)
773 $data = XML::parseString($msg["message"]);
775 if (!is_object($data)) {
776 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
780 // Is this the new or the old version?
781 if ($data->getName() == "XML") {
783 foreach ($data->post->children() as $child) {
791 $type = $element->getName();
794 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
796 // All retractions are handled identically from now on.
797 // In the new version there will only be "retraction".
798 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
799 $type = "retraction";
801 if ($type == "request") {
805 $fields = new SimpleXMLElement("<".$type."/>");
808 $author_signature = null;
809 $parent_author_signature = null;
811 foreach ($element->children() as $fieldname => $entry) {
813 // Translation for the old XML structure
814 if ($fieldname == "diaspora_handle") {
815 $fieldname = "author";
817 if ($fieldname == "participant_handles") {
818 $fieldname = "participants";
820 if (in_array($type, ["like", "participation"])) {
821 if ($fieldname == "target_type") {
822 $fieldname = "parent_type";
825 if ($fieldname == "sender_handle") {
826 $fieldname = "author";
828 if ($fieldname == "recipient_handle") {
829 $fieldname = "recipient";
831 if ($fieldname == "root_diaspora_id") {
832 $fieldname = "root_author";
834 if ($type == "status_message") {
835 if ($fieldname == "raw_message") {
839 if ($type == "retraction") {
840 if ($fieldname == "post_guid") {
841 $fieldname = "target_guid";
843 if ($fieldname == "type") {
844 $fieldname = "target_type";
849 if (($fieldname == "author_signature") && ($entry != "")) {
850 $author_signature = base64_decode($entry);
851 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
852 $parent_author_signature = base64_decode($entry);
853 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
854 if ($signed_data != "") {
858 $signed_data .= $entry;
860 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
861 || ($orig_type == "relayable_retraction")
863 XML::copy($entry, $fields, $fieldname);
867 // This is something that shouldn't happen at all.
868 if (in_array($type, ["status_message", "reshare", "profile"])) {
869 if ($msg["author"] != $fields->author) {
870 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
875 // Only some message types have signatures. So we quit here for the other types.
876 if (!in_array($type, ["comment", "like"])) {
879 // No author_signature? This is a must, so we quit.
880 if (!isset($author_signature)) {
881 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
885 if (isset($parent_author_signature)) {
886 $key = self::key($msg["author"]);
888 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
892 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
893 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);
898 $key = self::key($fields->author);
900 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
904 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
905 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);
913 * @brief Fetches the public key for a given handle
915 * @param string $handle The handle
917 * @return string The public key
918 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
919 * @throws \ImagickException
921 private static function key($handle)
923 $handle = strval($handle);
925 Logger::log("Fetching diaspora key for: ".$handle);
927 $r = self::personByHandle($handle);
936 * @brief Fetches data for a given handle
938 * @param string $handle The handle
940 * @return array the queried data
941 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
942 * @throws \ImagickException
944 public static function personByHandle($handle)
948 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
949 if (DBA::isResult($person)) {
950 Logger::debug("In cache " . print_r($person, true));
952 // update record occasionally so it doesn't get stale
953 $d = strtotime($person["updated"]." +00:00");
954 if ($d < strtotime("now - 14 days")) {
958 if ($person["guid"] == "") {
963 if (!DBA::isResult($person) || $update) {
964 Logger::log("create or refresh", Logger::DEBUG);
965 $r = Probe::uri($handle, Protocol::DIASPORA);
967 // Note that Friendica contacts will return a "Diaspora person"
968 // if Diaspora connectivity is enabled on their server
969 if ($r && ($r["network"] === Protocol::DIASPORA)) {
970 self::updateFContact($r);
972 // Fetch the updated or added contact
973 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
974 if (!DBA::isResult($person)) {
985 * @brief Updates the fcontact table
987 * @param array $arr The fcontact data
990 private static function updateFContact($arr)
992 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
993 'request' => $arr["request"], 'nick' => $arr["nick"],
994 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
995 'batch' => $arr["batch"], 'notify' => $arr["notify"],
996 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
997 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
998 'updated' => DateTimeFormat::utcNow()];
1000 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1002 DBA::update('fcontact', $fields, $condition, true);
1006 * @brief get a handle (user@domain.tld) from a given contact id
1008 * @param int $contact_id The id in the contact table
1009 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1011 * @return string the handle
1012 * @throws \Exception
1014 private static function handleFromContact($contact_id, $pcontact_id = 0)
1018 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1020 if ($pcontact_id != 0) {
1021 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1023 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1024 return strtolower($contact["addr"]);
1029 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1033 if (DBA::isResult($r)) {
1036 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1038 if ($contact['addr'] != "") {
1039 $handle = $contact['addr'];
1041 $baseurl_start = strpos($contact['url'], '://') + 3;
1042 // allows installations in a subdirectory--not sure how Diaspora will handle
1043 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1044 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1045 $handle = $contact['nick'].'@'.$baseurl;
1049 return strtolower($handle);
1053 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1056 * @param mixed $fcontact_guid Hexadecimal string guid
1058 * @return string the contact url or null
1059 * @throws \Exception
1061 public static function urlFromContactGuid($fcontact_guid)
1063 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1066 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1067 DBA::escape(Protocol::DIASPORA),
1068 DBA::escape($fcontact_guid)
1071 if (DBA::isResult($r)) {
1072 return $r[0]['url'];
1079 * @brief Get a contact id for a given handle
1081 * @todo Move to Friendica\Model\Contact
1083 * @param int $uid The user id
1084 * @param string $handle The handle in the format user@domain.tld
1086 * @return array Contact data
1087 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1088 * @throws \ImagickException
1090 private static function contactByHandle($uid, $handle)
1092 $cid = Contact::getIdForURL($handle, $uid);
1094 $handle_parts = explode("@", $handle);
1095 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1096 $cid = Contact::getIdForURL($nurl_sql, $uid);
1100 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1104 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1105 if (!DBA::isResult($contact)) {
1106 // This here shouldn't happen at all
1107 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1115 * @brief Check if posting is allowed for this contact
1117 * @param array $importer Array of the importer user
1118 * @param array $contact The contact that is checked
1119 * @param bool $is_comment Is the check for a comment?
1121 * @return bool is the contact allowed to post?
1123 private static function postAllow(array $importer, array $contact, $is_comment = false)
1126 * Perhaps we were already sharing with this person. Now they're sharing with us.
1127 * That makes us friends.
1128 * Normally this should have handled by getting a request - but this could get lost
1130 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1131 // It is not removed by now. Possibly the code is needed?
1132 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1135 // array('rel' => Contact::FRIEND, 'writable' => true),
1136 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1139 // $contact["rel"] = Contact::FRIEND;
1140 // Logger::log("defining user ".$contact["nick"]." as friend");
1143 // Contact server is blocked
1144 if (Network::isUrlBlocked($contact['url'])) {
1146 // We don't seem to like that person
1147 } elseif ($contact["blocked"]) {
1148 // Maybe blocked, don't accept.
1150 // We are following this person?
1151 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1152 // Yes, then it is fine.
1154 // Is it a post to a community?
1155 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1158 // Is the message a global user or a comment?
1159 } elseif (($importer["uid"] == 0) || $is_comment) {
1160 // Messages for the global users and comments are always accepted
1168 * @brief Fetches the contact id for a handle and checks if posting is allowed
1170 * @param array $importer Array of the importer user
1171 * @param string $handle The checked handle in the format user@domain.tld
1172 * @param bool $is_comment Is the check for a comment?
1174 * @return array The contact data
1175 * @throws \Exception
1177 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1179 $contact = self::contactByHandle($importer["uid"], $handle);
1181 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1182 // If a contact isn't found, we accept it anyway if it is a comment
1183 if ($is_comment && ($importer["uid"] != 0)) {
1184 return self::contactByHandle(0, $handle);
1185 } elseif ($is_comment) {
1192 if (!self::postAllow($importer, $contact, $is_comment)) {
1193 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1200 * @brief Does the message already exists on the system?
1202 * @param int $uid The user id
1203 * @param string $guid The guid of the message
1205 * @return int|bool message id if the message already was stored into the system - or false.
1206 * @throws \Exception
1208 private static function messageExists($uid, $guid)
1210 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1211 if (DBA::isResult($item)) {
1212 Logger::log("message ".$guid." already exists for user ".$uid);
1220 * @brief Checks for links to posts in a message
1222 * @param array $item The item array
1225 private static function fetchGuid(array $item)
1227 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1228 preg_replace_callback(
1230 function ($match) use ($item) {
1231 self::fetchGuidSub($match, $item);
1236 preg_replace_callback(
1237 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1238 function ($match) use ($item) {
1239 self::fetchGuidSub($match, $item);
1246 * @brief Checks for relative /people/* links in an item body to match local
1247 * contacts or prepends the remote host taken from the author link.
1249 * @param string $body The item body to replace links from
1250 * @param string $author_link The author link for missing local contact fallback
1252 * @return string the replaced string
1254 public static function replacePeopleGuid($body, $author_link)
1256 $return = preg_replace_callback(
1257 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1258 function ($match) use ($author_link) {
1260 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1261 // 1 => '0123456789abcdef'
1263 $handle = self::urlFromContactGuid($match[1]);
1266 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1268 // No local match, restoring absolute remote URL from author scheme and host
1269 $author_url = parse_url($author_link);
1270 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1282 * @brief sub function of "fetchGuid" which checks for links in messages
1284 * @param array $match array containing a link that has to be checked for a message link
1285 * @param array $item The item array
1287 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1288 * @throws \ImagickException
1290 private static function fetchGuidSub($match, $item)
1292 if (!self::storeByGuid($match[1], $item["author-link"])) {
1293 self::storeByGuid($match[1], $item["owner-link"]);
1298 * @brief Fetches an item with a given guid from a given server
1300 * @param string $guid the message guid
1301 * @param string $server The server address
1302 * @param int $uid The user id of the user
1304 * @return int the message id of the stored message or false
1305 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1306 * @throws \ImagickException
1308 private static function storeByGuid($guid, $server, $uid = 0)
1310 $serverparts = parse_url($server);
1312 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1316 $server = $serverparts["scheme"]."://".$serverparts["host"];
1318 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1320 $msg = self::message($guid, $server);
1326 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1328 // Now call the dispatcher
1329 return self::dispatchPublic($msg);
1333 * @brief Fetches a message from a server
1335 * @param string $guid message guid
1336 * @param string $server The url of the server
1337 * @param int $level Endless loop prevention
1340 * 'message' => The message XML
1341 * 'author' => The author handle
1342 * 'key' => The public key of the author
1343 * @throws \Exception
1345 private static function message($guid, $server, $level = 0)
1351 // This will work for new Diaspora servers and Friendica servers from 3.5
1352 $source_url = $server."/fetch/post/".urlencode($guid);
1354 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1356 $envelope = Network::fetchUrl($source_url);
1358 Logger::log("Envelope was fetched.", Logger::DEBUG);
1359 $x = self::verifyMagicEnvelope($envelope);
1361 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1363 Logger::log("Envelope was verified.", Logger::DEBUG);
1373 $source_xml = XML::parseString($x);
1375 if (!is_object($source_xml)) {
1379 if ($source_xml->post->reshare) {
1380 // Reshare of a reshare - old Diaspora version
1381 Logger::log("Message is a reshare", Logger::DEBUG);
1382 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1383 } elseif ($source_xml->getName() == "reshare") {
1384 // Reshare of a reshare - new Diaspora version
1385 Logger::log("Message is a new reshare", Logger::DEBUG);
1386 return self::message($source_xml->root_guid, $server, ++$level);
1391 // Fetch the author - for the old and the new Diaspora version
1392 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1393 $author = (string)$source_xml->post->status_message->diaspora_handle;
1394 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1395 $author = (string)$source_xml->author;
1398 // If this isn't a "status_message" then quit
1400 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1404 $msg = ["message" => $x, "author" => $author];
1406 $msg["key"] = self::key($msg["author"]);
1412 * @brief Fetches the item record of a given guid
1414 * @param int $uid The user id
1415 * @param string $guid message guid
1416 * @param string $author The handle of the item
1417 * @param array $contact The contact of the item owner
1419 * @return array the item record
1420 * @throws \Exception
1422 private static function parentItem($uid, $guid, $author, array $contact)
1424 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1425 'author-name', 'author-link', 'author-avatar',
1426 'owner-name', 'owner-link', 'owner-avatar'];
1427 $condition = ['uid' => $uid, 'guid' => $guid];
1428 $item = Item::selectFirst($fields, $condition);
1430 if (!DBA::isResult($item)) {
1431 $person = self::personByHandle($author);
1432 $result = self::storeByGuid($guid, $person["url"], $uid);
1434 // We don't have an url for items that arrived at the public dispatcher
1435 if (!$result && !empty($contact["url"])) {
1436 $result = self::storeByGuid($guid, $contact["url"], $uid);
1440 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1442 $item = Item::selectFirst($fields, $condition);
1446 if (!DBA::isResult($item)) {
1447 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1450 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1456 * @brief returns contact details
1458 * @param array $def_contact The default contact if the person isn't found
1459 * @param array $person The record of the person
1460 * @param int $uid The user id
1463 * 'cid' => contact id
1464 * 'network' => network type
1465 * @throws \Exception
1467 private static function authorContactByUrl($def_contact, $person, $uid)
1469 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1470 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1471 if (DBA::isResult($contact)) {
1472 $cid = $contact["id"];
1473 $network = $contact["network"];
1475 $cid = $def_contact["id"];
1476 $network = Protocol::DIASPORA;
1479 return ["cid" => $cid, "network" => $network];
1483 * @brief Is the profile a hubzilla profile?
1485 * @param string $url The profile link
1487 * @return bool is it a hubzilla server?
1489 public static function isRedmatrix($url)
1491 return(strstr($url, "/channel/"));
1495 * @brief Generate a post link with a given handle and message guid
1497 * @param string $addr The user handle
1498 * @param string $guid message guid
1499 * @param string $parent_guid optional parent guid
1501 * @return string the post link
1502 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1503 * @throws \ImagickException
1505 private static function plink($addr, $guid, $parent_guid = '')
1507 $contact = Contact::getDetailsByAddr($addr);
1511 if ($parent_guid != '') {
1512 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1514 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1518 if ($contact["network"] == Protocol::DFRN) {
1519 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1522 if (self::isRedmatrix($contact["url"])) {
1523 return $contact["url"] . "/?f=&mid=" . $guid;
1526 if ($parent_guid != '') {
1527 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1529 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1534 * @brief Receives account migration
1536 * @param array $importer Array of the importer user
1537 * @param object $data The message object
1539 * @return bool Success
1540 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1541 * @throws \ImagickException
1543 private static function receiveAccountMigration(array $importer, $data)
1545 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1546 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1547 $signature = Strings::escapeTags(XML::unescape($data->signature));
1549 $contact = self::contactByHandle($importer["uid"], $old_handle);
1551 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1555 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1558 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1559 $key = self::key($old_handle);
1560 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1561 Logger::log('No valid signature for migration.');
1565 // Update the profile
1566 self::receiveProfile($importer, $data->profile);
1568 // change the technical stuff in contact and gcontact
1569 $data = Probe::uri($new_handle);
1570 if ($data['network'] == Protocol::PHANTOM) {
1571 Logger::log('Account for '.$new_handle." couldn't be probed.");
1575 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1576 'name' => $data['name'], 'nick' => $data['nick'],
1577 'addr' => $data['addr'], 'batch' => $data['batch'],
1578 'notify' => $data['notify'], 'poll' => $data['poll'],
1579 'network' => $data['network']];
1581 DBA::update('contact', $fields, ['addr' => $old_handle]);
1583 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1584 'name' => $data['name'], 'nick' => $data['nick'],
1585 'addr' => $data['addr'], 'connect' => $data['addr'],
1586 'notify' => $data['notify'], 'photo' => $data['photo'],
1587 'server_url' => $data['baseurl'], 'network' => $data['network']];
1589 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1591 Logger::log('Contacts are updated.');
1597 * @brief Processes an account deletion
1599 * @param object $data The message object
1601 * @return bool Success
1602 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1604 private static function receiveAccountDeletion($data)
1606 $author = Strings::escapeTags(XML::unescape($data->author));
1608 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1609 while ($contact = DBA::fetch($contacts)) {
1610 Contact::remove($contact["id"]);
1613 DBA::delete('gcontact', ['addr' => $author]);
1615 Logger::log('Removed contacts for ' . $author);
1621 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1623 * @param string $author Author handle
1624 * @param string $guid Message guid
1625 * @param boolean $onlyfound Only return uri when found in the database
1627 * @return string The constructed uri or the one from our database
1628 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1629 * @throws \ImagickException
1631 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1633 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1634 if (DBA::isResult($item)) {
1635 return $item["uri"];
1636 } elseif (!$onlyfound) {
1637 $person = self::personByHandle($author);
1639 $parts = parse_url($person['url']);
1640 unset($parts['path']);
1641 $host_url = Network::unparseURL($parts);
1643 return $host_url . '/objects/' . $guid;
1650 * @brief Fetch the guid from our database with a given uri
1652 * @param string $uri Message uri
1653 * @param string $uid Author handle
1655 * @return string The post guid
1656 * @throws \Exception
1658 private static function getGuidFromUri($uri, $uid)
1660 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1661 if (DBA::isResult($item)) {
1662 return $item["guid"];
1669 * @brief Find the best importer for a comment, like, ...
1671 * @param string $guid The guid of the item
1673 * @return array|boolean the origin owner of that post - or false
1674 * @throws \Exception
1676 private static function importerForGuid($guid)
1678 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1679 if (DBA::isResult($item)) {
1680 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1681 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1682 if (DBA::isResult($contact)) {
1690 * @brief Processes an incoming comment
1692 * @param array $importer Array of the importer user
1693 * @param string $sender The sender of the message
1694 * @param object $data The message object
1695 * @param string $xml The original XML of the message
1697 * @return int The message id of the generated comment or "false" if there was an error
1698 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1699 * @throws \ImagickException
1701 private static function receiveComment(array $importer, $sender, $data, $xml)
1703 $author = Strings::escapeTags(XML::unescape($data->author));
1704 $guid = Strings::escapeTags(XML::unescape($data->guid));
1705 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1706 $text = XML::unescape($data->text);
1708 if (isset($data->created_at)) {
1709 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1711 $created_at = DateTimeFormat::utcNow();
1714 if (isset($data->thread_parent_guid)) {
1715 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1716 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1721 $contact = self::allowedContactByHandle($importer, $sender, true);
1726 $message_id = self::messageExists($importer["uid"], $guid);
1731 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1732 if (!$parent_item) {
1736 $person = self::personByHandle($author);
1737 if (!is_array($person)) {
1738 Logger::log("unable to find author details");
1742 // Fetch the contact id - if we know this contact
1743 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1747 $datarray["uid"] = $importer["uid"];
1748 $datarray["contact-id"] = $author_contact["cid"];
1749 $datarray["network"] = $author_contact["network"];
1751 $datarray["author-link"] = $person["url"];
1752 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1754 $datarray["owner-link"] = $contact["url"];
1755 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1757 $datarray["guid"] = $guid;
1758 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1760 $datarray["verb"] = ACTIVITY_POST;
1761 $datarray["gravity"] = GRAVITY_COMMENT;
1763 if ($thr_uri != "") {
1764 $datarray["parent-uri"] = $thr_uri;
1766 $datarray["parent-uri"] = $parent_item["uri"];
1769 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1771 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1772 $datarray["source"] = $xml;
1774 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1776 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1778 $body = Markdown::toBBCode($text);
1780 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1782 self::fetchGuid($datarray);
1784 // If we are the origin of the parent we store the original data.
1785 // We notify our followers during the item storage.
1786 if ($parent_item["origin"]) {
1787 $datarray['diaspora_signed_text'] = json_encode($data);
1790 $message_id = Item::insert($datarray);
1792 if ($message_id <= 0) {
1797 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1798 if ($datarray['uid'] == 0) {
1799 Item::distribute($message_id, json_encode($data));
1807 * @brief processes and stores private messages
1809 * @param array $importer Array of the importer user
1810 * @param array $contact The contact of the message
1811 * @param object $data The message object
1812 * @param array $msg Array of the processed message, author handle and key
1813 * @param object $mesg The private message
1814 * @param array $conversation The conversation record to which this message belongs
1816 * @return bool "true" if it was successful
1817 * @throws \Exception
1819 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1821 $author = Strings::escapeTags(XML::unescape($data->author));
1822 $guid = Strings::escapeTags(XML::unescape($data->guid));
1823 $subject = Strings::escapeTags(XML::unescape($data->subject));
1825 // "diaspora_handle" is the element name from the old version
1826 // "author" is the element name from the new version
1827 if ($mesg->author) {
1828 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1829 } elseif ($mesg->diaspora_handle) {
1830 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1835 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1836 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1837 $msg_text = XML::unescape($mesg->text);
1838 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1840 if ($msg_conversation_guid != $guid) {
1841 Logger::log("message conversation guid does not belong to the current conversation.");
1845 $body = Markdown::toBBCode($msg_text);
1846 $message_uri = $msg_author.":".$msg_guid;
1848 $person = self::personByHandle($msg_author);
1850 return Mail::insert([
1851 'uid' => $importer['uid'],
1852 'guid' => $msg_guid,
1853 'convid' => $conversation['id'],
1854 'from-name' => $person['name'],
1855 'from-photo' => $person['photo'],
1856 'from-url' => $person['url'],
1857 'contact-id' => $contact['id'],
1858 'title' => $subject,
1860 'uri' => $message_uri,
1861 'parent-uri' => $author . ':' . $guid,
1862 'created' => $msg_created_at
1867 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1869 * @param array $importer Array of the importer user
1870 * @param array $msg Array of the processed message, author handle and key
1871 * @param object $data The message object
1873 * @return bool Success
1874 * @throws \Exception
1876 private static function receiveConversation(array $importer, $msg, $data)
1878 $author = Strings::escapeTags(XML::unescape($data->author));
1879 $guid = Strings::escapeTags(XML::unescape($data->guid));
1880 $subject = Strings::escapeTags(XML::unescape($data->subject));
1881 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1882 $participants = Strings::escapeTags(XML::unescape($data->participants));
1884 $messages = $data->message;
1886 if (!count($messages)) {
1887 Logger::log("empty conversation");
1891 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1896 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1897 if (!DBA::isResult($conversation)) {
1899 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1900 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1901 intval($importer["uid"]),
1903 DBA::escape($author),
1904 DBA::escape($created_at),
1905 DBA::escape(DateTimeFormat::utcNow()),
1906 DBA::escape($subject),
1907 DBA::escape($participants)
1910 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1913 if (!$conversation) {
1914 Logger::log("unable to create conversation.");
1918 foreach ($messages as $mesg) {
1919 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1926 * @brief Processes "like" messages
1928 * @param array $importer Array of the importer user
1929 * @param string $sender The sender of the message
1930 * @param object $data The message object
1932 * @return int The message id of the generated like or "false" if there was an error
1933 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1934 * @throws \ImagickException
1936 private static function receiveLike(array $importer, $sender, $data)
1938 $author = Strings::escapeTags(XML::unescape($data->author));
1939 $guid = Strings::escapeTags(XML::unescape($data->guid));
1940 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1941 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1942 $positive = Strings::escapeTags(XML::unescape($data->positive));
1944 // likes on comments aren't supported by Diaspora - only on posts
1945 // But maybe this will be supported in the future, so we will accept it.
1946 if (!in_array($parent_type, ["Post", "Comment"])) {
1950 $contact = self::allowedContactByHandle($importer, $sender, true);
1955 $message_id = self::messageExists($importer["uid"], $guid);
1960 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1961 if (!$parent_item) {
1965 $person = self::personByHandle($author);
1966 if (!is_array($person)) {
1967 Logger::log("unable to find author details");
1971 // Fetch the contact id - if we know this contact
1972 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1974 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1975 // We would accept this anyhow.
1976 if ($positive == "true") {
1977 $verb = ACTIVITY_LIKE;
1979 $verb = ACTIVITY_DISLIKE;
1984 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1986 $datarray["uid"] = $importer["uid"];
1987 $datarray["contact-id"] = $author_contact["cid"];
1988 $datarray["network"] = $author_contact["network"];
1990 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1991 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1993 $datarray["guid"] = $guid;
1994 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1996 $datarray["verb"] = $verb;
1997 $datarray["gravity"] = GRAVITY_ACTIVITY;
1998 $datarray["parent-uri"] = $parent_item["uri"];
2000 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2002 $datarray["body"] = $verb;
2004 // Diaspora doesn't provide a date for likes
2005 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2007 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2008 if ($parent_item["id"] != $parent_item["parent"]) {
2009 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2010 $origin = $toplevel["origin"];
2012 $origin = $parent_item["origin"];
2015 // If we are the origin of the parent we store the original data.
2016 // We notify our followers during the item storage.
2018 $datarray['diaspora_signed_text'] = json_encode($data);
2021 $message_id = Item::insert($datarray);
2023 if ($message_id <= 0) {
2028 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2029 if ($datarray['uid'] == 0) {
2030 Item::distribute($message_id, json_encode($data));
2038 * @brief Processes private messages
2040 * @param array $importer Array of the importer user
2041 * @param object $data The message object
2043 * @return bool Success?
2044 * @throws \Exception
2046 private static function receiveMessage(array $importer, $data)
2048 $author = Strings::escapeTags(XML::unescape($data->author));
2049 $guid = Strings::escapeTags(XML::unescape($data->guid));
2050 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2051 $text = XML::unescape($data->text);
2052 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2054 $contact = self::allowedContactByHandle($importer, $author, true);
2059 $conversation = null;
2061 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2062 $conversation = DBA::selectFirst('conv', [], $condition);
2064 if (!DBA::isResult($conversation)) {
2065 Logger::log("conversation not available.");
2069 $message_uri = $author.":".$guid;
2071 $person = self::personByHandle($author);
2073 Logger::log("unable to find author details");
2077 $body = Markdown::toBBCode($text);
2079 $body = self::replacePeopleGuid($body, $person["url"]);
2081 return Mail::insert([
2082 'uid' => $importer['uid'],
2084 'convid' => $conversation['id'],
2085 'from-name' => $person['name'],
2086 'from-photo' => $person['photo'],
2087 'from-url' => $person['url'],
2088 'contact-id' => $contact['id'],
2089 'title' => $conversation['subject'],
2092 'uri' => $message_uri,
2093 'parent-uri' => $author.":".$conversation['guid'],
2094 'created' => $created_at
2099 * @brief Processes participations - unsupported by now
2101 * @param array $importer Array of the importer user
2102 * @param object $data The message object
2104 * @return bool always true
2105 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2106 * @throws \ImagickException
2108 private static function receiveParticipation(array $importer, $data)
2110 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2111 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2113 $contact_id = Contact::getIdForURL($author);
2115 Logger::log('Contact not found: '.$author);
2119 $person = self::personByHandle($author);
2120 if (!is_array($person)) {
2121 Logger::log("Person not found: ".$author);
2125 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2126 if (!DBA::isResult($item)) {
2127 Logger::log('Item not found, no origin or private: '.$parent_guid);
2131 $author_parts = explode('@', $author);
2132 if (isset($author_parts[1])) {
2133 $server = $author_parts[1];
2135 // Should never happen
2139 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2141 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2142 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2145 // Send all existing comments and likes to the requesting server
2146 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2147 while ($comment = Item::fetch($comments)) {
2148 if ($comment['id'] == $comment['parent']) {
2151 if ($comment['verb'] == ACTIVITY_POST) {
2152 $cmd = $comment['self'] ? Delivery::COMMENT : 'comment-import';
2154 $cmd = $comment['self'] ? Delivery::ACTIVITY : 'activity-import';
2156 Logger::log("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, Logger::DEBUG);
2157 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2159 DBA::close($comments);
2165 * @brief Processes photos - unneeded
2167 * @param array $importer Array of the importer user
2168 * @param object $data The message object
2170 * @return bool always true
2172 private static function receivePhoto(array $importer, $data)
2174 // There doesn't seem to be a reason for this function,
2175 // since the photo data is transmitted in the status message as well
2180 * @brief Processes poll participations - unssupported
2182 * @param array $importer Array of the importer user
2183 * @param object $data The message object
2185 * @return bool always true
2187 private static function receivePollParticipation(array $importer, $data)
2189 // We don't support polls by now
2194 * @brief Processes incoming profile updates
2196 * @param array $importer Array of the importer user
2197 * @param object $data The message object
2199 * @return bool Success
2200 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2201 * @throws \ImagickException
2203 private static function receiveProfile(array $importer, $data)
2205 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2207 $contact = self::contactByHandle($importer["uid"], $author);
2212 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2213 $image_url = XML::unescape($data->image_url);
2214 $birthday = XML::unescape($data->birthday);
2215 $gender = XML::unescape($data->gender);
2216 $about = Markdown::toBBCode(XML::unescape($data->bio));
2217 $location = Markdown::toBBCode(XML::unescape($data->location));
2218 $searchable = (XML::unescape($data->searchable) == "true");
2219 $nsfw = (XML::unescape($data->nsfw) == "true");
2220 $tags = XML::unescape($data->tag_string);
2222 $tags = explode("#", $tags);
2225 foreach ($tags as $tag) {
2226 $tag = trim(strtolower($tag));
2232 $keywords = implode(", ", $keywords);
2234 $handle_parts = explode("@", $author);
2235 $nick = $handle_parts[0];
2238 $name = $handle_parts[0];
2241 if (preg_match("|^https?://|", $image_url) === 0) {
2242 $image_url = "http://".$handle_parts[1].$image_url;
2245 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2247 // Generic birthday. We don't know the timezone. The year is irrelevant.
2249 $birthday = str_replace("1000", "1901", $birthday);
2251 if ($birthday != "") {
2252 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2255 // this is to prevent multiple birthday notifications in a single year
2256 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2258 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2259 $birthday = $contact["bd"];
2262 $fields = ['name' => $name, 'location' => $location,
2263 'name-date' => DateTimeFormat::utcNow(),
2264 'about' => $about, 'gender' => $gender,
2265 'addr' => $author, 'nick' => $nick,
2266 'keywords' => $keywords];
2268 if (!empty($birthday)) {
2269 $fields['bd'] = $birthday;
2272 DBA::update('contact', $fields, ['id' => $contact['id']]);
2274 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2275 "photo" => $image_url, "name" => $name, "location" => $location,
2276 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2277 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2278 "hide" => !$searchable, "nsfw" => $nsfw];
2280 $gcid = GContact::update($gcontact);
2282 GContact::link($gcid, $importer["uid"], $contact["id"]);
2284 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2290 * @brief Processes incoming friend requests
2292 * @param array $importer Array of the importer user
2293 * @param array $contact The contact that send the request
2295 * @throws \Exception
2297 private static function receiveRequestMakeFriend(array $importer, array $contact)
2299 if ($contact["rel"] == Contact::SHARING) {
2302 ['rel' => Contact::FRIEND, 'writable' => true],
2303 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2309 * @brief Processes incoming sharing notification
2311 * @param array $importer Array of the importer user
2312 * @param object $data The message object
2314 * @return bool Success
2315 * @throws \Exception
2317 private static function receiveContactRequest(array $importer, $data)
2319 $author = XML::unescape($data->author);
2320 $recipient = XML::unescape($data->recipient);
2322 if (!$author || !$recipient) {
2326 // the current protocol version doesn't know these fields
2327 // That means that we will assume their existance
2328 if (isset($data->following)) {
2329 $following = (XML::unescape($data->following) == "true");
2334 if (isset($data->sharing)) {
2335 $sharing = (XML::unescape($data->sharing) == "true");
2340 $contact = self::contactByHandle($importer["uid"], $author);
2342 // perhaps we were already sharing with this person. Now they're sharing with us.
2343 // That makes us friends.
2346 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2347 self::receiveRequestMakeFriend($importer, $contact);
2349 // refetch the contact array
2350 $contact = self::contactByHandle($importer["uid"], $author);
2352 // If we are now friends, we are sending a share message.
2353 // Normally we needn't to do so, but the first message could have been vanished.
2354 if (in_array($contact["rel"], [Contact::FRIEND])) {
2355 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2356 if (DBA::isResult($user)) {
2357 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2358 self::sendShare($user, $contact);
2363 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2364 Contact::removeFollower($importer, $contact);
2369 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2370 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2372 } elseif (!$following && !$sharing) {
2373 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2375 } elseif (!$following && $sharing) {
2376 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2377 } elseif ($following && $sharing) {
2378 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2379 } elseif ($following && !$sharing) {
2380 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2383 $ret = self::personByHandle($author);
2385 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2386 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2390 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2393 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2394 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2395 intval($importer["uid"]),
2396 DBA::escape($ret["network"]),
2397 DBA::escape($ret["addr"]),
2398 DateTimeFormat::utcNow(),
2399 DBA::escape($ret["url"]),
2400 DBA::escape(Strings::normaliseLink($ret["url"])),
2401 DBA::escape($batch),
2402 DBA::escape($ret["name"]),
2403 DBA::escape($ret["nick"]),
2404 DBA::escape($ret["photo"]),
2405 DBA::escape($ret["pubkey"]),
2406 DBA::escape($ret["notify"]),
2407 DBA::escape($ret["poll"]),
2412 // find the contact record we just created
2414 $contact_record = self::contactByHandle($importer["uid"], $author);
2416 if (!$contact_record) {
2417 Logger::log("unable to locate newly created contact record.");
2421 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2423 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2425 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2427 if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
2428 Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2430 $hash = Strings::getRandomHex().(string)time(); // Generate a confirm_key
2433 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2434 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2435 intval($importer["uid"]),
2436 intval($contact_record["id"]),
2439 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2441 DBA::escape(DateTimeFormat::utcNow())
2444 // automatic friend approval
2446 Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2448 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2451 * technically they are sharing with us (Contact::SHARING),
2452 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2453 * we are going to change the relationship and make them a follower.
2455 if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
2456 $new_relation = Contact::FRIEND;
2457 } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
2458 $new_relation = Contact::SHARING;
2460 $new_relation = Contact::FOLLOWER;
2464 "UPDATE `contact` SET `rel` = %d,
2472 intval($new_relation),
2473 DBA::escape(DateTimeFormat::utcNow()),
2474 DBA::escape(DateTimeFormat::utcNow()),
2475 intval($contact_record["id"])
2478 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2479 if (DBA::isResult($user)) {
2480 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2481 self::sendShare($user, $contact_record);
2483 // Send the profile data, maybe it weren't transmitted before
2484 self::sendProfile($importer["uid"], [$contact_record]);
2492 * @brief Fetches a message with a given guid
2494 * @param string $guid message guid
2495 * @param string $orig_author handle of the original post
2496 * @return array The fetched item
2497 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2498 * @throws \ImagickException
2500 public static function originalItem($guid, $orig_author)
2503 Logger::log('Empty guid. Quitting.');
2507 // Do we already have this item?
2508 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2509 'author-name', 'author-link', 'author-avatar'];
2510 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2511 $item = Item::selectFirst($fields, $condition);
2513 if (DBA::isResult($item)) {
2514 Logger::log("reshared message ".$guid." already exists on system.");
2516 // Maybe it is already a reshared item?
2517 // Then refetch the content, if it is a reshare from a reshare.
2518 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2519 if (self::isReshare($item["body"], true)) {
2521 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2522 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2524 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2526 // Add OEmbed and other information to the body
2527 $item["body"] = add_page_info_to_body($item["body"], false, true);
2535 if (!DBA::isResult($item)) {
2536 if (empty($orig_author)) {
2537 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2541 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2542 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2543 $stored = self::storeByGuid($guid, $server);
2546 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2547 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2548 $stored = self::storeByGuid($guid, $server);
2552 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2553 'author-name', 'author-link', 'author-avatar'];
2554 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2555 $item = Item::selectFirst($fields, $condition);
2557 if (DBA::isResult($item)) {
2558 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2559 if (self::isReshare($item["body"], false)) {
2560 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2561 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2572 * @brief Stores a reshare activity
2574 * @param array $item Array of reshare post
2575 * @param integer $parent_message_id Id of the parent post
2576 * @param string $guid GUID string of reshare action
2577 * @param string $author Author handle
2579 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2581 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2585 $datarray['uid'] = $item['uid'];
2586 $datarray['contact-id'] = $item['contact-id'];
2587 $datarray['network'] = $item['network'];
2589 $datarray['author-link'] = $item['author-link'];
2590 $datarray['author-id'] = $item['author-id'];
2592 $datarray['owner-link'] = $datarray['author-link'];
2593 $datarray['owner-id'] = $datarray['author-id'];
2595 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2596 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2597 $datarray['parent-uri'] = $parent['uri'];
2599 $datarray['verb'] = $datarray['body'] = ACTIVITY2_ANNOUNCE;
2600 $datarray['gravity'] = GRAVITY_ACTIVITY;
2601 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
2603 $datarray['protocol'] = $item['protocol'];
2605 $datarray['plink'] = self::plink($author, $datarray['guid']);
2606 $datarray['private'] = $item['private'];
2607 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2609 $message_id = Item::insert($datarray);
2612 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2613 if ($datarray['uid'] == 0) {
2614 Item::distribute($message_id);
2620 * @brief Processes a reshare message
2622 * @param array $importer Array of the importer user
2623 * @param object $data The message object
2624 * @param string $xml The original XML of the message
2626 * @return int the message id
2627 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2628 * @throws \ImagickException
2630 private static function receiveReshare(array $importer, $data, $xml)
2632 $author = Strings::escapeTags(XML::unescape($data->author));
2633 $guid = Strings::escapeTags(XML::unescape($data->guid));
2634 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2635 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2636 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2637 /// @todo handle unprocessed property "provider_display_name"
2638 $public = Strings::escapeTags(XML::unescape($data->public));
2640 $contact = self::allowedContactByHandle($importer, $author, false);
2645 $message_id = self::messageExists($importer["uid"], $guid);
2650 $original_item = self::originalItem($root_guid, $root_author);
2651 if (!$original_item) {
2655 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2659 $datarray["uid"] = $importer["uid"];
2660 $datarray["contact-id"] = $contact["id"];
2661 $datarray["network"] = Protocol::DIASPORA;
2663 $datarray["author-link"] = $contact["url"];
2664 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2666 $datarray["owner-link"] = $datarray["author-link"];
2667 $datarray["owner-id"] = $datarray["author-id"];
2669 $datarray["guid"] = $guid;
2670 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2672 $datarray["verb"] = ACTIVITY_POST;
2673 $datarray["gravity"] = GRAVITY_PARENT;
2675 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2676 $datarray["source"] = $xml;
2678 $prefix = share_header(
2679 $original_item["author-name"],
2680 $original_item["author-link"],
2681 $original_item["author-avatar"],
2682 $original_item["guid"],
2683 $original_item["created"],
2686 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2688 $datarray["tag"] = $original_item["tag"];
2689 $datarray["app"] = $original_item["app"];
2691 $datarray["plink"] = self::plink($author, $guid);
2692 $datarray["private"] = (($public == "false") ? 1 : 0);
2693 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2695 $datarray["object-type"] = $original_item["object-type"];
2697 self::fetchGuid($datarray);
2698 $message_id = Item::insert($datarray);
2700 self::sendParticipation($contact, $datarray);
2702 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2703 if ($root_message_id) {
2704 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2708 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2709 if ($datarray['uid'] == 0) {
2710 Item::distribute($message_id);
2719 * @brief Processes retractions
2721 * @param array $importer Array of the importer user
2722 * @param array $contact The contact of the item owner
2723 * @param object $data The message object
2725 * @return bool success
2726 * @throws \Exception
2728 private static function itemRetraction(array $importer, array $contact, $data)
2730 $author = Strings::escapeTags(XML::unescape($data->author));
2731 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2732 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2734 $person = self::personByHandle($author);
2735 if (!is_array($person)) {
2736 Logger::log("unable to find author detail for ".$author);
2740 if (empty($contact["url"])) {
2741 $contact["url"] = $person["url"];
2744 // Fetch items that are about to be deleted
2745 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2747 // When we receive a public retraction, we delete every item that we find.
2748 if ($importer['uid'] == 0) {
2749 $condition = ['guid' => $target_guid, 'deleted' => false];
2751 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2754 $r = Item::select($fields, $condition);
2755 if (!DBA::isResult($r)) {
2756 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2760 while ($item = Item::fetch($r)) {
2761 if (strstr($item['file'], '[')) {
2762 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2766 // Fetch the parent item
2767 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2769 // Only delete it if the parent author really fits
2770 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2771 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2775 Item::delete(['id' => $item['id']]);
2777 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2784 * @brief Receives retraction messages
2786 * @param array $importer Array of the importer user
2787 * @param string $sender The sender of the message
2788 * @param object $data The message object
2790 * @return bool Success
2791 * @throws \Exception
2793 private static function receiveRetraction(array $importer, $sender, $data)
2795 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2797 $contact = self::contactByHandle($importer["uid"], $sender);
2798 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2799 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2807 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2809 switch ($target_type) {
2814 case "StatusMessage":
2815 return self::itemRetraction($importer, $contact, $data);
2817 case "PollParticipation":
2819 // Currently unsupported
2823 Logger::log("Unknown target type ".$target_type);
2830 * @brief Receives status messages
2832 * @param array $importer Array of the importer user
2833 * @param SimpleXMLElement $data The message object
2834 * @param string $xml The original XML of the message
2836 * @return int The message id of the newly created item
2837 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2838 * @throws \ImagickException
2840 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2842 $author = Strings::escapeTags(XML::unescape($data->author));
2843 $guid = Strings::escapeTags(XML::unescape($data->guid));
2844 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2845 $public = Strings::escapeTags(XML::unescape($data->public));
2846 $text = XML::unescape($data->text);
2847 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2849 $contact = self::allowedContactByHandle($importer, $author, false);
2854 $message_id = self::messageExists($importer["uid"], $guid);
2860 if ($data->location) {
2861 foreach ($data->location->children() as $fieldname => $data) {
2862 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2866 $body = Markdown::toBBCode($text);
2870 // Attach embedded pictures to the body
2872 foreach ($data->photo as $photo) {
2873 $body = "[img]".XML::unescape($photo->remote_photo_path).
2874 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2877 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2879 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2881 // Add OEmbed and other information to the body
2882 if (!self::isRedmatrix($contact["url"])) {
2883 $body = add_page_info_to_body($body, false, true);
2887 /// @todo enable support for polls
2888 //if ($data->poll) {
2889 // foreach ($data->poll AS $poll)
2894 /// @todo enable support for events
2896 $datarray["uid"] = $importer["uid"];
2897 $datarray["contact-id"] = $contact["id"];
2898 $datarray["network"] = Protocol::DIASPORA;
2900 $datarray["author-link"] = $contact["url"];
2901 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2903 $datarray["owner-link"] = $datarray["author-link"];
2904 $datarray["owner-id"] = $datarray["author-id"];
2906 $datarray["guid"] = $guid;
2907 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2909 $datarray["verb"] = ACTIVITY_POST;
2910 $datarray["gravity"] = GRAVITY_PARENT;
2912 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2913 $datarray["source"] = $xml;
2915 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2917 if ($provider_display_name != "") {
2918 $datarray["app"] = $provider_display_name;
2921 $datarray["plink"] = self::plink($author, $guid);
2922 $datarray["private"] = (($public == "false") ? 1 : 0);
2923 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2925 if (isset($address["address"])) {
2926 $datarray["location"] = $address["address"];
2929 if (isset($address["lat"]) && isset($address["lng"])) {
2930 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2933 self::fetchGuid($datarray);
2934 $message_id = Item::insert($datarray);
2936 self::sendParticipation($contact, $datarray);
2939 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2940 if ($datarray['uid'] == 0) {
2941 Item::distribute($message_id);
2949 /* ************************************************************************************** *
2950 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2951 * ************************************************************************************** */
2954 * @brief returnes the handle of a contact
2956 * @param array $contact contact array
2958 * @return string the handle in the format user@domain.tld
2959 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2961 private static function myHandle(array $contact)
2963 if (!empty($contact["addr"])) {
2964 return $contact["addr"];
2967 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2968 // So - just in case - we build the the address here.
2969 if ($contact["nickname"] != "") {
2970 $nick = $contact["nickname"];
2972 $nick = $contact["nick"];
2975 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2980 * @brief Creates the data for a private message in the new format
2982 * @param string $msg The message that is to be transmitted
2983 * @param array $user The record of the sender
2984 * @param array $contact Target of the communication
2985 * @param string $prvkey The private key of the sender
2986 * @param string $pubkey The public key of the receiver
2988 * @return string The encrypted data
2989 * @throws \Exception
2991 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2993 Logger::log("Message: ".$msg, Logger::DATA);
2995 // without a public key nothing will work
2997 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3001 $aes_key = openssl_random_pseudo_bytes(32);
3002 $b_aes_key = base64_encode($aes_key);
3003 $iv = openssl_random_pseudo_bytes(16);
3004 $b_iv = base64_encode($iv);
3006 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3008 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3010 $encrypted_key_bundle = "";
3011 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3013 $json_object = json_encode(
3014 ["aes_key" => base64_encode($encrypted_key_bundle),
3015 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3018 return $json_object;
3022 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3024 * @param string $msg The message that is to be transmitted
3025 * @param array $user The record of the sender
3027 * @return string The envelope
3028 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3030 public static function buildMagicEnvelope($msg, array $user)
3032 $b64url_data = Strings::base64UrlEncode($msg);
3033 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3035 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3036 $type = "application/xml";
3037 $encoding = "base64url";
3038 $alg = "RSA-SHA256";
3039 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3041 // Fallback if the private key wasn't transmitted in the expected field
3042 if ($user['uprvkey'] == "") {
3043 $user['uprvkey'] = $user['prvkey'];
3046 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3047 $sig = Strings::base64UrlEncode($signature);
3049 $xmldata = ["me:env" => ["me:data" => $data,
3050 "@attributes" => ["type" => $type],
3051 "me:encoding" => $encoding,
3054 "@attributes2" => ["key_id" => $key_id]]];
3056 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3058 return XML::fromArray($xmldata, $xml, false, $namespaces);
3062 * @brief Create the envelope for a message
3064 * @param string $msg The message that is to be transmitted
3065 * @param array $user The record of the sender
3066 * @param array $contact Target of the communication
3067 * @param string $prvkey The private key of the sender
3068 * @param string $pubkey The public key of the receiver
3069 * @param bool $public Is the message public?
3071 * @return string The message that will be transmitted to other servers
3072 * @throws \Exception
3074 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3076 // The message is put into an envelope with the sender's signature
3077 $envelope = self::buildMagicEnvelope($msg, $user);
3079 // Private messages are put into a second envelope, encrypted with the receivers public key
3081 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3088 * @brief Creates a signature for a message
3090 * @param array $owner the array of the owner of the message
3091 * @param array $message The message that is to be signed
3093 * @return string The signature
3095 private static function signature($owner, $message)
3098 unset($sigmsg["author_signature"]);
3099 unset($sigmsg["parent_author_signature"]);
3101 $signed_text = implode(";", $sigmsg);
3103 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3107 * @brief Transmit a message to a target server
3109 * @param array $owner the array of the item owner
3110 * @param array $contact Target of the communication
3111 * @param string $envelope The message that is to be transmitted
3112 * @param bool $public_batch Is it a public post?
3113 * @param string $guid message guid
3115 * @return int Result of the transmission
3116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3117 * @throws \ImagickException
3119 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3121 $enabled = intval(Config::get("system", "diaspora_enabled"));
3126 $logid = Strings::getRandomHex(4);
3128 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3130 // We always try to use the data from the fcontact table.
3131 // This is important for transmitting data to Friendica servers.
3132 if (!empty($contact['addr'])) {
3133 $fcontact = self::personByHandle($contact['addr']);
3134 if (!empty($fcontact)) {
3135 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3140 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3144 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3146 if (!intval(Config::get("system", "diaspora_test"))) {
3147 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3149 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3150 $return_code = $postResult->getReturnCode();
3152 Logger::log("test_mode");
3156 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3158 return $return_code ? $return_code : -1;
3163 * @brief Build the post xml
3165 * @param string $type The message type
3166 * @param array $message The message data
3168 * @return string The post XML
3170 public static function buildPostXml($type, $message)
3172 $data = [$type => $message];
3174 return XML::fromArray($data, $xml);
3178 * @brief Builds and transmit messages
3180 * @param array $owner the array of the item owner
3181 * @param array $contact Target of the communication
3182 * @param string $type The message type
3183 * @param array $message The message data
3184 * @param bool $public_batch Is it a public post?
3185 * @param string $guid message guid
3187 * @return int Result of the transmission
3188 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3189 * @throws \ImagickException
3191 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3193 $msg = self::buildPostXml($type, $message);
3195 Logger::log('message: '.$msg, Logger::DATA);
3196 Logger::log('send guid '.$guid, Logger::DEBUG);
3198 // Fallback if the private key wasn't transmitted in the expected field
3199 if (empty($owner['uprvkey'])) {
3200 $owner['uprvkey'] = $owner['prvkey'];
3203 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3205 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3207 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3209 return $return_code;
3213 * @brief sends a participation (Used to get all further updates)
3215 * @param array $contact Target of the communication
3216 * @param array $item Item array
3218 * @return int The result of the transmission
3219 * @throws \Exception
3221 private static function sendParticipation(array $contact, array $item)
3223 // Don't send notifications for private postings
3224 if ($item['private']) {
3228 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3230 $result = Cache::get($cachekey);
3231 if (!is_null($result)) {
3235 // Fetch some user id to have a valid handle to transmit the participation.
3236 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3237 // If the item belongs to a user, we take this user id.
3238 if ($item['uid'] == 0) {
3239 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3240 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3241 $owner = User::getOwnerDataById($first_user['uid']);
3243 $owner = User::getOwnerDataById($item['uid']);
3246 $author = self::myHandle($owner);
3248 $message = ["author" => $author,
3249 "guid" => System::createUUID(),
3250 "parent_type" => "Post",
3251 "parent_guid" => $item["guid"]];
3253 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3255 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3256 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3258 return self::buildAndTransmit($owner, $contact, "participation", $message);
3262 * @brief sends an account migration
3264 * @param array $owner the array of the item owner
3265 * @param array $contact Target of the communication
3266 * @param int $uid User ID
3268 * @return int The result of the transmission
3269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3270 * @throws \ImagickException
3272 public static function sendAccountMigration(array $owner, array $contact, $uid)
3274 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3275 $profile = self::createProfileData($uid);
3277 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3278 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3280 $message = ["author" => $old_handle,
3281 "profile" => $profile,
3282 "signature" => $signature];
3284 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3286 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3290 * @brief Sends a "share" message
3292 * @param array $owner the array of the item owner
3293 * @param array $contact Target of the communication
3295 * @return int The result of the transmission
3296 * @throws \Exception
3298 public static function sendShare(array $owner, array $contact)
3301 * @todo support the different possible combinations of "following" and "sharing"
3302 * Currently, Diaspora only interprets the "sharing" field
3304 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3308 switch ($contact["rel"]) {
3309 case Contact::FRIEND:
3313 case Contact::SHARING:
3317 case Contact::FOLLOWER:
3323 $message = ["author" => self::myHandle($owner),
3324 "recipient" => $contact["addr"],
3325 "following" => "true",
3326 "sharing" => "true"];
3328 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3330 return self::buildAndTransmit($owner, $contact, "contact", $message);
3334 * @brief sends an "unshare"
3336 * @param array $owner the array of the item owner
3337 * @param array $contact Target of the communication
3339 * @return int The result of the transmission
3340 * @throws \Exception
3342 public static function sendUnshare(array $owner, array $contact)
3344 $message = ["author" => self::myHandle($owner),
3345 "recipient" => $contact["addr"],
3346 "following" => "false",
3347 "sharing" => "false"];
3349 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3351 return self::buildAndTransmit($owner, $contact, "contact", $message);
3355 * @brief Checks a message body if it is a reshare
3357 * @param string $body The message body that is to be check
3358 * @param bool $complete Should it be a complete check or a simple check?
3360 * @return array|bool Reshare details or "false" if no reshare
3361 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3362 * @throws \ImagickException
3364 public static function isReshare($body, $complete = true)
3366 $body = trim($body);
3368 // Skip if it isn't a pure repeated messages
3369 // Does it start with a share?
3370 if ((strpos($body, "[share") > 0) && $complete) {
3374 // Does it end with a share?
3375 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3379 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3380 // Skip if there is no shared message in there
3381 if ($body == $attributes) {
3385 // If we don't do the complete check we quit here
3388 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3389 if (!empty($matches[1])) {
3390 $guid = $matches[1];
3393 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3394 if (!empty($matches[1])) {
3395 $guid = $matches[1];
3398 if (($guid != "") && $complete) {
3399 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3400 $item = Item::selectFirst(['contact-id'], $condition);
3401 if (DBA::isResult($item)) {
3403 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3404 $ret["root_guid"] = $guid;
3406 } elseif ($complete) {
3407 // We are resharing something that isn't a DFRN or Diaspora post.
3408 // So we have to return "false" on "$complete" to not trigger a reshare.
3411 } elseif (($guid == "") && $complete) {
3415 $ret["root_guid"] = $guid;
3418 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3419 if (!empty($matches[1])) {
3420 $profile = $matches[1];
3423 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3424 if (!empty($matches[1])) {
3425 $profile = $matches[1];
3430 if ($profile != "") {
3431 if (Contact::getIdForURL($profile)) {
3432 $author = Contact::getDetailsByURL($profile);
3433 $ret["root_handle"] = $author['addr'];
3437 if (empty($ret) && !$complete) {
3445 * @brief Create an event array
3447 * @param integer $event_id The id of the event
3449 * @return array with event data
3450 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3452 private static function buildEvent($event_id)
3454 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3455 if (!DBA::isResult($r)) {
3463 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3464 if (!DBA::isResult($r)) {
3470 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3471 if (!DBA::isResult($r)) {
3477 $eventdata['author'] = self::myHandle($owner);
3479 if ($event['guid']) {
3480 $eventdata['guid'] = $event['guid'];
3483 $mask = DateTimeFormat::ATOM;
3485 /// @todo - establish "all day" events in Friendica
3486 $eventdata["all_day"] = "false";
3488 $eventdata['timezone'] = 'UTC';
3489 if (!$event['adjust'] && $user['timezone']) {
3490 $eventdata['timezone'] = $user['timezone'];
3493 if ($event['start']) {
3494 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3496 if ($event['finish'] && !$event['nofinish']) {
3497 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3499 if ($event['summary']) {
3500 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3502 if ($event['desc']) {
3503 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3505 if ($event['location']) {
3506 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3507 $coord = Map::getCoordinates($event['location']);
3510 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3511 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3512 $location["lat"] = $coord['lat'];
3513 $location["lng"] = $coord['lon'];
3515 $location["lat"] = 0;
3516 $location["lng"] = 0;
3518 $eventdata['location'] = $location;
3525 * @brief Create a post (status message or reshare)
3527 * @param array $item The item that will be exported
3528 * @param array $owner the array of the item owner
3531 * 'type' -> Message type ("status_message" or "reshare")
3532 * 'message' -> Array of XML elements of the status
3533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3534 * @throws \ImagickException
3536 public static function buildStatus(array $item, array $owner)
3538 $cachekey = "diaspora:buildStatus:".$item['guid'];
3540 $result = Cache::get($cachekey);
3541 if (!is_null($result)) {
3545 $myaddr = self::myHandle($owner);
3547 $public = ($item["private"] ? "false" : "true");
3549 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3550 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3552 // Detect a share element and do a reshare
3553 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3554 $message = ["author" => $myaddr,
3555 "guid" => $item["guid"],
3556 "created_at" => $created,
3557 "root_author" => $ret["root_handle"],
3558 "root_guid" => $ret["root_guid"],
3559 "provider_display_name" => $item["app"],
3560 "public" => $public];
3564 $title = $item["title"];
3565 $body = $item["body"];
3567 if ($item['author-link'] != $item['owner-link']) {
3568 require_once 'mod/share.php';
3569 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3570 "", $item['created'], $item['plink']) . $body . '[/share]';
3573 // convert to markdown
3574 $body = html_entity_decode(BBCode::toMarkdown($body));
3577 if (strlen($title)) {
3578 $body = "## ".html_entity_decode($title)."\n\n".$body;
3581 if ($item["attach"]) {
3582 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3584 $body .= "\n".L10n::t("Attachments:")."\n";
3585 foreach ($matches as $mtch) {
3586 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3593 if ($item["location"] != "")
3594 $location["address"] = $item["location"];
3596 if ($item["coord"] != "") {
3597 $coord = explode(" ", $item["coord"]);
3598 $location["lat"] = $coord[0];
3599 $location["lng"] = $coord[1];
3602 $message = ["author" => $myaddr,
3603 "guid" => $item["guid"],
3604 "created_at" => $created,
3605 "edited_at" => $edited,
3606 "public" => $public,
3608 "provider_display_name" => $item["app"],
3609 "location" => $location];
3611 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3612 if (!isset($location["lat"]) || !isset($location["lng"])) {
3613 unset($message["location"]);
3616 if ($item['event-id'] > 0) {
3617 $event = self::buildEvent($item['event-id']);
3618 if (count($event)) {
3619 $message['event'] = $event;
3621 if (!empty($event['location']['address']) &&
3622 !empty($event['location']['lat']) &&
3623 !empty($event['location']['lng'])) {
3624 $message['location'] = $event['location'];
3627 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3628 // $message['text'] = '';
3632 $type = "status_message";
3635 $msg = ["type" => $type, "message" => $message];
3637 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3642 private static function prependParentAuthorMention($body, $profile_url)
3644 $profile = Contact::getDetailsByURL($profile_url);
3645 if (!empty($profile['addr'])
3646 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3647 && !strstr($body, $profile['addr'])
3648 && !strstr($body, $profile_url)
3650 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3657 * @brief Sends a post
3659 * @param array $item The item that will be exported
3660 * @param array $owner the array of the item owner
3661 * @param array $contact Target of the communication
3662 * @param bool $public_batch Is it a public post?
3664 * @return int The result of the transmission
3665 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3666 * @throws \ImagickException
3668 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3670 $status = self::buildStatus($item, $owner);
3672 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3676 * @brief Creates a "like" object
3678 * @param array $item The item that will be exported
3679 * @param array $owner the array of the item owner
3681 * @return array The data for a "like"
3682 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3684 private static function constructLike(array $item, array $owner)
3686 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3687 if (!DBA::isResult($parent)) {
3691 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3693 if ($item['verb'] === ACTIVITY_LIKE) {
3695 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3696 $positive = "false";
3699 return(["author" => self::myHandle($owner),
3700 "guid" => $item["guid"],
3701 "parent_guid" => $parent["guid"],
3702 "parent_type" => $target_type,
3703 "positive" => $positive,
3704 "author_signature" => ""]);
3708 * @brief Creates an "EventParticipation" object
3710 * @param array $item The item that will be exported
3711 * @param array $owner the array of the item owner
3713 * @return array The data for an "EventParticipation"
3714 * @throws \Exception
3716 private static function constructAttend(array $item, array $owner)
3718 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3719 if (!DBA::isResult($parent)) {
3723 switch ($item['verb']) {
3724 case ACTIVITY_ATTEND:
3725 $attend_answer = 'accepted';
3727 case ACTIVITY_ATTENDNO:
3728 $attend_answer = 'declined';
3730 case ACTIVITY_ATTENDMAYBE:
3731 $attend_answer = 'tentative';
3734 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3738 return(["author" => self::myHandle($owner),
3739 "guid" => $item["guid"],
3740 "parent_guid" => $parent["guid"],
3741 "status" => $attend_answer,
3742 "author_signature" => ""]);
3746 * @brief Creates the object for a comment
3748 * @param array $item The item that will be exported
3749 * @param array $owner the array of the item owner
3751 * @return array|false The data for a comment
3752 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3754 private static function constructComment(array $item, array $owner)
3756 $cachekey = "diaspora:constructComment:".$item['guid'];
3758 $result = Cache::get($cachekey);
3759 if (!is_null($result)) {
3763 $toplevel_item = Item::selectFirst(['guid', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3764 if (!DBA::isResult($toplevel_item)) {
3765 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3769 $thread_parent_item = $toplevel_item;
3770 if ($item['thr-parent'] != $item['parent-uri']) {
3771 $thread_parent_item = Item::selectFirst(['guid', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3774 $body = $item["body"];
3776 if ((empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3777 && !Config::get('system', 'disable_implicit_mentions')
3779 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3782 $text = html_entity_decode(BBCode::toMarkdown($body));
3783 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3784 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3787 "author" => self::myHandle($owner),
3788 "guid" => $item["guid"],
3789 "created_at" => $created,
3790 "edited_at" => $edited,
3791 "parent_guid" => $toplevel_item["guid"],
3793 "author_signature" => ""
3796 // Send the thread parent guid only if it is a threaded comment
3797 if ($item['thr-parent'] != $item['parent-uri']) {
3798 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3801 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3807 * @brief Send a like or a comment
3809 * @param array $item The item that will be exported
3810 * @param array $owner the array of the item owner
3811 * @param array $contact Target of the communication
3812 * @param bool $public_batch Is it a public post?
3814 * @return int The result of the transmission
3815 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3816 * @throws \ImagickException
3818 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3820 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3821 $message = self::constructAttend($item, $owner);
3822 $type = "event_participation";
3823 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3824 $message = self::constructLike($item, $owner);
3826 } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW, ACTIVITY_TAG])) {
3827 $message = self::constructComment($item, $owner);
3831 if (empty($message)) {
3835 $message["author_signature"] = self::signature($owner, $message);
3837 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3841 * @brief Creates a message from a signature record entry
3843 * @param array $item The item that will be exported
3844 * @return array The message
3846 private static function messageFromSignature(array $item)
3848 // Split the signed text
3849 $signed_parts = explode(";", $item['signed_text']);
3851 if ($item["deleted"]) {
3852 $message = ["author" => $item['signer'],
3853 "target_guid" => $signed_parts[0],
3854 "target_type" => $signed_parts[1]];
3855 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3856 $message = ["author" => $signed_parts[4],
3857 "guid" => $signed_parts[1],
3858 "parent_guid" => $signed_parts[3],
3859 "parent_type" => $signed_parts[2],
3860 "positive" => $signed_parts[0],
3861 "author_signature" => $item['signature'],
3862 "parent_author_signature" => ""];
3864 // Remove the comment guid
3865 $guid = array_shift($signed_parts);
3867 // Remove the parent guid
3868 $parent_guid = array_shift($signed_parts);
3870 // Remove the handle
3871 $handle = array_pop($signed_parts);
3874 "author" => $handle,
3876 "parent_guid" => $parent_guid,
3877 "text" => implode(";", $signed_parts),
3878 "author_signature" => $item['signature'],
3879 "parent_author_signature" => ""
3886 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3888 * @param array $item The item that will be exported
3889 * @param array $owner the array of the item owner
3890 * @param array $contact Target of the communication
3891 * @param bool $public_batch Is it a public post?
3893 * @return int The result of the transmission
3894 * @throws \Exception
3896 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3898 if ($item["deleted"]) {
3899 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3900 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3906 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3908 // Old way - is used by the internal Friendica functions
3909 /// @todo Change all signatur storing functions to the new format
3910 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
3911 $message = self::messageFromSignature($item);
3913 $msg = json_decode($item['signed_text'], true);
3916 if (is_array($msg)) {
3917 foreach ($msg as $field => $data) {
3918 if (!$item["deleted"]) {
3919 if ($field == "diaspora_handle") {
3922 if ($field == "target_type") {
3923 $field = "parent_type";
3927 $message[$field] = $data;
3930 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3934 $message["parent_author_signature"] = self::signature($owner, $message);
3936 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
3938 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3942 * @brief Sends a retraction (deletion) of a message, like or comment
3944 * @param array $item The item that will be exported
3945 * @param array $owner the array of the item owner
3946 * @param array $contact Target of the communication
3947 * @param bool $public_batch Is it a public post?
3948 * @param bool $relay Is the retraction transmitted from a relay?
3950 * @return int The result of the transmission
3951 * @throws \Exception
3953 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3955 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3957 $msg_type = "retraction";
3959 if ($item['id'] == $item['parent']) {
3960 $target_type = "Post";
3961 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3962 $target_type = "Like";
3964 $target_type = "Comment";
3967 $message = ["author" => $itemaddr,
3968 "target_guid" => $item['guid'],
3969 "target_type" => $target_type];
3971 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
3973 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3977 * @brief Sends a mail
3979 * @param array $item The item that will be exported
3980 * @param array $owner The owner
3981 * @param array $contact Target of the communication
3983 * @return int The result of the transmission
3984 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3985 * @throws \ImagickException
3987 public static function sendMail(array $item, array $owner, array $contact)
3989 $myaddr = self::myHandle($owner);
3991 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3992 if (!DBA::isResult($cnv)) {
3993 Logger::log("conversation not found.");
3997 $body = BBCode::toMarkdown($item["body"]);
3998 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4001 "author" => $myaddr,
4002 "guid" => $item["guid"],
4003 "conversation_guid" => $cnv["guid"],
4005 "created_at" => $created,
4008 if ($item["reply"]) {
4013 "author" => $cnv["creator"],
4014 "guid" => $cnv["guid"],
4015 "subject" => $cnv["subject"],
4016 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4017 "participants" => $cnv["recips"],
4021 $type = "conversation";
4024 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4028 * @brief Split a name into first name and last name
4030 * @param string $name The name
4032 * @return array The array with "first" and "last"
4034 public static function splitName($name) {
4035 $name = trim($name);
4037 // Is the name longer than 64 characters? Then cut the rest of it.
4038 if (strlen($name) > 64) {
4039 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4040 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4042 $name = substr($name, 0, 64);
4046 // Take the first word as first name
4047 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4048 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4049 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4050 return ['first' => $first, 'last' => $last];
4053 // Take the last word as last name
4054 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4055 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4057 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4058 return ['first' => $first, 'last' => $last];
4061 // Take the first 32 characters if there is no space in the first 32 characters
4062 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4063 $first = substr($name, 0, 32);
4064 $last = substr($name, 32);
4065 return ['first' => $first, 'last' => $last];
4068 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4069 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4071 // Check if the last name is longer than 32 characters
4072 if (strlen($last) > 32) {
4073 if (strpos($last, ' ') <= 32) {
4074 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4076 $last = substr($last, 0, 32);
4080 return ['first' => $first, 'last' => $last];
4084 * @brief Create profile data
4086 * @param int $uid The user id
4088 * @return array The profile data
4089 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4091 private static function createProfileData($uid)
4094 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4096 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4097 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4098 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4107 $handle = $profile["addr"];
4109 $split_name = self::splitName($profile['name']);
4110 $first = $split_name['first'];
4111 $last = $split_name['last'];
4113 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4114 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4115 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4116 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4122 if ($searchable === 'true') {
4125 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4126 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4130 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4133 $about = $profile['about'];
4134 $about = strip_tags(BBCode::convert($about));
4136 $location = Profile::formatLocation($profile);
4138 if ($profile['pub_keywords']) {
4139 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4140 $kw = str_replace(' ', ' ', $kw);
4141 $arr = explode(' ', $kw);
4143 for ($x = 0; $x < 5; $x ++) {
4144 if (!empty($arr[$x])) {
4145 $tags .= '#'. trim($arr[$x]) .' ';
4150 $tags = trim($tags);
4153 return ["author" => $handle,
4154 "first_name" => $first,
4155 "last_name" => $last,
4156 "image_url" => $large,
4157 "image_url_medium" => $medium,
4158 "image_url_small" => $small,
4160 "gender" => $profile['gender'],
4162 "location" => $location,
4163 "searchable" => $searchable,
4165 "tag_string" => $tags];
4169 * @brief Sends profile data
4171 * @param int $uid The user id
4172 * @param bool $recips optional, default false
4174 * @throws \Exception
4176 public static function sendProfile($uid, $recips = false)
4182 $owner = User::getOwnerDataById($uid);
4189 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4190 AND `uid` = %d AND `rel` != %d",
4191 DBA::escape(Protocol::DIASPORA),
4193 intval(Contact::SHARING)
4201 $message = self::createProfileData($uid);
4203 // @ToDo Split this into single worker jobs
4204 foreach ($recips as $recip) {
4205 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4206 self::buildAndTransmit($owner, $recip, "profile", $message);
4211 * @brief Creates the signature for likes that are created on our system
4213 * @param integer $uid The user of that comment
4214 * @param array $item Item array
4216 * @return array Signed content
4217 * @throws \Exception
4219 public static function createLikeSignature($uid, array $item)
4221 $owner = User::getOwnerDataById($uid);
4222 if (empty($owner)) {
4223 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4227 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4231 $message = self::constructLike($item, $owner);
4232 if ($message === false) {
4236 $message["author_signature"] = self::signature($owner, $message);
4242 * @brief Creates the signature for Comments that are created on our system
4244 * @param integer $uid The user of that comment
4245 * @param array $item Item array
4247 * @return array Signed content
4248 * @throws \Exception
4250 public static function createCommentSignature($uid, array $item)
4252 $owner = User::getOwnerDataById($uid);
4253 if (empty($owner)) {
4254 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4258 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4259 $item['thr-parent'] = $item['parent-uri'];
4261 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4262 if (!DBA::isResult($parent)) {
4266 $item['parent-uri'] = $parent['parent-uri'];
4268 $message = self::constructComment($item, $owner);
4269 if ($message === false) {
4273 $message["author_signature"] = self::signature($owner, $message);