3 * @file src/Protocol/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "validPosting" and interpret only the new protocol.
11 namespace Friendica\Protocol;
13 use Friendica\Content\Feature;
14 use Friendica\Content\Text\BBCode;
15 use Friendica\Content\Text\Markdown;
16 use Friendica\Core\Cache;
17 use Friendica\Core\Config;
18 use Friendica\Core\L10n;
19 use Friendica\Core\Logger;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Conversation;
27 use Friendica\Model\GContact;
28 use Friendica\Model\Group;
29 use Friendica\Model\Item;
30 use Friendica\Model\Mail;
31 use Friendica\Model\Profile;
32 use Friendica\Model\User;
33 use Friendica\Network\Probe;
34 use Friendica\Util\Crypto;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Map;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
39 use Friendica\Util\XML;
40 use Friendica\Worker\Delivery;
44 * @brief This class contain functions to create and send Diaspora XML files
50 * @brief Return a list of relay servers
52 * The list contains not only the official relays but also servers that we serve directly
54 * @param integer $item_id The id of the item that is sent
55 * @param array $contacts The previously fetched contacts
57 * @return array of relay servers
58 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
60 public static function relayList($item_id, array $contacts = [])
64 // Fetching relay servers
65 $serverdata = Config::get("system", "relay_server");
67 if (!empty($serverdata)) {
68 $servers = explode(",", $serverdata);
69 foreach ($servers as $server) {
70 $serverlist[$server] = trim($server);
74 if (Config::get("system", "relay_directly", false)) {
75 // We distribute our stuff based on the parent to ensure that the thread will be complete
76 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
77 if (!DBA::isResult($parent)) {
81 // Servers that want to get all content
82 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
83 while ($server = DBA::fetch($servers)) {
84 $serverlist[$server['url']] = $server['url'];
87 // All tags of the current post
88 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
89 $tags = DBA::select('term', ['term'], $condition);
91 while ($tag = DBA::fetch($tags)) {
92 $taglist[] = $tag['term'];
95 // All servers who wants content with this tag
97 if (!empty($taglist)) {
98 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
99 while ($server = DBA::fetch($tagserver)) {
100 $tagserverlist[] = $server['gserver-id'];
104 // All adresses with the given id
105 if (!empty($tagserverlist)) {
106 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
107 while ($server = DBA::fetch($servers)) {
108 $serverlist[$server['url']] = $server['url'];
113 // Now we are collecting all relay contacts
114 foreach ($serverlist as $server_url) {
115 // We don't send messages to ourselves
116 if (Strings::compareLink($server_url, System::baseUrl())) {
119 $contact = self::getRelayContact($server_url);
120 if (is_bool($contact)) {
125 foreach ($contacts as $entry) {
126 if ($entry['batch'] == $contact['batch']) {
132 $contacts[] = $contact;
140 * @brief Return a contact for a given server address or creates a dummy entry
142 * @param string $server_url The url of the server
143 * @return array with the contact
146 private static function getRelayContact($server_url)
148 $fields = ['batch', 'id', 'name', 'network', 'protocol', 'archive', 'blocked'];
150 // Fetch the relay contact
151 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
152 'contact-type' => Contact::TYPE_RELAY];
153 $contact = DBA::selectFirst('contact', $fields, $condition);
155 if (DBA::isResult($contact)) {
156 if ($contact['archive'] || $contact['blocked']) {
161 self::setRelayContact($server_url);
163 $contact = DBA::selectFirst('contact', $fields, $condition);
164 if (DBA::isResult($contact)) {
169 // It should never happen that we arrive here
174 * @brief Update or insert a relay contact
176 * @param string $server_url The url of the server
177 * @param array $network_fields Optional network specific fields
180 public static function setRelayContact($server_url, array $network_fields = [])
182 $fields = ['created' => DateTimeFormat::utcNow(),
183 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url,
184 'nurl' => Strings::normaliseLink($server_url),
185 'network' => Protocol::DIASPORA, 'uid' => 0,
186 'batch' => $server_url . '/receive/public',
187 'rel' => Contact::FOLLOWER, 'blocked' => false,
188 'pending' => false, 'writable' => true,
189 'baseurl' => $server_url, 'contact-type' => Contact::TYPE_RELAY];
191 $fields = array_merge($fields, $network_fields);
193 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url)];
194 $relay = DBA::selectFirst('contact', ['id'], $condition);
195 if (DBA::isResult($relay)) {
196 unset($fields['created']);
197 $condition = ['id' => $relay['id']];
200 Logger::info('Set relay contact', ['fields' => $fields, 'condition' => $condition]);
202 DBA::update('contact', $fields, $condition, true);
206 * @brief Return a list of participating contacts for a thread
208 * This is used for the participation feature.
209 * One of the parameters is a contact array.
210 * This is done to avoid duplicates.
212 * @param integer $thread The id of the thread
213 * @param array $contacts The previously fetched contacts
215 * @return array of relay servers
218 public static function participantsForThread($thread, array $contacts)
220 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`, `contact`.`protocol`,
221 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
222 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
223 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
224 WHERE `participation`.`iid` = ?", $thread);
226 while ($contact = DBA::fetch($r)) {
227 if (!empty($contact['fnetwork'])) {
228 $contact['network'] = $contact['fnetwork'];
230 unset($contact['fnetwork']);
232 if (empty($contact['protocol'])) {
233 $contact['protocol'] = $contact['network'];
236 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
237 $contact['batch'] = $contact['fbatch'];
239 unset($contact['fbatch']);
242 foreach ($contacts as $entry) {
243 if ($entry['batch'] == $contact['batch']) {
249 $contacts[] = $contact;
258 * @brief repairs a signature that was double encoded
260 * The function is unused at the moment. It was copied from the old implementation.
262 * @param string $signature The signature
263 * @param string $handle The handle of the signature owner
264 * @param integer $level This value is only set inside this function to avoid endless loops
266 * @return string the repaired signature
269 private static function repairSignature($signature, $handle = "", $level = 1)
271 if ($signature == "") {
275 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
276 $signature = base64_decode($signature);
277 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
279 // Do a recursive call to be able to fix even multiple levels
281 $signature = self::repairSignature($signature, $handle, ++$level);
289 * @brief verify the envelope and return the verified data
291 * @param string $envelope The magic envelope
293 * @return string verified data
294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
295 * @throws \ImagickException
297 private static function verifyMagicEnvelope($envelope)
299 $basedom = XML::parseString($envelope);
301 if (!is_object($basedom)) {
302 Logger::log("Envelope is no XML file");
306 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
308 if (sizeof($children) == 0) {
309 Logger::log("XML has no children");
315 $data = Strings::base64UrlDecode($children->data);
316 $type = $children->data->attributes()->type[0];
318 $encoding = $children->encoding;
320 $alg = $children->alg;
322 $sig = Strings::base64UrlDecode($children->sig);
323 $key_id = $children->sig->attributes()->key_id[0];
325 $handle = Strings::base64UrlDecode($key_id);
328 $b64url_data = Strings::base64UrlEncode($data);
329 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
331 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
334 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
338 $key = self::key($handle);
340 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
344 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
346 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
354 * @brief encrypts data via AES
356 * @param string $key The AES key
357 * @param string $iv The IV (is used for CBC encoding)
358 * @param string $data The data that is to be encrypted
360 * @return string encrypted data
362 private static function aesEncrypt($key, $iv, $data)
364 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
368 * @brief decrypts data via AES
370 * @param string $key The AES key
371 * @param string $iv The IV (is used for CBC encoding)
372 * @param string $encrypted The encrypted data
374 * @return string decrypted data
376 private static function aesDecrypt($key, $iv, $encrypted)
378 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
382 * @brief: Decodes incoming Diaspora message in the new format
384 * @param array $importer Array of the importer user
385 * @param string $raw raw post message
386 * @param boolean $no_exit Don't do an http exit on error
389 * 'message' -> decoded Diaspora XML message
390 * 'author' -> author diaspora handle
391 * 'key' -> author public key (converted to pkcs#8)
392 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
393 * @throws \ImagickException
395 public static function decodeRaw(array $importer, $raw, $no_exit = false)
397 $data = json_decode($raw);
399 // Is it a private post? Then decrypt the outer Salmon
400 if (is_object($data)) {
401 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
402 $ciphertext = base64_decode($data->encrypted_magic_envelope);
404 $outer_key_bundle = '';
405 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
406 $j_outer_key_bundle = json_decode($outer_key_bundle);
408 if (!is_object($j_outer_key_bundle)) {
409 Logger::log('Outer Salmon did not verify. Discarding.');
413 throw new \Friendica\Network\HTTPException\BadRequestException();
417 $outer_iv = base64_decode($j_outer_key_bundle->iv);
418 $outer_key = base64_decode($j_outer_key_bundle->key);
420 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
425 $basedom = XML::parseString($xml);
427 if (!is_object($basedom)) {
428 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
432 throw new \Friendica\Network\HTTPException\BadRequestException();
436 $base = $basedom->children(NAMESPACE_SALMON_ME);
438 // Not sure if this cleaning is needed
439 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
441 // Build the signed data
442 $type = $base->data[0]->attributes()->type[0];
443 $encoding = $base->encoding;
445 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
447 // This is the signature
448 $signature = Strings::base64UrlDecode($base->sig);
450 // Get the senders' public key
451 $key_id = $base->sig[0]->attributes()->key_id[0];
452 $author_addr = base64_decode($key_id);
453 if ($author_addr == '') {
454 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
458 throw new \Friendica\Network\HTTPException\BadRequestException();
462 $key = self::key($author_addr);
464 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
468 throw new \Friendica\Network\HTTPException\BadRequestException();
472 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
474 Logger::log('Message did not verify. Discarding.');
478 throw new \Friendica\Network\HTTPException\BadRequestException();
482 return ['message' => (string)Strings::base64UrlDecode($base->data),
483 'author' => XML::unescape($author_addr),
484 'key' => (string)$key];
488 * @brief: Decodes incoming Diaspora message in the deprecated format
490 * @param array $importer Array of the importer user
491 * @param string $xml urldecoded Diaspora salmon
494 * 'message' -> decoded Diaspora XML message
495 * 'author' -> author diaspora handle
496 * 'key' -> author public key (converted to pkcs#8)
497 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
498 * @throws \ImagickException
500 public static function decode(array $importer, $xml)
503 $basedom = XML::parseString($xml);
505 if (!is_object($basedom)) {
506 Logger::log("XML is not parseable.");
509 $children = $basedom->children('https://joindiaspora.com/protocol');
511 $inner_aes_key = null;
514 if ($children->header) {
516 $author_link = str_replace('acct:', '', $children->header->author_id);
518 // This happens with posts from a relais
520 Logger::log("This is no private post in the old format", Logger::DEBUG);
524 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
526 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
527 $ciphertext = base64_decode($encrypted_header->ciphertext);
529 $outer_key_bundle = '';
530 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
532 $j_outer_key_bundle = json_decode($outer_key_bundle);
534 $outer_iv = base64_decode($j_outer_key_bundle->iv);
535 $outer_key = base64_decode($j_outer_key_bundle->key);
537 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
539 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
540 $idom = XML::parseString($decrypted);
542 $inner_iv = base64_decode($idom->iv);
543 $inner_aes_key = base64_decode($idom->aes_key);
545 $author_link = str_replace('acct:', '', $idom->author_id);
548 $dom = $basedom->children(NAMESPACE_SALMON_ME);
550 // figure out where in the DOM tree our data is hiding
553 if ($dom->provenance->data) {
554 $base = $dom->provenance;
555 } elseif ($dom->env->data) {
557 } elseif ($dom->data) {
562 Logger::log('unable to locate salmon data in xml');
563 throw new \Friendica\Network\HTTPException\BadRequestException();
567 // Stash the signature away for now. We have to find their key or it won't be good for anything.
568 $signature = Strings::base64UrlDecode($base->sig);
572 // strip whitespace so our data element will return to one big base64 blob
573 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
576 // stash away some other stuff for later
578 $type = $base->data[0]->attributes()->type[0];
579 $keyhash = $base->sig[0]->attributes()->keyhash[0];
580 $encoding = $base->encoding;
584 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
588 $data = Strings::base64UrlDecode($data);
592 $inner_decrypted = $data;
594 // Decode the encrypted blob
595 $inner_encrypted = base64_decode($data);
596 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
600 Logger::log('Could not retrieve author URI.');
601 throw new \Friendica\Network\HTTPException\BadRequestException();
603 // Once we have the author URI, go to the web and try to find their public key
604 // (first this will look it up locally if it is in the fcontact cache)
605 // This will also convert diaspora public key from pkcs#1 to pkcs#8
607 Logger::log('Fetching key for '.$author_link);
608 $key = self::key($author_link);
611 Logger::log('Could not retrieve author key.');
612 throw new \Friendica\Network\HTTPException\BadRequestException();
615 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
618 Logger::log('Message did not verify. Discarding.');
619 throw new \Friendica\Network\HTTPException\BadRequestException();
622 Logger::log('Message verified.');
624 return ['message' => (string)$inner_decrypted,
625 'author' => XML::unescape($author_link),
626 'key' => (string)$key];
631 * @brief Dispatches public messages and find the fitting receivers
633 * @param array $msg The post that will be dispatched
635 * @return int The message id of the generated message, "true" or "false" if there was an error
636 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637 * @throws \ImagickException
639 public static function dispatchPublic($msg)
641 $enabled = intval(Config::get("system", "diaspora_enabled"));
643 Logger::log("diaspora is disabled");
647 if (!($fields = self::validPosting($msg))) {
648 Logger::log("Invalid posting");
652 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
653 $success = self::dispatch($importer, $msg, $fields);
659 * @brief Dispatches the different message types to the different functions
661 * @param array $importer Array of the importer user
662 * @param array $msg The post that will be dispatched
663 * @param SimpleXMLElement $fields SimpleXML object that contains the message
665 * @return int The message id of the generated message, "true" or "false" if there was an error
666 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
667 * @throws \ImagickException
669 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
671 // The sender is the handle of the contact that sent the message.
672 // This will often be different with relayed messages (for example "like" and "comment")
673 $sender = $msg["author"];
675 // This is only needed for private postings since this is already done for public ones before
676 if (is_null($fields)) {
678 if (!($fields = self::validPosting($msg))) {
679 Logger::log("Invalid posting");
686 $type = $fields->getName();
688 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
691 case "account_migration":
693 Logger::log('Message with type ' . $type . ' is not private, quitting.');
696 return self::receiveAccountMigration($importer, $fields);
698 case "account_deletion":
699 return self::receiveAccountDeletion($fields);
702 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
706 Logger::log('Message with type ' . $type . ' is not private, quitting.');
709 return self::receiveContactRequest($importer, $fields);
713 Logger::log('Message with type ' . $type . ' is not private, quitting.');
716 return self::receiveConversation($importer, $msg, $fields);
719 return self::receiveLike($importer, $sender, $fields);
723 Logger::log('Message with type ' . $type . ' is not private, quitting.');
726 return self::receiveMessage($importer, $fields);
728 case "participation":
730 Logger::log('Message with type ' . $type . ' is not private, quitting.');
733 return self::receiveParticipation($importer, $fields);
735 case "photo": // Not implemented
736 return self::receivePhoto($importer, $fields);
738 case "poll_participation": // Not implemented
739 return self::receivePollParticipation($importer, $fields);
743 Logger::log('Message with type ' . $type . ' is not private, quitting.');
746 return self::receiveProfile($importer, $fields);
749 return self::receiveReshare($importer, $fields, $msg["message"]);
752 return self::receiveRetraction($importer, $sender, $fields);
754 case "status_message":
755 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
758 Logger::log("Unknown message type ".$type);
764 * @brief Checks if a posting is valid and fetches the data fields.
766 * This function does not only check the signature.
767 * It also does the conversion between the old and the new diaspora format.
769 * @param array $msg Array with the XML, the sender handle and the sender signature
771 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
772 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
773 * @throws \ImagickException
775 private static function validPosting($msg)
777 $data = XML::parseString($msg["message"]);
779 if (!is_object($data)) {
780 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
784 // Is this the new or the old version?
785 if ($data->getName() == "XML") {
787 foreach ($data->post->children() as $child) {
795 $type = $element->getName();
798 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
800 // All retractions are handled identically from now on.
801 // In the new version there will only be "retraction".
802 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
803 $type = "retraction";
805 if ($type == "request") {
809 $fields = new SimpleXMLElement("<".$type."/>");
812 $author_signature = null;
813 $parent_author_signature = null;
815 foreach ($element->children() as $fieldname => $entry) {
817 // Translation for the old XML structure
818 if ($fieldname == "diaspora_handle") {
819 $fieldname = "author";
821 if ($fieldname == "participant_handles") {
822 $fieldname = "participants";
824 if (in_array($type, ["like", "participation"])) {
825 if ($fieldname == "target_type") {
826 $fieldname = "parent_type";
829 if ($fieldname == "sender_handle") {
830 $fieldname = "author";
832 if ($fieldname == "recipient_handle") {
833 $fieldname = "recipient";
835 if ($fieldname == "root_diaspora_id") {
836 $fieldname = "root_author";
838 if ($type == "status_message") {
839 if ($fieldname == "raw_message") {
843 if ($type == "retraction") {
844 if ($fieldname == "post_guid") {
845 $fieldname = "target_guid";
847 if ($fieldname == "type") {
848 $fieldname = "target_type";
853 if (($fieldname == "author_signature") && ($entry != "")) {
854 $author_signature = base64_decode($entry);
855 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
856 $parent_author_signature = base64_decode($entry);
857 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
858 if ($signed_data != "") {
862 $signed_data .= $entry;
864 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
865 || ($orig_type == "relayable_retraction")
867 XML::copy($entry, $fields, $fieldname);
871 // This is something that shouldn't happen at all.
872 if (in_array($type, ["status_message", "reshare", "profile"])) {
873 if ($msg["author"] != $fields->author) {
874 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
879 // Only some message types have signatures. So we quit here for the other types.
880 if (!in_array($type, ["comment", "like"])) {
883 // No author_signature? This is a must, so we quit.
884 if (!isset($author_signature)) {
885 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
889 if (isset($parent_author_signature)) {
890 $key = self::key($msg["author"]);
892 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
896 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
897 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);
902 $key = self::key($fields->author);
904 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
908 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
909 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);
917 * @brief Fetches the public key for a given handle
919 * @param string $handle The handle
921 * @return string The public key
922 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
923 * @throws \ImagickException
925 private static function key($handle)
927 $handle = strval($handle);
929 Logger::log("Fetching diaspora key for: ".$handle);
931 $r = self::personByHandle($handle);
940 * @brief Fetches data for a given handle
942 * @param string $handle The handle
944 * @return array the queried data
945 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
946 * @throws \ImagickException
948 public static function personByHandle($handle)
952 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
953 if (DBA::isResult($person)) {
954 Logger::debug("In cache " . print_r($person, true));
956 // update record occasionally so it doesn't get stale
957 $d = strtotime($person["updated"]." +00:00");
958 if ($d < strtotime("now - 14 days")) {
962 if ($person["guid"] == "") {
967 if (!DBA::isResult($person) || $update) {
968 Logger::log("create or refresh", Logger::DEBUG);
969 $r = Probe::uri($handle, Protocol::DIASPORA);
971 // Note that Friendica contacts will return a "Diaspora person"
972 // if Diaspora connectivity is enabled on their server
973 if ($r && ($r["network"] === Protocol::DIASPORA)) {
974 self::updateFContact($r);
976 // Fetch the updated or added contact
977 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
978 if (!DBA::isResult($person)) {
989 * @brief Updates the fcontact table
991 * @param array $arr The fcontact data
994 private static function updateFContact($arr)
996 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
997 'request' => $arr["request"], 'nick' => $arr["nick"],
998 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
999 'batch' => $arr["batch"], 'notify' => $arr["notify"],
1000 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
1001 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
1002 'updated' => DateTimeFormat::utcNow()];
1004 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1006 DBA::update('fcontact', $fields, $condition, true);
1010 * @brief get a handle (user@domain.tld) from a given contact id
1012 * @param int $contact_id The id in the contact table
1013 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1015 * @return string the handle
1016 * @throws \Exception
1018 private static function handleFromContact($contact_id, $pcontact_id = 0)
1022 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1024 if ($pcontact_id != 0) {
1025 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1027 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1028 return strtolower($contact["addr"]);
1033 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1037 if (DBA::isResult($r)) {
1040 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1042 if ($contact['addr'] != "") {
1043 $handle = $contact['addr'];
1045 $baseurl_start = strpos($contact['url'], '://') + 3;
1046 // allows installations in a subdirectory--not sure how Diaspora will handle
1047 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1048 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1049 $handle = $contact['nick'].'@'.$baseurl;
1053 return strtolower($handle);
1057 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1060 * @param mixed $fcontact_guid Hexadecimal string guid
1062 * @return string the contact url or null
1063 * @throws \Exception
1065 public static function urlFromContactGuid($fcontact_guid)
1067 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1070 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1071 DBA::escape(Protocol::DIASPORA),
1072 DBA::escape($fcontact_guid)
1075 if (DBA::isResult($r)) {
1076 return $r[0]['url'];
1083 * @brief Get a contact id for a given handle
1085 * @todo Move to Friendica\Model\Contact
1087 * @param int $uid The user id
1088 * @param string $handle The handle in the format user@domain.tld
1090 * @return array Contact data
1091 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1092 * @throws \ImagickException
1094 private static function contactByHandle($uid, $handle)
1096 $cid = Contact::getIdForURL($handle, $uid);
1098 $handle_parts = explode("@", $handle);
1099 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1100 $cid = Contact::getIdForURL($nurl_sql, $uid);
1104 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1108 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1109 if (!DBA::isResult($contact)) {
1110 // This here shouldn't happen at all
1111 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1119 * @brief Check if posting is allowed for this contact
1121 * @param array $importer Array of the importer user
1122 * @param array $contact The contact that is checked
1123 * @param bool $is_comment Is the check for a comment?
1125 * @return bool is the contact allowed to post?
1127 private static function postAllow(array $importer, array $contact, $is_comment = false)
1130 * Perhaps we were already sharing with this person. Now they're sharing with us.
1131 * That makes us friends.
1132 * Normally this should have handled by getting a request - but this could get lost
1134 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1135 // It is not removed by now. Possibly the code is needed?
1136 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1139 // array('rel' => Contact::FRIEND, 'writable' => true),
1140 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1143 // $contact["rel"] = Contact::FRIEND;
1144 // Logger::log("defining user ".$contact["nick"]." as friend");
1147 // Contact server is blocked
1148 if (Network::isUrlBlocked($contact['url'])) {
1150 // We don't seem to like that person
1151 } elseif ($contact["blocked"]) {
1152 // Maybe blocked, don't accept.
1154 // We are following this person?
1155 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1156 // Yes, then it is fine.
1158 // Is it a post to a community?
1159 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1162 // Is the message a global user or a comment?
1163 } elseif (($importer["uid"] == 0) || $is_comment) {
1164 // Messages for the global users and comments are always accepted
1172 * @brief Fetches the contact id for a handle and checks if posting is allowed
1174 * @param array $importer Array of the importer user
1175 * @param string $handle The checked handle in the format user@domain.tld
1176 * @param bool $is_comment Is the check for a comment?
1178 * @return array The contact data
1179 * @throws \Exception
1181 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1183 $contact = self::contactByHandle($importer["uid"], $handle);
1185 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1186 // If a contact isn't found, we accept it anyway if it is a comment
1187 if ($is_comment && ($importer["uid"] != 0)) {
1188 return self::contactByHandle(0, $handle);
1189 } elseif ($is_comment) {
1196 if (!self::postAllow($importer, $contact, $is_comment)) {
1197 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1204 * @brief Does the message already exists on the system?
1206 * @param int $uid The user id
1207 * @param string $guid The guid of the message
1209 * @return int|bool message id if the message already was stored into the system - or false.
1210 * @throws \Exception
1212 private static function messageExists($uid, $guid)
1214 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1215 if (DBA::isResult($item)) {
1216 Logger::log("message ".$guid." already exists for user ".$uid);
1224 * @brief Checks for links to posts in a message
1226 * @param array $item The item array
1229 private static function fetchGuid(array $item)
1231 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1232 preg_replace_callback(
1234 function ($match) use ($item) {
1235 self::fetchGuidSub($match, $item);
1240 preg_replace_callback(
1241 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1242 function ($match) use ($item) {
1243 self::fetchGuidSub($match, $item);
1250 * @brief Checks for relative /people/* links in an item body to match local
1251 * contacts or prepends the remote host taken from the author link.
1253 * @param string $body The item body to replace links from
1254 * @param string $author_link The author link for missing local contact fallback
1256 * @return string the replaced string
1258 public static function replacePeopleGuid($body, $author_link)
1260 $return = preg_replace_callback(
1261 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1262 function ($match) use ($author_link) {
1264 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1265 // 1 => '0123456789abcdef'
1267 $handle = self::urlFromContactGuid($match[1]);
1270 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1272 // No local match, restoring absolute remote URL from author scheme and host
1273 $author_url = parse_url($author_link);
1274 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1286 * @brief sub function of "fetchGuid" which checks for links in messages
1288 * @param array $match array containing a link that has to be checked for a message link
1289 * @param array $item The item array
1291 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1292 * @throws \ImagickException
1294 private static function fetchGuidSub($match, $item)
1296 if (!self::storeByGuid($match[1], $item["author-link"])) {
1297 self::storeByGuid($match[1], $item["owner-link"]);
1302 * @brief Fetches an item with a given guid from a given server
1304 * @param string $guid the message guid
1305 * @param string $server The server address
1306 * @param int $uid The user id of the user
1308 * @return int the message id of the stored message or false
1309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1310 * @throws \ImagickException
1312 private static function storeByGuid($guid, $server, $uid = 0)
1314 $serverparts = parse_url($server);
1316 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1320 $server = $serverparts["scheme"]."://".$serverparts["host"];
1322 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1324 $msg = self::message($guid, $server);
1330 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1332 // Now call the dispatcher
1333 return self::dispatchPublic($msg);
1337 * @brief Fetches a message from a server
1339 * @param string $guid message guid
1340 * @param string $server The url of the server
1341 * @param int $level Endless loop prevention
1344 * 'message' => The message XML
1345 * 'author' => The author handle
1346 * 'key' => The public key of the author
1347 * @throws \Exception
1349 private static function message($guid, $server, $level = 0)
1355 // This will work for new Diaspora servers and Friendica servers from 3.5
1356 $source_url = $server."/fetch/post/".urlencode($guid);
1358 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1360 $envelope = Network::fetchUrl($source_url);
1362 Logger::log("Envelope was fetched.", Logger::DEBUG);
1363 $x = self::verifyMagicEnvelope($envelope);
1365 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1367 Logger::log("Envelope was verified.", Logger::DEBUG);
1377 $source_xml = XML::parseString($x);
1379 if (!is_object($source_xml)) {
1383 if ($source_xml->post->reshare) {
1384 // Reshare of a reshare - old Diaspora version
1385 Logger::log("Message is a reshare", Logger::DEBUG);
1386 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1387 } elseif ($source_xml->getName() == "reshare") {
1388 // Reshare of a reshare - new Diaspora version
1389 Logger::log("Message is a new reshare", Logger::DEBUG);
1390 return self::message($source_xml->root_guid, $server, ++$level);
1395 // Fetch the author - for the old and the new Diaspora version
1396 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1397 $author = (string)$source_xml->post->status_message->diaspora_handle;
1398 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1399 $author = (string)$source_xml->author;
1402 // If this isn't a "status_message" then quit
1404 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1408 $msg = ["message" => $x, "author" => $author];
1410 $msg["key"] = self::key($msg["author"]);
1416 * @brief Fetches the item record of a given guid
1418 * @param int $uid The user id
1419 * @param string $guid message guid
1420 * @param string $author The handle of the item
1421 * @param array $contact The contact of the item owner
1423 * @return array the item record
1424 * @throws \Exception
1426 private static function parentItem($uid, $guid, $author, array $contact)
1428 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1429 'author-name', 'author-link', 'author-avatar',
1430 'owner-name', 'owner-link', 'owner-avatar'];
1431 $condition = ['uid' => $uid, 'guid' => $guid];
1432 $item = Item::selectFirst($fields, $condition);
1434 if (!DBA::isResult($item)) {
1435 $person = self::personByHandle($author);
1436 $result = self::storeByGuid($guid, $person["url"], $uid);
1438 // We don't have an url for items that arrived at the public dispatcher
1439 if (!$result && !empty($contact["url"])) {
1440 $result = self::storeByGuid($guid, $contact["url"], $uid);
1444 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1446 $item = Item::selectFirst($fields, $condition);
1450 if (!DBA::isResult($item)) {
1451 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1454 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1460 * @brief returns contact details
1462 * @param array $def_contact The default contact if the person isn't found
1463 * @param array $person The record of the person
1464 * @param int $uid The user id
1467 * 'cid' => contact id
1468 * 'network' => network type
1469 * @throws \Exception
1471 private static function authorContactByUrl($def_contact, $person, $uid)
1473 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1474 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1475 if (DBA::isResult($contact)) {
1476 $cid = $contact["id"];
1477 $network = $contact["network"];
1479 $cid = $def_contact["id"];
1480 $network = Protocol::DIASPORA;
1483 return ["cid" => $cid, "network" => $network];
1487 * @brief Is the profile a hubzilla profile?
1489 * @param string $url The profile link
1491 * @return bool is it a hubzilla server?
1493 public static function isRedmatrix($url)
1495 return(strstr($url, "/channel/"));
1499 * @brief Generate a post link with a given handle and message guid
1501 * @param string $addr The user handle
1502 * @param string $guid message guid
1503 * @param string $parent_guid optional parent guid
1505 * @return string the post link
1506 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1507 * @throws \ImagickException
1509 private static function plink($addr, $guid, $parent_guid = '')
1511 $contact = Contact::getDetailsByAddr($addr);
1515 if ($parent_guid != '') {
1516 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1518 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1522 if ($contact["network"] == Protocol::DFRN) {
1523 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1526 if (self::isRedmatrix($contact["url"])) {
1527 return $contact["url"] . "/?f=&mid=" . $guid;
1530 if ($parent_guid != '') {
1531 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1533 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1538 * @brief Receives account migration
1540 * @param array $importer Array of the importer user
1541 * @param object $data The message object
1543 * @return bool Success
1544 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1545 * @throws \ImagickException
1547 private static function receiveAccountMigration(array $importer, $data)
1549 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1550 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1551 $signature = Strings::escapeTags(XML::unescape($data->signature));
1553 $contact = self::contactByHandle($importer["uid"], $old_handle);
1555 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1559 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1562 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1563 $key = self::key($old_handle);
1564 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1565 Logger::log('No valid signature for migration.');
1569 // Update the profile
1570 self::receiveProfile($importer, $data->profile);
1572 // change the technical stuff in contact and gcontact
1573 $data = Probe::uri($new_handle);
1574 if ($data['network'] == Protocol::PHANTOM) {
1575 Logger::log('Account for '.$new_handle." couldn't be probed.");
1579 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1580 'name' => $data['name'], 'nick' => $data['nick'],
1581 'addr' => $data['addr'], 'batch' => $data['batch'],
1582 'notify' => $data['notify'], 'poll' => $data['poll'],
1583 'network' => $data['network']];
1585 DBA::update('contact', $fields, ['addr' => $old_handle]);
1587 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1588 'name' => $data['name'], 'nick' => $data['nick'],
1589 'addr' => $data['addr'], 'connect' => $data['addr'],
1590 'notify' => $data['notify'], 'photo' => $data['photo'],
1591 'server_url' => $data['baseurl'], 'network' => $data['network']];
1593 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1595 Logger::log('Contacts are updated.');
1601 * @brief Processes an account deletion
1603 * @param object $data The message object
1605 * @return bool Success
1606 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1608 private static function receiveAccountDeletion($data)
1610 $author = Strings::escapeTags(XML::unescape($data->author));
1612 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1613 while ($contact = DBA::fetch($contacts)) {
1614 Contact::remove($contact["id"]);
1617 DBA::delete('gcontact', ['addr' => $author]);
1619 Logger::log('Removed contacts for ' . $author);
1625 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1627 * @param string $author Author handle
1628 * @param string $guid Message guid
1629 * @param boolean $onlyfound Only return uri when found in the database
1631 * @return string The constructed uri or the one from our database
1632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1633 * @throws \ImagickException
1635 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1637 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1638 if (DBA::isResult($item)) {
1639 return $item["uri"];
1640 } elseif (!$onlyfound) {
1641 $person = self::personByHandle($author);
1643 $parts = parse_url($person['url']);
1644 unset($parts['path']);
1645 $host_url = Network::unparseURL($parts);
1647 return $host_url . '/objects/' . $guid;
1654 * @brief Fetch the guid from our database with a given uri
1656 * @param string $uri Message uri
1657 * @param string $uid Author handle
1659 * @return string The post guid
1660 * @throws \Exception
1662 private static function getGuidFromUri($uri, $uid)
1664 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1665 if (DBA::isResult($item)) {
1666 return $item["guid"];
1673 * @brief Find the best importer for a comment, like, ...
1675 * @param string $guid The guid of the item
1677 * @return array|boolean the origin owner of that post - or false
1678 * @throws \Exception
1680 private static function importerForGuid($guid)
1682 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1683 if (DBA::isResult($item)) {
1684 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1685 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1686 if (DBA::isResult($contact)) {
1694 * @brief Processes an incoming comment
1696 * @param array $importer Array of the importer user
1697 * @param string $sender The sender of the message
1698 * @param object $data The message object
1699 * @param string $xml The original XML of the message
1701 * @return int The message id of the generated comment or "false" if there was an error
1702 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1703 * @throws \ImagickException
1705 private static function receiveComment(array $importer, $sender, $data, $xml)
1707 $author = Strings::escapeTags(XML::unescape($data->author));
1708 $guid = Strings::escapeTags(XML::unescape($data->guid));
1709 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1710 $text = XML::unescape($data->text);
1712 if (isset($data->created_at)) {
1713 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1715 $created_at = DateTimeFormat::utcNow();
1718 if (isset($data->thread_parent_guid)) {
1719 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1720 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1725 $contact = self::allowedContactByHandle($importer, $sender, true);
1730 $message_id = self::messageExists($importer["uid"], $guid);
1735 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1736 if (!$parent_item) {
1740 $person = self::personByHandle($author);
1741 if (!is_array($person)) {
1742 Logger::log("unable to find author details");
1746 // Fetch the contact id - if we know this contact
1747 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1751 $datarray["uid"] = $importer["uid"];
1752 $datarray["contact-id"] = $author_contact["cid"];
1753 $datarray["network"] = $author_contact["network"];
1755 $datarray["author-link"] = $person["url"];
1756 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1758 $datarray["owner-link"] = $contact["url"];
1759 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1761 $datarray["guid"] = $guid;
1762 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1764 $datarray["verb"] = ACTIVITY_POST;
1765 $datarray["gravity"] = GRAVITY_COMMENT;
1767 if ($thr_uri != "") {
1768 $datarray["parent-uri"] = $thr_uri;
1770 $datarray["parent-uri"] = $parent_item["uri"];
1773 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1775 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1776 $datarray["source"] = $xml;
1778 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1780 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1782 $body = Markdown::toBBCode($text);
1784 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1786 self::fetchGuid($datarray);
1788 // If we are the origin of the parent we store the original data.
1789 // We notify our followers during the item storage.
1790 if ($parent_item["origin"]) {
1791 $datarray['diaspora_signed_text'] = json_encode($data);
1794 $message_id = Item::insert($datarray);
1796 if ($message_id <= 0) {
1801 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1802 if ($datarray['uid'] == 0) {
1803 Item::distribute($message_id, json_encode($data));
1811 * @brief processes and stores private messages
1813 * @param array $importer Array of the importer user
1814 * @param array $contact The contact of the message
1815 * @param object $data The message object
1816 * @param array $msg Array of the processed message, author handle and key
1817 * @param object $mesg The private message
1818 * @param array $conversation The conversation record to which this message belongs
1820 * @return bool "true" if it was successful
1821 * @throws \Exception
1823 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1825 $author = Strings::escapeTags(XML::unescape($data->author));
1826 $guid = Strings::escapeTags(XML::unescape($data->guid));
1827 $subject = Strings::escapeTags(XML::unescape($data->subject));
1829 // "diaspora_handle" is the element name from the old version
1830 // "author" is the element name from the new version
1831 if ($mesg->author) {
1832 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1833 } elseif ($mesg->diaspora_handle) {
1834 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1839 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1840 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1841 $msg_text = XML::unescape($mesg->text);
1842 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1844 if ($msg_conversation_guid != $guid) {
1845 Logger::log("message conversation guid does not belong to the current conversation.");
1849 $body = Markdown::toBBCode($msg_text);
1850 $message_uri = $msg_author.":".$msg_guid;
1852 $person = self::personByHandle($msg_author);
1854 return Mail::insert([
1855 'uid' => $importer['uid'],
1856 'guid' => $msg_guid,
1857 'convid' => $conversation['id'],
1858 'from-name' => $person['name'],
1859 'from-photo' => $person['photo'],
1860 'from-url' => $person['url'],
1861 'contact-id' => $contact['id'],
1862 'title' => $subject,
1864 'uri' => $message_uri,
1865 'parent-uri' => $author . ':' . $guid,
1866 'created' => $msg_created_at
1871 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1873 * @param array $importer Array of the importer user
1874 * @param array $msg Array of the processed message, author handle and key
1875 * @param object $data The message object
1877 * @return bool Success
1878 * @throws \Exception
1880 private static function receiveConversation(array $importer, $msg, $data)
1882 $author = Strings::escapeTags(XML::unescape($data->author));
1883 $guid = Strings::escapeTags(XML::unescape($data->guid));
1884 $subject = Strings::escapeTags(XML::unescape($data->subject));
1885 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1886 $participants = Strings::escapeTags(XML::unescape($data->participants));
1888 $messages = $data->message;
1890 if (!count($messages)) {
1891 Logger::log("empty conversation");
1895 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1900 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1901 if (!DBA::isResult($conversation)) {
1903 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1904 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1905 intval($importer["uid"]),
1907 DBA::escape($author),
1908 DBA::escape($created_at),
1909 DBA::escape(DateTimeFormat::utcNow()),
1910 DBA::escape($subject),
1911 DBA::escape($participants)
1914 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1917 if (!$conversation) {
1918 Logger::log("unable to create conversation.");
1922 foreach ($messages as $mesg) {
1923 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1930 * @brief Processes "like" messages
1932 * @param array $importer Array of the importer user
1933 * @param string $sender The sender of the message
1934 * @param object $data The message object
1936 * @return int The message id of the generated like or "false" if there was an error
1937 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1938 * @throws \ImagickException
1940 private static function receiveLike(array $importer, $sender, $data)
1942 $author = Strings::escapeTags(XML::unescape($data->author));
1943 $guid = Strings::escapeTags(XML::unescape($data->guid));
1944 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1945 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1946 $positive = Strings::escapeTags(XML::unescape($data->positive));
1948 // likes on comments aren't supported by Diaspora - only on posts
1949 // But maybe this will be supported in the future, so we will accept it.
1950 if (!in_array($parent_type, ["Post", "Comment"])) {
1954 $contact = self::allowedContactByHandle($importer, $sender, true);
1959 $message_id = self::messageExists($importer["uid"], $guid);
1964 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1965 if (!$parent_item) {
1969 $person = self::personByHandle($author);
1970 if (!is_array($person)) {
1971 Logger::log("unable to find author details");
1975 // Fetch the contact id - if we know this contact
1976 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1978 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1979 // We would accept this anyhow.
1980 if ($positive == "true") {
1981 $verb = ACTIVITY_LIKE;
1983 $verb = ACTIVITY_DISLIKE;
1988 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1990 $datarray["uid"] = $importer["uid"];
1991 $datarray["contact-id"] = $author_contact["cid"];
1992 $datarray["network"] = $author_contact["network"];
1994 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1995 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1997 $datarray["guid"] = $guid;
1998 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2000 $datarray["verb"] = $verb;
2001 $datarray["gravity"] = GRAVITY_ACTIVITY;
2002 $datarray["parent-uri"] = $parent_item["uri"];
2004 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2006 $datarray["body"] = $verb;
2008 // Diaspora doesn't provide a date for likes
2009 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2011 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2012 if ($parent_item["id"] != $parent_item["parent"]) {
2013 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2014 $origin = $toplevel["origin"];
2016 $origin = $parent_item["origin"];
2019 // If we are the origin of the parent we store the original data.
2020 // We notify our followers during the item storage.
2022 $datarray['diaspora_signed_text'] = json_encode($data);
2025 $message_id = Item::insert($datarray);
2027 if ($message_id <= 0) {
2032 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2033 if ($datarray['uid'] == 0) {
2034 Item::distribute($message_id, json_encode($data));
2042 * @brief Processes private messages
2044 * @param array $importer Array of the importer user
2045 * @param object $data The message object
2047 * @return bool Success?
2048 * @throws \Exception
2050 private static function receiveMessage(array $importer, $data)
2052 $author = Strings::escapeTags(XML::unescape($data->author));
2053 $guid = Strings::escapeTags(XML::unescape($data->guid));
2054 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2055 $text = XML::unescape($data->text);
2056 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2058 $contact = self::allowedContactByHandle($importer, $author, true);
2063 $conversation = null;
2065 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2066 $conversation = DBA::selectFirst('conv', [], $condition);
2068 if (!DBA::isResult($conversation)) {
2069 Logger::log("conversation not available.");
2073 $message_uri = $author.":".$guid;
2075 $person = self::personByHandle($author);
2077 Logger::log("unable to find author details");
2081 $body = Markdown::toBBCode($text);
2083 $body = self::replacePeopleGuid($body, $person["url"]);
2085 return Mail::insert([
2086 'uid' => $importer['uid'],
2088 'convid' => $conversation['id'],
2089 'from-name' => $person['name'],
2090 'from-photo' => $person['photo'],
2091 'from-url' => $person['url'],
2092 'contact-id' => $contact['id'],
2093 'title' => $conversation['subject'],
2096 'uri' => $message_uri,
2097 'parent-uri' => $author.":".$conversation['guid'],
2098 'created' => $created_at
2103 * @brief Processes participations - unsupported by now
2105 * @param array $importer Array of the importer user
2106 * @param object $data The message object
2108 * @return bool always true
2109 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2110 * @throws \ImagickException
2112 private static function receiveParticipation(array $importer, $data)
2114 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2115 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2117 $contact_id = Contact::getIdForURL($author);
2119 Logger::log('Contact not found: '.$author);
2123 $person = self::personByHandle($author);
2124 if (!is_array($person)) {
2125 Logger::log("Person not found: ".$author);
2129 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2130 if (!DBA::isResult($item)) {
2131 Logger::log('Item not found, no origin or private: '.$parent_guid);
2135 $author_parts = explode('@', $author);
2136 if (isset($author_parts[1])) {
2137 $server = $author_parts[1];
2139 // Should never happen
2143 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2145 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2146 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2149 // Send all existing comments and likes to the requesting server
2150 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2151 while ($comment = Item::fetch($comments)) {
2152 if ($comment['id'] == $comment['parent']) {
2156 Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $contact_id]);
2157 Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $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, 'keywords' => $keywords,
2266 'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2268 if (!empty($birthday)) {
2269 $fields['bd'] = $birthday;
2272 DBA::update('contact', $fields, ['id' => $contact['id']]);
2274 // @todo Update the public contact, then update the gcontact from that
2276 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2277 "photo" => $image_url, "name" => $name, "location" => $location,
2278 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2279 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2280 "hide" => !$searchable, "nsfw" => $nsfw];
2282 $gcid = GContact::update($gcontact);
2284 GContact::link($gcid, $importer["uid"], $contact["id"]);
2286 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2292 * @brief Processes incoming friend requests
2294 * @param array $importer Array of the importer user
2295 * @param array $contact The contact that send the request
2297 * @throws \Exception
2299 private static function receiveRequestMakeFriend(array $importer, array $contact)
2301 if ($contact["rel"] == Contact::SHARING) {
2304 ['rel' => Contact::FRIEND, 'writable' => true],
2305 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2311 * @brief Processes incoming sharing notification
2313 * @param array $importer Array of the importer user
2314 * @param object $data The message object
2316 * @return bool Success
2317 * @throws \Exception
2319 private static function receiveContactRequest(array $importer, $data)
2321 $author = XML::unescape($data->author);
2322 $recipient = XML::unescape($data->recipient);
2324 if (!$author || !$recipient) {
2328 // the current protocol version doesn't know these fields
2329 // That means that we will assume their existance
2330 if (isset($data->following)) {
2331 $following = (XML::unescape($data->following) == "true");
2336 if (isset($data->sharing)) {
2337 $sharing = (XML::unescape($data->sharing) == "true");
2342 $contact = self::contactByHandle($importer["uid"], $author);
2344 // perhaps we were already sharing with this person. Now they're sharing with us.
2345 // That makes us friends.
2348 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2349 self::receiveRequestMakeFriend($importer, $contact);
2351 // refetch the contact array
2352 $contact = self::contactByHandle($importer["uid"], $author);
2354 // If we are now friends, we are sending a share message.
2355 // Normally we needn't to do so, but the first message could have been vanished.
2356 if (in_array($contact["rel"], [Contact::FRIEND])) {
2357 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2358 if (DBA::isResult($user)) {
2359 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2360 self::sendShare($user, $contact);
2365 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2366 Contact::removeFollower($importer, $contact);
2371 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2372 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2374 } elseif (!$following && !$sharing) {
2375 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2377 } elseif (!$following && $sharing) {
2378 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2379 } elseif ($following && $sharing) {
2380 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2381 } elseif ($following && !$sharing) {
2382 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2385 $ret = self::personByHandle($author);
2387 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2388 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2392 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2395 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2396 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2397 intval($importer["uid"]),
2398 DBA::escape($ret["network"]),
2399 DBA::escape($ret["addr"]),
2400 DateTimeFormat::utcNow(),
2401 DBA::escape($ret["url"]),
2402 DBA::escape(Strings::normaliseLink($ret["url"])),
2403 DBA::escape($batch),
2404 DBA::escape($ret["name"]),
2405 DBA::escape($ret["nick"]),
2406 DBA::escape($ret["photo"]),
2407 DBA::escape($ret["pubkey"]),
2408 DBA::escape($ret["notify"]),
2409 DBA::escape($ret["poll"]),
2414 // find the contact record we just created
2416 $contact_record = self::contactByHandle($importer["uid"], $author);
2418 if (!$contact_record) {
2419 Logger::log("unable to locate newly created contact record.");
2423 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2425 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2427 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2429 if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
2430 Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2432 $hash = Strings::getRandomHex().(string)time(); // Generate a confirm_key
2435 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2436 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2437 intval($importer["uid"]),
2438 intval($contact_record["id"]),
2441 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2443 DBA::escape(DateTimeFormat::utcNow())
2446 // automatic friend approval
2448 Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2450 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2453 * technically they are sharing with us (Contact::SHARING),
2454 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2455 * we are going to change the relationship and make them a follower.
2457 if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
2458 $new_relation = Contact::FRIEND;
2459 } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
2460 $new_relation = Contact::SHARING;
2462 $new_relation = Contact::FOLLOWER;
2466 "UPDATE `contact` SET `rel` = %d,
2474 intval($new_relation),
2475 DBA::escape(DateTimeFormat::utcNow()),
2476 DBA::escape(DateTimeFormat::utcNow()),
2477 intval($contact_record["id"])
2480 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2481 if (DBA::isResult($user)) {
2482 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2483 self::sendShare($user, $contact_record);
2485 // Send the profile data, maybe it weren't transmitted before
2486 self::sendProfile($importer["uid"], [$contact_record]);
2494 * @brief Fetches a message with a given guid
2496 * @param string $guid message guid
2497 * @param string $orig_author handle of the original post
2498 * @return array The fetched item
2499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2500 * @throws \ImagickException
2502 public static function originalItem($guid, $orig_author)
2505 Logger::log('Empty guid. Quitting.');
2509 // Do we already have this item?
2510 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2511 'author-name', 'author-link', 'author-avatar'];
2512 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2513 $item = Item::selectFirst($fields, $condition);
2515 if (DBA::isResult($item)) {
2516 Logger::log("reshared message ".$guid." already exists on system.");
2518 // Maybe it is already a reshared item?
2519 // Then refetch the content, if it is a reshare from a reshare.
2520 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2521 if (self::isReshare($item["body"], true)) {
2523 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2524 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2526 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2528 // Add OEmbed and other information to the body
2529 $item["body"] = add_page_info_to_body($item["body"], false, true);
2537 if (!DBA::isResult($item)) {
2538 if (empty($orig_author)) {
2539 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2543 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2544 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2545 $stored = self::storeByGuid($guid, $server);
2548 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2549 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2550 $stored = self::storeByGuid($guid, $server);
2554 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2555 'author-name', 'author-link', 'author-avatar'];
2556 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2557 $item = Item::selectFirst($fields, $condition);
2559 if (DBA::isResult($item)) {
2560 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2561 if (self::isReshare($item["body"], false)) {
2562 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2563 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2574 * @brief Stores a reshare activity
2576 * @param array $item Array of reshare post
2577 * @param integer $parent_message_id Id of the parent post
2578 * @param string $guid GUID string of reshare action
2579 * @param string $author Author handle
2581 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2583 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2587 $datarray['uid'] = $item['uid'];
2588 $datarray['contact-id'] = $item['contact-id'];
2589 $datarray['network'] = $item['network'];
2591 $datarray['author-link'] = $item['author-link'];
2592 $datarray['author-id'] = $item['author-id'];
2594 $datarray['owner-link'] = $datarray['author-link'];
2595 $datarray['owner-id'] = $datarray['author-id'];
2597 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2598 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2599 $datarray['parent-uri'] = $parent['uri'];
2601 $datarray['verb'] = $datarray['body'] = ACTIVITY2_ANNOUNCE;
2602 $datarray['gravity'] = GRAVITY_ACTIVITY;
2603 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
2605 $datarray['protocol'] = $item['protocol'];
2607 $datarray['plink'] = self::plink($author, $datarray['guid']);
2608 $datarray['private'] = $item['private'];
2609 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2611 $message_id = Item::insert($datarray);
2614 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2615 if ($datarray['uid'] == 0) {
2616 Item::distribute($message_id);
2622 * @brief Processes a reshare message
2624 * @param array $importer Array of the importer user
2625 * @param object $data The message object
2626 * @param string $xml The original XML of the message
2628 * @return int the message id
2629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2630 * @throws \ImagickException
2632 private static function receiveReshare(array $importer, $data, $xml)
2634 $author = Strings::escapeTags(XML::unescape($data->author));
2635 $guid = Strings::escapeTags(XML::unescape($data->guid));
2636 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2637 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2638 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2639 /// @todo handle unprocessed property "provider_display_name"
2640 $public = Strings::escapeTags(XML::unescape($data->public));
2642 $contact = self::allowedContactByHandle($importer, $author, false);
2647 $message_id = self::messageExists($importer["uid"], $guid);
2652 $original_item = self::originalItem($root_guid, $root_author);
2653 if (!$original_item) {
2657 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2661 $datarray["uid"] = $importer["uid"];
2662 $datarray["contact-id"] = $contact["id"];
2663 $datarray["network"] = Protocol::DIASPORA;
2665 $datarray["author-link"] = $contact["url"];
2666 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2668 $datarray["owner-link"] = $datarray["author-link"];
2669 $datarray["owner-id"] = $datarray["author-id"];
2671 $datarray["guid"] = $guid;
2672 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2674 $datarray["verb"] = ACTIVITY_POST;
2675 $datarray["gravity"] = GRAVITY_PARENT;
2677 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2678 $datarray["source"] = $xml;
2680 $prefix = share_header(
2681 $original_item["author-name"],
2682 $original_item["author-link"],
2683 $original_item["author-avatar"],
2684 $original_item["guid"],
2685 $original_item["created"],
2688 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2690 $datarray["tag"] = $original_item["tag"];
2691 $datarray["app"] = $original_item["app"];
2693 $datarray["plink"] = self::plink($author, $guid);
2694 $datarray["private"] = (($public == "false") ? 1 : 0);
2695 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2697 $datarray["object-type"] = $original_item["object-type"];
2699 self::fetchGuid($datarray);
2700 $message_id = Item::insert($datarray);
2702 self::sendParticipation($contact, $datarray);
2704 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2705 if ($root_message_id) {
2706 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2710 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2711 if ($datarray['uid'] == 0) {
2712 Item::distribute($message_id);
2721 * @brief Processes retractions
2723 * @param array $importer Array of the importer user
2724 * @param array $contact The contact of the item owner
2725 * @param object $data The message object
2727 * @return bool success
2728 * @throws \Exception
2730 private static function itemRetraction(array $importer, array $contact, $data)
2732 $author = Strings::escapeTags(XML::unescape($data->author));
2733 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2734 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2736 $person = self::personByHandle($author);
2737 if (!is_array($person)) {
2738 Logger::log("unable to find author detail for ".$author);
2742 if (empty($contact["url"])) {
2743 $contact["url"] = $person["url"];
2746 // Fetch items that are about to be deleted
2747 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2749 // When we receive a public retraction, we delete every item that we find.
2750 if ($importer['uid'] == 0) {
2751 $condition = ['guid' => $target_guid, 'deleted' => false];
2753 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2756 $r = Item::select($fields, $condition);
2757 if (!DBA::isResult($r)) {
2758 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2762 while ($item = Item::fetch($r)) {
2763 if (strstr($item['file'], '[')) {
2764 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2768 // Fetch the parent item
2769 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2771 // Only delete it if the parent author really fits
2772 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2773 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2777 Item::delete(['id' => $item['id']]);
2779 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2786 * @brief Receives retraction messages
2788 * @param array $importer Array of the importer user
2789 * @param string $sender The sender of the message
2790 * @param object $data The message object
2792 * @return bool Success
2793 * @throws \Exception
2795 private static function receiveRetraction(array $importer, $sender, $data)
2797 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2799 $contact = self::contactByHandle($importer["uid"], $sender);
2800 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2801 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2809 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2811 switch ($target_type) {
2816 case "StatusMessage":
2817 return self::itemRetraction($importer, $contact, $data);
2819 case "PollParticipation":
2821 // Currently unsupported
2825 Logger::log("Unknown target type ".$target_type);
2832 * @brief Receives status messages
2834 * @param array $importer Array of the importer user
2835 * @param SimpleXMLElement $data The message object
2836 * @param string $xml The original XML of the message
2838 * @return int The message id of the newly created item
2839 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2840 * @throws \ImagickException
2842 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2844 $author = Strings::escapeTags(XML::unescape($data->author));
2845 $guid = Strings::escapeTags(XML::unescape($data->guid));
2846 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2847 $public = Strings::escapeTags(XML::unescape($data->public));
2848 $text = XML::unescape($data->text);
2849 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2851 $contact = self::allowedContactByHandle($importer, $author, false);
2856 $message_id = self::messageExists($importer["uid"], $guid);
2862 if ($data->location) {
2863 foreach ($data->location->children() as $fieldname => $data) {
2864 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2868 $body = Markdown::toBBCode($text);
2872 // Attach embedded pictures to the body
2874 foreach ($data->photo as $photo) {
2875 $body = "[img]".XML::unescape($photo->remote_photo_path).
2876 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2879 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2881 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2883 // Add OEmbed and other information to the body
2884 if (!self::isRedmatrix($contact["url"])) {
2885 $body = add_page_info_to_body($body, false, true);
2889 /// @todo enable support for polls
2890 //if ($data->poll) {
2891 // foreach ($data->poll AS $poll)
2896 /// @todo enable support for events
2898 $datarray["uid"] = $importer["uid"];
2899 $datarray["contact-id"] = $contact["id"];
2900 $datarray["network"] = Protocol::DIASPORA;
2902 $datarray["author-link"] = $contact["url"];
2903 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2905 $datarray["owner-link"] = $datarray["author-link"];
2906 $datarray["owner-id"] = $datarray["author-id"];
2908 $datarray["guid"] = $guid;
2909 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2911 $datarray["verb"] = ACTIVITY_POST;
2912 $datarray["gravity"] = GRAVITY_PARENT;
2914 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2915 $datarray["source"] = $xml;
2917 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2919 if ($provider_display_name != "") {
2920 $datarray["app"] = $provider_display_name;
2923 $datarray["plink"] = self::plink($author, $guid);
2924 $datarray["private"] = (($public == "false") ? 1 : 0);
2925 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2927 if (isset($address["address"])) {
2928 $datarray["location"] = $address["address"];
2931 if (isset($address["lat"]) && isset($address["lng"])) {
2932 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2935 self::fetchGuid($datarray);
2936 $message_id = Item::insert($datarray);
2938 self::sendParticipation($contact, $datarray);
2941 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2942 if ($datarray['uid'] == 0) {
2943 Item::distribute($message_id);
2951 /* ************************************************************************************** *
2952 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2953 * ************************************************************************************** */
2956 * @brief returnes the handle of a contact
2958 * @param array $contact contact array
2960 * @return string the handle in the format user@domain.tld
2961 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2963 private static function myHandle(array $contact)
2965 if (!empty($contact["addr"])) {
2966 return $contact["addr"];
2969 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2970 // So - just in case - we build the the address here.
2971 if ($contact["nickname"] != "") {
2972 $nick = $contact["nickname"];
2974 $nick = $contact["nick"];
2977 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2982 * @brief Creates the data for a private message in the new format
2984 * @param string $msg The message that is to be transmitted
2985 * @param array $user The record of the sender
2986 * @param array $contact Target of the communication
2987 * @param string $prvkey The private key of the sender
2988 * @param string $pubkey The public key of the receiver
2990 * @return string The encrypted data
2991 * @throws \Exception
2993 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2995 Logger::log("Message: ".$msg, Logger::DATA);
2997 // without a public key nothing will work
2999 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3003 $aes_key = openssl_random_pseudo_bytes(32);
3004 $b_aes_key = base64_encode($aes_key);
3005 $iv = openssl_random_pseudo_bytes(16);
3006 $b_iv = base64_encode($iv);
3008 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3010 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3012 $encrypted_key_bundle = "";
3013 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3015 $json_object = json_encode(
3016 ["aes_key" => base64_encode($encrypted_key_bundle),
3017 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3020 return $json_object;
3024 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3026 * @param string $msg The message that is to be transmitted
3027 * @param array $user The record of the sender
3029 * @return string The envelope
3030 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3032 public static function buildMagicEnvelope($msg, array $user)
3034 $b64url_data = Strings::base64UrlEncode($msg);
3035 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3037 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3038 $type = "application/xml";
3039 $encoding = "base64url";
3040 $alg = "RSA-SHA256";
3041 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3043 // Fallback if the private key wasn't transmitted in the expected field
3044 if ($user['uprvkey'] == "") {
3045 $user['uprvkey'] = $user['prvkey'];
3048 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3049 $sig = Strings::base64UrlEncode($signature);
3051 $xmldata = ["me:env" => ["me:data" => $data,
3052 "@attributes" => ["type" => $type],
3053 "me:encoding" => $encoding,
3056 "@attributes2" => ["key_id" => $key_id]]];
3058 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3060 return XML::fromArray($xmldata, $xml, false, $namespaces);
3064 * @brief Create the envelope for a message
3066 * @param string $msg The message that is to be transmitted
3067 * @param array $user The record of the sender
3068 * @param array $contact Target of the communication
3069 * @param string $prvkey The private key of the sender
3070 * @param string $pubkey The public key of the receiver
3071 * @param bool $public Is the message public?
3073 * @return string The message that will be transmitted to other servers
3074 * @throws \Exception
3076 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3078 // The message is put into an envelope with the sender's signature
3079 $envelope = self::buildMagicEnvelope($msg, $user);
3081 // Private messages are put into a second envelope, encrypted with the receivers public key
3083 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3090 * @brief Creates a signature for a message
3092 * @param array $owner the array of the owner of the message
3093 * @param array $message The message that is to be signed
3095 * @return string The signature
3097 private static function signature($owner, $message)
3100 unset($sigmsg["author_signature"]);
3101 unset($sigmsg["parent_author_signature"]);
3103 $signed_text = implode(";", $sigmsg);
3105 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3109 * @brief Transmit a message to a target server
3111 * @param array $owner the array of the item owner
3112 * @param array $contact Target of the communication
3113 * @param string $envelope The message that is to be transmitted
3114 * @param bool $public_batch Is it a public post?
3115 * @param string $guid message guid
3117 * @return int Result of the transmission
3118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3119 * @throws \ImagickException
3121 private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3123 $enabled = intval(Config::get("system", "diaspora_enabled"));
3128 $logid = Strings::getRandomHex(4);
3130 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3132 // We always try to use the data from the fcontact table.
3133 // This is important for transmitting data to Friendica servers.
3134 if (!empty($contact['addr'])) {
3135 $fcontact = self::personByHandle($contact['addr']);
3136 if (!empty($fcontact)) {
3137 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3142 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3146 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3148 if (!intval(Config::get("system", "diaspora_test"))) {
3149 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3151 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3152 $return_code = $postResult->getReturnCode();
3154 Logger::log("test_mode");
3158 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3160 return $return_code ? $return_code : -1;
3165 * @brief Build the post xml
3167 * @param string $type The message type
3168 * @param array $message The message data
3170 * @return string The post XML
3172 public static function buildPostXml($type, $message)
3174 $data = [$type => $message];
3176 return XML::fromArray($data, $xml);
3180 * @brief Builds and transmit messages
3182 * @param array $owner the array of the item owner
3183 * @param array $contact Target of the communication
3184 * @param string $type The message type
3185 * @param array $message The message data
3186 * @param bool $public_batch Is it a public post?
3187 * @param string $guid message guid
3189 * @return int Result of the transmission
3190 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3191 * @throws \ImagickException
3193 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3195 $msg = self::buildPostXml($type, $message);
3197 Logger::log('message: '.$msg, Logger::DATA);
3198 Logger::log('send guid '.$guid, Logger::DEBUG);
3200 // Fallback if the private key wasn't transmitted in the expected field
3201 if (empty($owner['uprvkey'])) {
3202 $owner['uprvkey'] = $owner['prvkey'];
3205 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3207 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3209 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3211 return $return_code;
3215 * @brief sends a participation (Used to get all further updates)
3217 * @param array $contact Target of the communication
3218 * @param array $item Item array
3220 * @return int The result of the transmission
3221 * @throws \Exception
3223 private static function sendParticipation(array $contact, array $item)
3225 // Don't send notifications for private postings
3226 if ($item['private']) {
3230 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3232 $result = Cache::get($cachekey);
3233 if (!is_null($result)) {
3237 // Fetch some user id to have a valid handle to transmit the participation.
3238 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3239 // If the item belongs to a user, we take this user id.
3240 if ($item['uid'] == 0) {
3241 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3242 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3243 $owner = User::getOwnerDataById($first_user['uid']);
3245 $owner = User::getOwnerDataById($item['uid']);
3248 $author = self::myHandle($owner);
3250 $message = ["author" => $author,
3251 "guid" => System::createUUID(),
3252 "parent_type" => "Post",
3253 "parent_guid" => $item["guid"]];
3255 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3257 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3258 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3260 return self::buildAndTransmit($owner, $contact, "participation", $message);
3264 * @brief sends an account migration
3266 * @param array $owner the array of the item owner
3267 * @param array $contact Target of the communication
3268 * @param int $uid User ID
3270 * @return int The result of the transmission
3271 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3272 * @throws \ImagickException
3274 public static function sendAccountMigration(array $owner, array $contact, $uid)
3276 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3277 $profile = self::createProfileData($uid);
3279 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3280 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3282 $message = ["author" => $old_handle,
3283 "profile" => $profile,
3284 "signature" => $signature];
3286 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3288 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3292 * @brief Sends a "share" message
3294 * @param array $owner the array of the item owner
3295 * @param array $contact Target of the communication
3297 * @return int The result of the transmission
3298 * @throws \Exception
3300 public static function sendShare(array $owner, array $contact)
3303 * @todo support the different possible combinations of "following" and "sharing"
3304 * Currently, Diaspora only interprets the "sharing" field
3306 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3310 switch ($contact["rel"]) {
3311 case Contact::FRIEND:
3315 case Contact::SHARING:
3319 case Contact::FOLLOWER:
3325 $message = ["author" => self::myHandle($owner),
3326 "recipient" => $contact["addr"],
3327 "following" => "true",
3328 "sharing" => "true"];
3330 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3332 return self::buildAndTransmit($owner, $contact, "contact", $message);
3336 * @brief sends an "unshare"
3338 * @param array $owner the array of the item owner
3339 * @param array $contact Target of the communication
3341 * @return int The result of the transmission
3342 * @throws \Exception
3344 public static function sendUnshare(array $owner, array $contact)
3346 $message = ["author" => self::myHandle($owner),
3347 "recipient" => $contact["addr"],
3348 "following" => "false",
3349 "sharing" => "false"];
3351 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3353 return self::buildAndTransmit($owner, $contact, "contact", $message);
3357 * @brief Checks a message body if it is a reshare
3359 * @param string $body The message body that is to be check
3360 * @param bool $complete Should it be a complete check or a simple check?
3362 * @return array|bool Reshare details or "false" if no reshare
3363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3364 * @throws \ImagickException
3366 public static function isReshare($body, $complete = true)
3368 $body = trim($body);
3370 // Skip if it isn't a pure repeated messages
3371 // Does it start with a share?
3372 if ((strpos($body, "[share") > 0) && $complete) {
3376 // Does it end with a share?
3377 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3381 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3382 // Skip if there is no shared message in there
3383 if ($body == $attributes) {
3387 // If we don't do the complete check we quit here
3390 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3391 if (!empty($matches[1])) {
3392 $guid = $matches[1];
3395 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3396 if (!empty($matches[1])) {
3397 $guid = $matches[1];
3400 if (($guid != "") && $complete) {
3401 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3402 $item = Item::selectFirst(['contact-id'], $condition);
3403 if (DBA::isResult($item)) {
3405 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3406 $ret["root_guid"] = $guid;
3408 } elseif ($complete) {
3409 // We are resharing something that isn't a DFRN or Diaspora post.
3410 // So we have to return "false" on "$complete" to not trigger a reshare.
3413 } elseif (($guid == "") && $complete) {
3417 $ret["root_guid"] = $guid;
3420 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3421 if (!empty($matches[1])) {
3422 $profile = $matches[1];
3425 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3426 if (!empty($matches[1])) {
3427 $profile = $matches[1];
3432 if ($profile != "") {
3433 if (Contact::getIdForURL($profile)) {
3434 $author = Contact::getDetailsByURL($profile);
3435 $ret["root_handle"] = $author['addr'];
3439 if (empty($ret) && !$complete) {
3447 * @brief Create an event array
3449 * @param integer $event_id The id of the event
3451 * @return array with event data
3452 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3454 private static function buildEvent($event_id)
3456 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3457 if (!DBA::isResult($r)) {
3465 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3466 if (!DBA::isResult($r)) {
3472 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3473 if (!DBA::isResult($r)) {
3479 $eventdata['author'] = self::myHandle($owner);
3481 if ($event['guid']) {
3482 $eventdata['guid'] = $event['guid'];
3485 $mask = DateTimeFormat::ATOM;
3487 /// @todo - establish "all day" events in Friendica
3488 $eventdata["all_day"] = "false";
3490 $eventdata['timezone'] = 'UTC';
3491 if (!$event['adjust'] && $user['timezone']) {
3492 $eventdata['timezone'] = $user['timezone'];
3495 if ($event['start']) {
3496 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3498 if ($event['finish'] && !$event['nofinish']) {
3499 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3501 if ($event['summary']) {
3502 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3504 if ($event['desc']) {
3505 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3507 if ($event['location']) {
3508 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3509 $coord = Map::getCoordinates($event['location']);
3512 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3513 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3514 $location["lat"] = $coord['lat'];
3515 $location["lng"] = $coord['lon'];
3517 $location["lat"] = 0;
3518 $location["lng"] = 0;
3520 $eventdata['location'] = $location;
3527 * @brief Create a post (status message or reshare)
3529 * @param array $item The item that will be exported
3530 * @param array $owner the array of the item owner
3533 * 'type' -> Message type ("status_message" or "reshare")
3534 * 'message' -> Array of XML elements of the status
3535 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3536 * @throws \ImagickException
3538 public static function buildStatus(array $item, array $owner)
3540 $cachekey = "diaspora:buildStatus:".$item['guid'];
3542 $result = Cache::get($cachekey);
3543 if (!is_null($result)) {
3547 $myaddr = self::myHandle($owner);
3549 $public = ($item["private"] ? "false" : "true");
3551 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3552 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3554 // Detect a share element and do a reshare
3555 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3556 $message = ["author" => $myaddr,
3557 "guid" => $item["guid"],
3558 "created_at" => $created,
3559 "root_author" => $ret["root_handle"],
3560 "root_guid" => $ret["root_guid"],
3561 "provider_display_name" => $item["app"],
3562 "public" => $public];
3566 $title = $item["title"];
3567 $body = $item["body"];
3569 if ($item['author-link'] != $item['owner-link']) {
3570 require_once 'mod/share.php';
3571 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3572 "", $item['created'], $item['plink']) . $body . '[/share]';
3575 // convert to markdown
3576 $body = html_entity_decode(BBCode::toMarkdown($body));
3579 if (strlen($title)) {
3580 $body = "## ".html_entity_decode($title)."\n\n".$body;
3583 if ($item["attach"]) {
3584 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3586 $body .= "\n".L10n::t("Attachments:")."\n";
3587 foreach ($matches as $mtch) {
3588 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3595 if ($item["location"] != "")
3596 $location["address"] = $item["location"];
3598 if ($item["coord"] != "") {
3599 $coord = explode(" ", $item["coord"]);
3600 $location["lat"] = $coord[0];
3601 $location["lng"] = $coord[1];
3604 $message = ["author" => $myaddr,
3605 "guid" => $item["guid"],
3606 "created_at" => $created,
3607 "edited_at" => $edited,
3608 "public" => $public,
3610 "provider_display_name" => $item["app"],
3611 "location" => $location];
3613 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3614 if (!isset($location["lat"]) || !isset($location["lng"])) {
3615 unset($message["location"]);
3618 if ($item['event-id'] > 0) {
3619 $event = self::buildEvent($item['event-id']);
3620 if (count($event)) {
3621 $message['event'] = $event;
3623 if (!empty($event['location']['address']) &&
3624 !empty($event['location']['lat']) &&
3625 !empty($event['location']['lng'])) {
3626 $message['location'] = $event['location'];
3629 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3630 // $message['text'] = '';
3634 $type = "status_message";
3637 $msg = ["type" => $type, "message" => $message];
3639 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3644 private static function prependParentAuthorMention($body, $profile_url)
3646 $profile = Contact::getDetailsByURL($profile_url);
3647 if (!empty($profile['addr'])
3648 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3649 && !strstr($body, $profile['addr'])
3650 && !strstr($body, $profile_url)
3652 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3659 * @brief Sends a post
3661 * @param array $item The item that will be exported
3662 * @param array $owner the array of the item owner
3663 * @param array $contact Target of the communication
3664 * @param bool $public_batch Is it a public post?
3666 * @return int The result of the transmission
3667 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3668 * @throws \ImagickException
3670 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3672 $status = self::buildStatus($item, $owner);
3674 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3678 * @brief Creates a "like" object
3680 * @param array $item The item that will be exported
3681 * @param array $owner the array of the item owner
3683 * @return array The data for a "like"
3684 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3686 private static function constructLike(array $item, array $owner)
3688 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3689 if (!DBA::isResult($parent)) {
3693 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3695 if ($item['verb'] === ACTIVITY_LIKE) {
3697 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3698 $positive = "false";
3701 return(["author" => self::myHandle($owner),
3702 "guid" => $item["guid"],
3703 "parent_guid" => $parent["guid"],
3704 "parent_type" => $target_type,
3705 "positive" => $positive,
3706 "author_signature" => ""]);
3710 * @brief Creates an "EventParticipation" object
3712 * @param array $item The item that will be exported
3713 * @param array $owner the array of the item owner
3715 * @return array The data for an "EventParticipation"
3716 * @throws \Exception
3718 private static function constructAttend(array $item, array $owner)
3720 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3721 if (!DBA::isResult($parent)) {
3725 switch ($item['verb']) {
3726 case ACTIVITY_ATTEND:
3727 $attend_answer = 'accepted';
3729 case ACTIVITY_ATTENDNO:
3730 $attend_answer = 'declined';
3732 case ACTIVITY_ATTENDMAYBE:
3733 $attend_answer = 'tentative';
3736 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3740 return(["author" => self::myHandle($owner),
3741 "guid" => $item["guid"],
3742 "parent_guid" => $parent["guid"],
3743 "status" => $attend_answer,
3744 "author_signature" => ""]);
3748 * @brief Creates the object for a comment
3750 * @param array $item The item that will be exported
3751 * @param array $owner the array of the item owner
3753 * @return array|false The data for a comment
3754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3756 private static function constructComment(array $item, array $owner)
3758 $cachekey = "diaspora:constructComment:".$item['guid'];
3760 $result = Cache::get($cachekey);
3761 if (!is_null($result)) {
3765 $toplevel_item = Item::selectFirst(['guid', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3766 if (!DBA::isResult($toplevel_item)) {
3767 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3771 $thread_parent_item = $toplevel_item;
3772 if ($item['thr-parent'] != $item['parent-uri']) {
3773 $thread_parent_item = Item::selectFirst(['guid', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3776 $body = $item["body"];
3778 if ((empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3779 && !Config::get('system', 'disable_implicit_mentions')
3781 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3784 $text = html_entity_decode(BBCode::toMarkdown($body));
3785 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3786 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3789 "author" => self::myHandle($owner),
3790 "guid" => $item["guid"],
3791 "created_at" => $created,
3792 "edited_at" => $edited,
3793 "parent_guid" => $toplevel_item["guid"],
3795 "author_signature" => ""
3798 // Send the thread parent guid only if it is a threaded comment
3799 if ($item['thr-parent'] != $item['parent-uri']) {
3800 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3803 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3809 * @brief Send a like or a comment
3811 * @param array $item The item that will be exported
3812 * @param array $owner the array of the item owner
3813 * @param array $contact Target of the communication
3814 * @param bool $public_batch Is it a public post?
3816 * @return int The result of the transmission
3817 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3818 * @throws \ImagickException
3820 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3822 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3823 $message = self::constructAttend($item, $owner);
3824 $type = "event_participation";
3825 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3826 $message = self::constructLike($item, $owner);
3828 } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW, ACTIVITY_TAG])) {
3829 $message = self::constructComment($item, $owner);
3833 if (empty($message)) {
3837 $message["author_signature"] = self::signature($owner, $message);
3839 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3843 * @brief Creates a message from a signature record entry
3845 * @param array $item The item that will be exported
3846 * @return array The message
3848 private static function messageFromSignature(array $item)
3850 // Split the signed text
3851 $signed_parts = explode(";", $item['signed_text']);
3853 if ($item["deleted"]) {
3854 $message = ["author" => $item['signer'],
3855 "target_guid" => $signed_parts[0],
3856 "target_type" => $signed_parts[1]];
3857 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3858 $message = ["author" => $signed_parts[4],
3859 "guid" => $signed_parts[1],
3860 "parent_guid" => $signed_parts[3],
3861 "parent_type" => $signed_parts[2],
3862 "positive" => $signed_parts[0],
3863 "author_signature" => $item['signature'],
3864 "parent_author_signature" => ""];
3866 // Remove the comment guid
3867 $guid = array_shift($signed_parts);
3869 // Remove the parent guid
3870 $parent_guid = array_shift($signed_parts);
3872 // Remove the handle
3873 $handle = array_pop($signed_parts);
3876 "author" => $handle,
3878 "parent_guid" => $parent_guid,
3879 "text" => implode(";", $signed_parts),
3880 "author_signature" => $item['signature'],
3881 "parent_author_signature" => ""
3888 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3890 * @param array $item The item that will be exported
3891 * @param array $owner the array of the item owner
3892 * @param array $contact Target of the communication
3893 * @param bool $public_batch Is it a public post?
3895 * @return int The result of the transmission
3896 * @throws \Exception
3898 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3900 if ($item["deleted"]) {
3901 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3902 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3908 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3910 // Old way - is used by the internal Friendica functions
3911 /// @todo Change all signatur storing functions to the new format
3912 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
3913 $message = self::messageFromSignature($item);
3915 $msg = json_decode($item['signed_text'], true);
3918 if (is_array($msg)) {
3919 foreach ($msg as $field => $data) {
3920 if (!$item["deleted"]) {
3921 if ($field == "diaspora_handle") {
3924 if ($field == "target_type") {
3925 $field = "parent_type";
3929 $message[$field] = $data;
3932 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3936 $message["parent_author_signature"] = self::signature($owner, $message);
3938 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
3940 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3944 * @brief Sends a retraction (deletion) of a message, like or comment
3946 * @param array $item The item that will be exported
3947 * @param array $owner the array of the item owner
3948 * @param array $contact Target of the communication
3949 * @param bool $public_batch Is it a public post?
3950 * @param bool $relay Is the retraction transmitted from a relay?
3952 * @return int The result of the transmission
3953 * @throws \Exception
3955 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3957 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3959 $msg_type = "retraction";
3961 if ($item['id'] == $item['parent']) {
3962 $target_type = "Post";
3963 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3964 $target_type = "Like";
3966 $target_type = "Comment";
3969 $message = ["author" => $itemaddr,
3970 "target_guid" => $item['guid'],
3971 "target_type" => $target_type];
3973 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
3975 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3979 * @brief Sends a mail
3981 * @param array $item The item that will be exported
3982 * @param array $owner The owner
3983 * @param array $contact Target of the communication
3985 * @return int The result of the transmission
3986 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3987 * @throws \ImagickException
3989 public static function sendMail(array $item, array $owner, array $contact)
3991 $myaddr = self::myHandle($owner);
3993 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3994 if (!DBA::isResult($cnv)) {
3995 Logger::log("conversation not found.");
3999 $body = BBCode::toMarkdown($item["body"]);
4000 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4003 "author" => $myaddr,
4004 "guid" => $item["guid"],
4005 "conversation_guid" => $cnv["guid"],
4007 "created_at" => $created,
4010 if ($item["reply"]) {
4015 "author" => $cnv["creator"],
4016 "guid" => $cnv["guid"],
4017 "subject" => $cnv["subject"],
4018 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4019 "participants" => $cnv["recips"],
4023 $type = "conversation";
4026 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4030 * @brief Split a name into first name and last name
4032 * @param string $name The name
4034 * @return array The array with "first" and "last"
4036 public static function splitName($name) {
4037 $name = trim($name);
4039 // Is the name longer than 64 characters? Then cut the rest of it.
4040 if (strlen($name) > 64) {
4041 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4042 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4044 $name = substr($name, 0, 64);
4048 // Take the first word as first name
4049 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4050 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4051 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4052 return ['first' => $first, 'last' => $last];
4055 // Take the last word as last name
4056 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4057 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4059 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4060 return ['first' => $first, 'last' => $last];
4063 // Take the first 32 characters if there is no space in the first 32 characters
4064 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4065 $first = substr($name, 0, 32);
4066 $last = substr($name, 32);
4067 return ['first' => $first, 'last' => $last];
4070 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4071 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4073 // Check if the last name is longer than 32 characters
4074 if (strlen($last) > 32) {
4075 if (strpos($last, ' ') <= 32) {
4076 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4078 $last = substr($last, 0, 32);
4082 return ['first' => $first, 'last' => $last];
4086 * @brief Create profile data
4088 * @param int $uid The user id
4090 * @return array The profile data
4091 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4093 private static function createProfileData($uid)
4096 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4098 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4099 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4100 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4109 $handle = $profile["addr"];
4111 $split_name = self::splitName($profile['name']);
4112 $first = $split_name['first'];
4113 $last = $split_name['last'];
4115 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4116 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4117 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4118 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4124 if ($searchable === 'true') {
4127 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4128 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4132 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4135 $about = $profile['about'];
4136 $about = strip_tags(BBCode::convert($about));
4138 $location = Profile::formatLocation($profile);
4140 if ($profile['pub_keywords']) {
4141 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4142 $kw = str_replace(' ', ' ', $kw);
4143 $arr = explode(' ', $kw);
4145 for ($x = 0; $x < 5; $x ++) {
4146 if (!empty($arr[$x])) {
4147 $tags .= '#'. trim($arr[$x]) .' ';
4152 $tags = trim($tags);
4155 return ["author" => $handle,
4156 "first_name" => $first,
4157 "last_name" => $last,
4158 "image_url" => $large,
4159 "image_url_medium" => $medium,
4160 "image_url_small" => $small,
4162 "gender" => $profile['gender'],
4164 "location" => $location,
4165 "searchable" => $searchable,
4167 "tag_string" => $tags];
4171 * @brief Sends profile data
4173 * @param int $uid The user id
4174 * @param bool $recips optional, default false
4176 * @throws \Exception
4178 public static function sendProfile($uid, $recips = false)
4184 $owner = User::getOwnerDataById($uid);
4191 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4192 AND `uid` = %d AND `rel` != %d",
4193 DBA::escape(Protocol::DIASPORA),
4195 intval(Contact::SHARING)
4203 $message = self::createProfileData($uid);
4205 // @ToDo Split this into single worker jobs
4206 foreach ($recips as $recip) {
4207 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4208 self::buildAndTransmit($owner, $recip, "profile", $message);
4213 * @brief Creates the signature for likes that are created on our system
4215 * @param integer $uid The user of that comment
4216 * @param array $item Item array
4218 * @return array Signed content
4219 * @throws \Exception
4221 public static function createLikeSignature($uid, array $item)
4223 $owner = User::getOwnerDataById($uid);
4224 if (empty($owner)) {
4225 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4229 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4233 $message = self::constructLike($item, $owner);
4234 if ($message === false) {
4238 $message["author_signature"] = self::signature($owner, $message);
4244 * @brief Creates the signature for Comments that are created on our system
4246 * @param integer $uid The user of that comment
4247 * @param array $item Item array
4249 * @return array Signed content
4250 * @throws \Exception
4252 public static function createCommentSignature($uid, array $item)
4254 $owner = User::getOwnerDataById($uid);
4255 if (empty($owner)) {
4256 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4260 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4261 $item['thr-parent'] = $item['parent-uri'];
4263 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4264 if (!DBA::isResult($parent)) {
4268 $item['parent-uri'] = $parent['parent-uri'];
4270 $message = self::constructComment($item, $owner);
4271 if ($message === false) {
4275 $message["author_signature"] = self::signature($owner, $message);