3 * @file src/Protocol/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "validPosting" and interpret only the new protocol.
11 namespace Friendica\Protocol;
13 use Friendica\Content\Feature;
14 use Friendica\Content\Text\BBCode;
15 use Friendica\Content\Text\Markdown;
16 use Friendica\Core\Cache;
17 use Friendica\Core\Config;
18 use Friendica\Core\L10n;
19 use Friendica\Core\Logger;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Conversation;
27 use Friendica\Model\GContact;
28 use Friendica\Model\Group;
29 use Friendica\Model\Item;
30 use Friendica\Model\Profile;
31 use Friendica\Model\Queue;
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;
43 * @brief This class contain functions to create and send Diaspora XML files
49 * @brief Return a list of relay servers
51 * The list contains not only the official relays but also servers that we serve directly
53 * @param integer $item_id The id of the item that is sent
54 * @param array $contacts The previously fetched contacts
56 * @return array of relay servers
57 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
59 public static function relayList($item_id, array $contacts = [])
63 // Fetching relay servers
64 $serverdata = Config::get("system", "relay_server");
66 if (!empty($serverdata)) {
67 $servers = explode(",", $serverdata);
68 foreach ($servers as $server) {
69 $serverlist[$server] = trim($server);
73 if (Config::get("system", "relay_directly", false)) {
74 // We distribute our stuff based on the parent to ensure that the thread will be complete
75 $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
76 if (!DBA::isResult($parent)) {
80 // Servers that want to get all content
81 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
82 while ($server = DBA::fetch($servers)) {
83 $serverlist[$server['url']] = $server['url'];
86 // All tags of the current post
87 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
88 $tags = DBA::select('term', ['term'], $condition);
90 while ($tag = DBA::fetch($tags)) {
91 $taglist[] = $tag['term'];
94 // All servers who wants content with this tag
96 if (!empty($taglist)) {
97 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
98 while ($server = DBA::fetch($tagserver)) {
99 $tagserverlist[] = $server['gserver-id'];
103 // All adresses with the given id
104 if (!empty($tagserverlist)) {
105 $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
106 while ($server = DBA::fetch($servers)) {
107 $serverlist[$server['url']] = $server['url'];
112 // Now we are collecting all relay contacts
113 foreach ($serverlist as $server_url) {
114 // We don't send messages to ourselves
115 if (Strings::compareLink($server_url, System::baseUrl())) {
118 $contact = self::getRelayContact($server_url);
119 if (is_bool($contact)) {
124 foreach ($contacts as $entry) {
125 if ($entry['batch'] == $contact['batch']) {
131 $contacts[] = $contact;
139 * @brief Return a contact for a given server address or creates a dummy entry
141 * @param string $server_url The url of the server
142 * @return array with the contact
145 private static function getRelayContact($server_url)
147 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
149 // Fetch the relay contact
150 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
151 'contact-type' => Contact::TYPE_RELAY];
152 $contact = DBA::selectFirst('contact', $fields, $condition);
154 if (DBA::isResult($contact)) {
155 if ($contact['archive'] || $contact['blocked']) {
160 self::setRelayContact($server_url);
162 $contact = DBA::selectFirst('contact', $fields, $condition);
163 if (DBA::isResult($contact)) {
168 // It should never happen that we arrive here
173 * @brief Update or insert a relay contact
175 * @param string $server_url The url of the server
176 * @param array $network_fields Optional network specific fields
179 public static function setRelayContact($server_url, array $network_fields = [])
181 $fields = ['created' => DateTimeFormat::utcNow(),
182 'name' => 'relay', 'nick' => 'relay',
183 'url' => $server_url, 'network' => Protocol::DIASPORA,
184 'batch' => $server_url . '/receive/public',
185 'rel' => Contact::FOLLOWER, 'blocked' => false,
186 'pending' => false, 'writable' => true];
188 $fields = array_merge($fields, $network_fields);
190 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
191 'contact-type' => Contact::TYPE_RELAY];
193 if (DBA::exists('contact', $condition)) {
194 unset($fields['created']);
197 DBA::update('contact', $fields, $condition, true);
201 * @brief Return a list of participating contacts for a thread
203 * This is used for the participation feature.
204 * One of the parameters is a contact array.
205 * This is done to avoid duplicates.
207 * @param integer $thread The id of the thread
208 * @param array $contacts The previously fetched contacts
210 * @return array of relay servers
213 public static function participantsForThread($thread, array $contacts)
215 $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
216 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
217 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
218 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
219 WHERE `participation`.`iid` = ?", $thread);
221 while ($contact = DBA::fetch($r)) {
222 if (!empty($contact['fnetwork'])) {
223 $contact['network'] = $contact['fnetwork'];
225 unset($contact['fnetwork']);
227 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
228 $contact['batch'] = $contact['fbatch'];
230 unset($contact['fbatch']);
233 foreach ($contacts as $entry) {
234 if ($entry['batch'] == $contact['batch']) {
240 $contacts[] = $contact;
249 * @brief repairs a signature that was double encoded
251 * The function is unused at the moment. It was copied from the old implementation.
253 * @param string $signature The signature
254 * @param string $handle The handle of the signature owner
255 * @param integer $level This value is only set inside this function to avoid endless loops
257 * @return string the repaired signature
260 private static function repairSignature($signature, $handle = "", $level = 1)
262 if ($signature == "") {
266 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
267 $signature = base64_decode($signature);
268 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
270 // Do a recursive call to be able to fix even multiple levels
272 $signature = self::repairSignature($signature, $handle, ++$level);
280 * @brief verify the envelope and return the verified data
282 * @param string $envelope The magic envelope
284 * @return string verified data
285 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
286 * @throws \ImagickException
288 private static function verifyMagicEnvelope($envelope)
290 $basedom = XML::parseString($envelope);
292 if (!is_object($basedom)) {
293 Logger::log("Envelope is no XML file");
297 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
299 if (sizeof($children) == 0) {
300 Logger::log("XML has no children");
306 $data = Strings::base64UrlDecode($children->data);
307 $type = $children->data->attributes()->type[0];
309 $encoding = $children->encoding;
311 $alg = $children->alg;
313 $sig = Strings::base64UrlDecode($children->sig);
314 $key_id = $children->sig->attributes()->key_id[0];
316 $handle = Strings::base64UrlDecode($key_id);
319 $b64url_data = Strings::base64UrlEncode($data);
320 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
322 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
325 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
329 $key = self::key($handle);
331 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
335 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
337 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
345 * @brief encrypts data via AES
347 * @param string $key The AES key
348 * @param string $iv The IV (is used for CBC encoding)
349 * @param string $data The data that is to be encrypted
351 * @return string encrypted data
353 private static function aesEncrypt($key, $iv, $data)
355 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
359 * @brief decrypts data via AES
361 * @param string $key The AES key
362 * @param string $iv The IV (is used for CBC encoding)
363 * @param string $encrypted The encrypted data
365 * @return string decrypted data
367 private static function aesDecrypt($key, $iv, $encrypted)
369 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
373 * @brief: Decodes incoming Diaspora message in the new format
375 * @param array $importer Array of the importer user
376 * @param string $raw raw post message
377 * @param boolean $no_exit Don't do an http exit on error
380 * 'message' -> decoded Diaspora XML message
381 * 'author' -> author diaspora handle
382 * 'key' -> author public key (converted to pkcs#8)
383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
384 * @throws \ImagickException
386 public static function decodeRaw(array $importer, $raw, $no_exit = false)
388 $data = json_decode($raw);
390 // Is it a private post? Then decrypt the outer Salmon
391 if (is_object($data)) {
392 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
393 $ciphertext = base64_decode($data->encrypted_magic_envelope);
395 $outer_key_bundle = '';
396 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
397 $j_outer_key_bundle = json_decode($outer_key_bundle);
399 if (!is_object($j_outer_key_bundle)) {
400 Logger::log('Outer Salmon did not verify. Discarding.');
404 System::httpExit(400);
408 $outer_iv = base64_decode($j_outer_key_bundle->iv);
409 $outer_key = base64_decode($j_outer_key_bundle->key);
411 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
416 $basedom = XML::parseString($xml);
418 if (!is_object($basedom)) {
419 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
423 System::httpExit(400);
427 $base = $basedom->children(NAMESPACE_SALMON_ME);
429 // Not sure if this cleaning is needed
430 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
432 // Build the signed data
433 $type = $base->data[0]->attributes()->type[0];
434 $encoding = $base->encoding;
436 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
438 // This is the signature
439 $signature = Strings::base64UrlDecode($base->sig);
441 // Get the senders' public key
442 $key_id = $base->sig[0]->attributes()->key_id[0];
443 $author_addr = base64_decode($key_id);
444 if ($author_addr == '') {
445 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
449 System::httpExit(400);
453 $key = self::key($author_addr);
455 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
459 System::httpExit(400);
463 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
465 Logger::log('Message did not verify. Discarding.');
469 System::httpExit(400);
473 return ['message' => (string)Strings::base64UrlDecode($base->data),
474 'author' => XML::unescape($author_addr),
475 'key' => (string)$key];
479 * @brief: Decodes incoming Diaspora message in the deprecated format
481 * @param array $importer Array of the importer user
482 * @param string $xml urldecoded Diaspora salmon
485 * 'message' -> decoded Diaspora XML message
486 * 'author' -> author diaspora handle
487 * 'key' -> author public key (converted to pkcs#8)
488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
489 * @throws \ImagickException
491 public static function decode(array $importer, $xml)
494 $basedom = XML::parseString($xml);
496 if (!is_object($basedom)) {
497 Logger::log("XML is not parseable.");
500 $children = $basedom->children('https://joindiaspora.com/protocol');
502 $inner_aes_key = null;
505 if ($children->header) {
507 $author_link = str_replace('acct:', '', $children->header->author_id);
509 // This happens with posts from a relais
511 Logger::log("This is no private post in the old format", Logger::DEBUG);
515 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
517 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
518 $ciphertext = base64_decode($encrypted_header->ciphertext);
520 $outer_key_bundle = '';
521 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
523 $j_outer_key_bundle = json_decode($outer_key_bundle);
525 $outer_iv = base64_decode($j_outer_key_bundle->iv);
526 $outer_key = base64_decode($j_outer_key_bundle->key);
528 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
530 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
531 $idom = XML::parseString($decrypted);
533 $inner_iv = base64_decode($idom->iv);
534 $inner_aes_key = base64_decode($idom->aes_key);
536 $author_link = str_replace('acct:', '', $idom->author_id);
539 $dom = $basedom->children(NAMESPACE_SALMON_ME);
541 // figure out where in the DOM tree our data is hiding
544 if ($dom->provenance->data) {
545 $base = $dom->provenance;
546 } elseif ($dom->env->data) {
548 } elseif ($dom->data) {
553 Logger::log('unable to locate salmon data in xml');
554 System::httpExit(400);
558 // Stash the signature away for now. We have to find their key or it won't be good for anything.
559 $signature = Strings::base64UrlDecode($base->sig);
563 // strip whitespace so our data element will return to one big base64 blob
564 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
567 // stash away some other stuff for later
569 $type = $base->data[0]->attributes()->type[0];
570 $keyhash = $base->sig[0]->attributes()->keyhash[0];
571 $encoding = $base->encoding;
575 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
579 $data = Strings::base64UrlDecode($data);
583 $inner_decrypted = $data;
585 // Decode the encrypted blob
586 $inner_encrypted = base64_decode($data);
587 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
591 Logger::log('Could not retrieve author URI.');
592 System::httpExit(400);
594 // Once we have the author URI, go to the web and try to find their public key
595 // (first this will look it up locally if it is in the fcontact cache)
596 // This will also convert diaspora public key from pkcs#1 to pkcs#8
598 Logger::log('Fetching key for '.$author_link);
599 $key = self::key($author_link);
602 Logger::log('Could not retrieve author key.');
603 System::httpExit(400);
606 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
609 Logger::log('Message did not verify. Discarding.');
610 System::httpExit(400);
613 Logger::log('Message verified.');
615 return ['message' => (string)$inner_decrypted,
616 'author' => XML::unescape($author_link),
617 'key' => (string)$key];
622 * @brief Dispatches public messages and find the fitting receivers
624 * @param array $msg The post that will be dispatched
626 * @return int The message id of the generated message, "true" or "false" if there was an error
627 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
628 * @throws \ImagickException
630 public static function dispatchPublic($msg)
632 $enabled = intval(Config::get("system", "diaspora_enabled"));
634 Logger::log("diaspora is disabled");
638 if (!($fields = self::validPosting($msg))) {
639 Logger::log("Invalid posting");
643 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
644 $success = self::dispatch($importer, $msg, $fields);
650 * @brief Dispatches the different message types to the different functions
652 * @param array $importer Array of the importer user
653 * @param array $msg The post that will be dispatched
654 * @param SimpleXMLElement $fields SimpleXML object that contains the message
656 * @return int The message id of the generated message, "true" or "false" if there was an error
657 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
658 * @throws \ImagickException
660 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
662 // The sender is the handle of the contact that sent the message.
663 // This will often be different with relayed messages (for example "like" and "comment")
664 $sender = $msg["author"];
666 // This is only needed for private postings since this is already done for public ones before
667 if (is_null($fields)) {
669 if (!($fields = self::validPosting($msg))) {
670 Logger::log("Invalid posting");
677 $type = $fields->getName();
679 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
682 case "account_migration":
684 Logger::log('Message with type ' . $type . ' is not private, quitting.');
687 return self::receiveAccountMigration($importer, $fields);
689 case "account_deletion":
690 return self::receiveAccountDeletion($fields);
693 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
697 Logger::log('Message with type ' . $type . ' is not private, quitting.');
700 return self::receiveContactRequest($importer, $fields);
704 Logger::log('Message with type ' . $type . ' is not private, quitting.');
707 return self::receiveConversation($importer, $msg, $fields);
710 return self::receiveLike($importer, $sender, $fields);
714 Logger::log('Message with type ' . $type . ' is not private, quitting.');
717 return self::receiveMessage($importer, $fields);
719 case "participation":
721 Logger::log('Message with type ' . $type . ' is not private, quitting.');
724 return self::receiveParticipation($importer, $fields);
726 case "photo": // Not implemented
727 return self::receivePhoto($importer, $fields);
729 case "poll_participation": // Not implemented
730 return self::receivePollParticipation($importer, $fields);
734 Logger::log('Message with type ' . $type . ' is not private, quitting.');
737 return self::receiveProfile($importer, $fields);
740 return self::receiveReshare($importer, $fields, $msg["message"]);
743 return self::receiveRetraction($importer, $sender, $fields);
745 case "status_message":
746 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
749 Logger::log("Unknown message type ".$type);
755 * @brief Checks if a posting is valid and fetches the data fields.
757 * This function does not only check the signature.
758 * It also does the conversion between the old and the new diaspora format.
760 * @param array $msg Array with the XML, the sender handle and the sender signature
762 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
763 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
764 * @throws \ImagickException
766 private static function validPosting($msg)
768 $data = XML::parseString($msg["message"]);
770 if (!is_object($data)) {
771 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
775 // Is this the new or the old version?
776 if ($data->getName() == "XML") {
778 foreach ($data->post->children() as $child) {
786 $type = $element->getName();
789 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
791 // All retractions are handled identically from now on.
792 // In the new version there will only be "retraction".
793 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
794 $type = "retraction";
796 if ($type == "request") {
800 $fields = new SimpleXMLElement("<".$type."/>");
803 $author_signature = null;
804 $parent_author_signature = null;
806 foreach ($element->children() as $fieldname => $entry) {
808 // Translation for the old XML structure
809 if ($fieldname == "diaspora_handle") {
810 $fieldname = "author";
812 if ($fieldname == "participant_handles") {
813 $fieldname = "participants";
815 if (in_array($type, ["like", "participation"])) {
816 if ($fieldname == "target_type") {
817 $fieldname = "parent_type";
820 if ($fieldname == "sender_handle") {
821 $fieldname = "author";
823 if ($fieldname == "recipient_handle") {
824 $fieldname = "recipient";
826 if ($fieldname == "root_diaspora_id") {
827 $fieldname = "root_author";
829 if ($type == "status_message") {
830 if ($fieldname == "raw_message") {
834 if ($type == "retraction") {
835 if ($fieldname == "post_guid") {
836 $fieldname = "target_guid";
838 if ($fieldname == "type") {
839 $fieldname = "target_type";
844 if (($fieldname == "author_signature") && ($entry != "")) {
845 $author_signature = base64_decode($entry);
846 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
847 $parent_author_signature = base64_decode($entry);
848 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
849 if ($signed_data != "") {
853 $signed_data .= $entry;
855 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
856 || ($orig_type == "relayable_retraction")
858 XML::copy($entry, $fields, $fieldname);
862 // This is something that shouldn't happen at all.
863 if (in_array($type, ["status_message", "reshare", "profile"])) {
864 if ($msg["author"] != $fields->author) {
865 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
870 // Only some message types have signatures. So we quit here for the other types.
871 if (!in_array($type, ["comment", "like"])) {
874 // No author_signature? This is a must, so we quit.
875 if (!isset($author_signature)) {
876 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
880 if (isset($parent_author_signature)) {
881 $key = self::key($msg["author"]);
883 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
887 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
888 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);
893 $key = self::key($fields->author);
895 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
899 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
900 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);
908 * @brief Fetches the public key for a given handle
910 * @param string $handle The handle
912 * @return string The public key
913 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
914 * @throws \ImagickException
916 private static function key($handle)
918 $handle = strval($handle);
920 Logger::log("Fetching diaspora key for: ".$handle);
922 $r = self::personByHandle($handle);
931 * @brief Fetches data for a given handle
933 * @param string $handle The handle
935 * @return array the queried data
936 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
937 * @throws \ImagickException
939 public static function personByHandle($handle)
943 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
944 if (DBA::isResult($person)) {
945 Logger::debug("In cache " . print_r($person, true));
947 // update record occasionally so it doesn't get stale
948 $d = strtotime($person["updated"]." +00:00");
949 if ($d < strtotime("now - 14 days")) {
953 if ($person["guid"] == "") {
958 if (!DBA::isResult($person) || $update) {
959 Logger::log("create or refresh", Logger::DEBUG);
960 $r = Probe::uri($handle, Protocol::DIASPORA);
962 // Note that Friendica contacts will return a "Diaspora person"
963 // if Diaspora connectivity is enabled on their server
964 if ($r && ($r["network"] === Protocol::DIASPORA)) {
965 self::updateFContact($r);
967 // Fetch the updated or added contact
968 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
969 if (!DBA::isResult($person)) {
980 * @brief Updates the fcontact table
982 * @param array $arr The fcontact data
985 private static function updateFContact($arr)
987 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
988 'request' => $arr["request"], 'nick' => $arr["nick"],
989 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
990 'batch' => $arr["batch"], 'notify' => $arr["notify"],
991 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
992 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
993 'updated' => DateTimeFormat::utcNow()];
995 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
997 DBA::update('fcontact', $fields, $condition, true);
1001 * @brief get a handle (user@domain.tld) from a given contact id
1003 * @param int $contact_id The id in the contact table
1004 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1006 * @return string the handle
1007 * @throws \Exception
1009 private static function handleFromContact($contact_id, $pcontact_id = 0)
1013 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1015 if ($pcontact_id != 0) {
1016 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1018 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1019 return strtolower($contact["addr"]);
1024 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1028 if (DBA::isResult($r)) {
1031 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1033 if ($contact['addr'] != "") {
1034 $handle = $contact['addr'];
1036 $baseurl_start = strpos($contact['url'], '://') + 3;
1037 // allows installations in a subdirectory--not sure how Diaspora will handle
1038 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1039 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1040 $handle = $contact['nick'].'@'.$baseurl;
1044 return strtolower($handle);
1048 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1051 * @param mixed $fcontact_guid Hexadecimal string guid
1053 * @return string the contact url or null
1054 * @throws \Exception
1056 public static function urlFromContactGuid($fcontact_guid)
1058 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1061 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1062 DBA::escape(Protocol::DIASPORA),
1063 DBA::escape($fcontact_guid)
1066 if (DBA::isResult($r)) {
1067 return $r[0]['url'];
1074 * @brief Get a contact id for a given handle
1076 * @todo Move to Friendica\Model\Contact
1078 * @param int $uid The user id
1079 * @param string $handle The handle in the format user@domain.tld
1081 * @return array Contact data
1082 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1083 * @throws \ImagickException
1085 private static function contactByHandle($uid, $handle)
1087 $cid = Contact::getIdForURL($handle, $uid);
1089 $handle_parts = explode("@", $handle);
1090 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1091 $cid = Contact::getIdForURL($nurl_sql, $uid);
1095 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1099 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1100 if (!DBA::isResult($contact)) {
1101 // This here shouldn't happen at all
1102 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1110 * @brief Check if posting is allowed for this contact
1112 * @param array $importer Array of the importer user
1113 * @param array $contact The contact that is checked
1114 * @param bool $is_comment Is the check for a comment?
1116 * @return bool is the contact allowed to post?
1118 private static function postAllow(array $importer, array $contact, $is_comment = false)
1121 * Perhaps we were already sharing with this person. Now they're sharing with us.
1122 * That makes us friends.
1123 * Normally this should have handled by getting a request - but this could get lost
1125 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1126 // It is not removed by now. Possibly the code is needed?
1127 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1130 // array('rel' => Contact::FRIEND, 'writable' => true),
1131 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1134 // $contact["rel"] = Contact::FRIEND;
1135 // Logger::log("defining user ".$contact["nick"]." as friend");
1138 // We don't seem to like that person
1139 if ($contact["blocked"]) {
1140 // Maybe blocked, don't accept.
1142 // We are following this person?
1143 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1144 // Yes, then it is fine.
1146 // Is it a post to a community?
1147 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1150 // Is the message a global user or a comment?
1151 } elseif (($importer["uid"] == 0) || $is_comment) {
1152 // Messages for the global users and comments are always accepted
1160 * @brief Fetches the contact id for a handle and checks if posting is allowed
1162 * @param array $importer Array of the importer user
1163 * @param string $handle The checked handle in the format user@domain.tld
1164 * @param bool $is_comment Is the check for a comment?
1166 * @return array The contact data
1167 * @throws \Exception
1169 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1171 $contact = self::contactByHandle($importer["uid"], $handle);
1173 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1174 // If a contact isn't found, we accept it anyway if it is a comment
1175 if ($is_comment && ($importer["uid"] != 0)) {
1176 return self::contactByHandle(0, $handle);
1177 } elseif ($is_comment) {
1184 if (!self::postAllow($importer, $contact, $is_comment)) {
1185 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1192 * @brief Does the message already exists on the system?
1194 * @param int $uid The user id
1195 * @param string $guid The guid of the message
1197 * @return int|bool message id if the message already was stored into the system - or false.
1198 * @throws \Exception
1200 private static function messageExists($uid, $guid)
1202 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1203 if (DBA::isResult($item)) {
1204 Logger::log("message ".$guid." already exists for user ".$uid);
1212 * @brief Checks for links to posts in a message
1214 * @param array $item The item array
1217 private static function fetchGuid(array $item)
1219 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1220 preg_replace_callback(
1222 function ($match) use ($item) {
1223 self::fetchGuidSub($match, $item);
1228 preg_replace_callback(
1229 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1230 function ($match) use ($item) {
1231 self::fetchGuidSub($match, $item);
1238 * @brief Checks for relative /people/* links in an item body to match local
1239 * contacts or prepends the remote host taken from the author link.
1241 * @param string $body The item body to replace links from
1242 * @param string $author_link The author link for missing local contact fallback
1244 * @return string the replaced string
1246 public static function replacePeopleGuid($body, $author_link)
1248 $return = preg_replace_callback(
1249 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1250 function ($match) use ($author_link) {
1252 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1253 // 1 => '0123456789abcdef'
1255 $handle = self::urlFromContactGuid($match[1]);
1258 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1260 // No local match, restoring absolute remote URL from author scheme and host
1261 $author_url = parse_url($author_link);
1262 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1274 * @brief sub function of "fetchGuid" which checks for links in messages
1276 * @param array $match array containing a link that has to be checked for a message link
1277 * @param array $item The item array
1279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1280 * @throws \ImagickException
1282 private static function fetchGuidSub($match, $item)
1284 if (!self::storeByGuid($match[1], $item["author-link"])) {
1285 self::storeByGuid($match[1], $item["owner-link"]);
1290 * @brief Fetches an item with a given guid from a given server
1292 * @param string $guid the message guid
1293 * @param string $server The server address
1294 * @param int $uid The user id of the user
1296 * @return int the message id of the stored message or false
1297 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1298 * @throws \ImagickException
1300 private static function storeByGuid($guid, $server, $uid = 0)
1302 $serverparts = parse_url($server);
1304 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1308 $server = $serverparts["scheme"]."://".$serverparts["host"];
1310 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1312 $msg = self::message($guid, $server);
1318 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1320 // Now call the dispatcher
1321 return self::dispatchPublic($msg);
1325 * @brief Fetches a message from a server
1327 * @param string $guid message guid
1328 * @param string $server The url of the server
1329 * @param int $level Endless loop prevention
1332 * 'message' => The message XML
1333 * 'author' => The author handle
1334 * 'key' => The public key of the author
1335 * @throws \Exception
1337 private static function message($guid, $server, $level = 0)
1343 // This will work for new Diaspora servers and Friendica servers from 3.5
1344 $source_url = $server."/fetch/post/".urlencode($guid);
1346 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1348 $envelope = Network::fetchUrl($source_url);
1350 Logger::log("Envelope was fetched.", Logger::DEBUG);
1351 $x = self::verifyMagicEnvelope($envelope);
1353 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1355 Logger::log("Envelope was verified.", Logger::DEBUG);
1365 $source_xml = XML::parseString($x);
1367 if (!is_object($source_xml)) {
1371 if ($source_xml->post->reshare) {
1372 // Reshare of a reshare - old Diaspora version
1373 Logger::log("Message is a reshare", Logger::DEBUG);
1374 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1375 } elseif ($source_xml->getName() == "reshare") {
1376 // Reshare of a reshare - new Diaspora version
1377 Logger::log("Message is a new reshare", Logger::DEBUG);
1378 return self::message($source_xml->root_guid, $server, ++$level);
1383 // Fetch the author - for the old and the new Diaspora version
1384 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1385 $author = (string)$source_xml->post->status_message->diaspora_handle;
1386 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1387 $author = (string)$source_xml->author;
1390 // If this isn't a "status_message" then quit
1392 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1396 $msg = ["message" => $x, "author" => $author];
1398 $msg["key"] = self::key($msg["author"]);
1404 * @brief Fetches the item record of a given guid
1406 * @param int $uid The user id
1407 * @param string $guid message guid
1408 * @param string $author The handle of the item
1409 * @param array $contact The contact of the item owner
1411 * @return array the item record
1412 * @throws \Exception
1414 private static function parentItem($uid, $guid, $author, array $contact)
1416 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1417 'author-name', 'author-link', 'author-avatar',
1418 'owner-name', 'owner-link', 'owner-avatar'];
1419 $condition = ['uid' => $uid, 'guid' => $guid];
1420 $item = Item::selectFirst($fields, $condition);
1422 if (!DBA::isResult($item)) {
1423 $person = self::personByHandle($author);
1424 $result = self::storeByGuid($guid, $person["url"], $uid);
1426 // We don't have an url for items that arrived at the public dispatcher
1427 if (!$result && !empty($contact["url"])) {
1428 $result = self::storeByGuid($guid, $contact["url"], $uid);
1432 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1434 $item = Item::selectFirst($fields, $condition);
1438 if (!DBA::isResult($item)) {
1439 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1442 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1448 * @brief returns contact details
1450 * @param array $def_contact The default contact if the person isn't found
1451 * @param array $person The record of the person
1452 * @param int $uid The user id
1455 * 'cid' => contact id
1456 * 'network' => network type
1457 * @throws \Exception
1459 private static function authorContactByUrl($def_contact, $person, $uid)
1461 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1462 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1463 if (DBA::isResult($contact)) {
1464 $cid = $contact["id"];
1465 $network = $contact["network"];
1467 $cid = $def_contact["id"];
1468 $network = Protocol::DIASPORA;
1471 return ["cid" => $cid, "network" => $network];
1475 * @brief Is the profile a hubzilla profile?
1477 * @param string $url The profile link
1479 * @return bool is it a hubzilla server?
1481 public static function isRedmatrix($url)
1483 return(strstr($url, "/channel/"));
1487 * @brief Generate a post link with a given handle and message guid
1489 * @param string $addr The user handle
1490 * @param string $guid message guid
1491 * @param string $parent_guid optional parent guid
1493 * @return string the post link
1494 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1495 * @throws \ImagickException
1497 private static function plink($addr, $guid, $parent_guid = '')
1499 $contact = Contact::getDetailsByAddr($addr);
1503 if ($parent_guid != '') {
1504 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1506 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1510 if ($contact["network"] == Protocol::DFRN) {
1511 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1514 if (self::isRedmatrix($contact["url"])) {
1515 return $contact["url"] . "/?f=&mid=" . $guid;
1518 if ($parent_guid != '') {
1519 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1521 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1526 * @brief Receives account migration
1528 * @param array $importer Array of the importer user
1529 * @param object $data The message object
1531 * @return bool Success
1532 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1533 * @throws \ImagickException
1535 private static function receiveAccountMigration(array $importer, $data)
1537 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1538 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1539 $signature = Strings::escapeTags(XML::unescape($data->signature));
1541 $contact = self::contactByHandle($importer["uid"], $old_handle);
1543 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1547 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1550 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1551 $key = self::key($old_handle);
1552 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1553 Logger::log('No valid signature for migration.');
1557 // Update the profile
1558 self::receiveProfile($importer, $data->profile);
1560 // change the technical stuff in contact and gcontact
1561 $data = Probe::uri($new_handle);
1562 if ($data['network'] == Protocol::PHANTOM) {
1563 Logger::log('Account for '.$new_handle." couldn't be probed.");
1567 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1568 'name' => $data['name'], 'nick' => $data['nick'],
1569 'addr' => $data['addr'], 'batch' => $data['batch'],
1570 'notify' => $data['notify'], 'poll' => $data['poll'],
1571 'network' => $data['network']];
1573 DBA::update('contact', $fields, ['addr' => $old_handle]);
1575 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1576 'name' => $data['name'], 'nick' => $data['nick'],
1577 'addr' => $data['addr'], 'connect' => $data['addr'],
1578 'notify' => $data['notify'], 'photo' => $data['photo'],
1579 'server_url' => $data['baseurl'], 'network' => $data['network']];
1581 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1583 Logger::log('Contacts are updated.');
1589 * @brief Processes an account deletion
1591 * @param object $data The message object
1593 * @return bool Success
1594 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1596 private static function receiveAccountDeletion($data)
1598 $author = Strings::escapeTags(XML::unescape($data->author));
1600 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1601 while ($contact = DBA::fetch($contacts)) {
1602 Contact::remove($contact["id"]);
1605 DBA::delete('gcontact', ['addr' => $author]);
1607 Logger::log('Removed contacts for ' . $author);
1613 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1615 * @param string $author Author handle
1616 * @param string $guid Message guid
1617 * @param boolean $onlyfound Only return uri when found in the database
1619 * @return string The constructed uri or the one from our database
1620 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1621 * @throws \ImagickException
1623 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1625 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1626 if (DBA::isResult($item)) {
1627 return $item["uri"];
1628 } elseif (!$onlyfound) {
1629 $person = self::personByHandle($author);
1631 $parts = parse_url($person['url']);
1632 unset($parts['path']);
1633 $host_url = Network::unparseURL($parts);
1635 return $host_url . '/objects/' . $guid;
1642 * @brief Fetch the guid from our database with a given uri
1644 * @param string $uri Message uri
1645 * @param string $uid Author handle
1647 * @return string The post guid
1648 * @throws \Exception
1650 private static function getGuidFromUri($uri, $uid)
1652 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1653 if (DBA::isResult($item)) {
1654 return $item["guid"];
1661 * @brief Find the best importer for a comment, like, ...
1663 * @param string $guid The guid of the item
1665 * @return array|boolean the origin owner of that post - or false
1666 * @throws \Exception
1668 private static function importerForGuid($guid)
1670 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1671 if (DBA::isResult($item)) {
1672 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1673 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1674 if (DBA::isResult($contact)) {
1682 * @brief Processes an incoming comment
1684 * @param array $importer Array of the importer user
1685 * @param string $sender The sender of the message
1686 * @param object $data The message object
1687 * @param string $xml The original XML of the message
1689 * @return int The message id of the generated comment or "false" if there was an error
1690 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1691 * @throws \ImagickException
1693 private static function receiveComment(array $importer, $sender, $data, $xml)
1695 $author = Strings::escapeTags(XML::unescape($data->author));
1696 $guid = Strings::escapeTags(XML::unescape($data->guid));
1697 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1698 $text = XML::unescape($data->text);
1700 if (isset($data->created_at)) {
1701 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1703 $created_at = DateTimeFormat::utcNow();
1706 if (isset($data->thread_parent_guid)) {
1707 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1708 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1713 $contact = self::allowedContactByHandle($importer, $sender, true);
1718 $message_id = self::messageExists($importer["uid"], $guid);
1723 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1724 if (!$parent_item) {
1728 $person = self::personByHandle($author);
1729 if (!is_array($person)) {
1730 Logger::log("unable to find author details");
1734 // Fetch the contact id - if we know this contact
1735 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1739 $datarray["uid"] = $importer["uid"];
1740 $datarray["contact-id"] = $author_contact["cid"];
1741 $datarray["network"] = $author_contact["network"];
1743 $datarray["author-link"] = $person["url"];
1744 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1746 $datarray["owner-link"] = $contact["url"];
1747 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1749 $datarray["guid"] = $guid;
1750 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1752 $datarray["verb"] = ACTIVITY_POST;
1753 $datarray["gravity"] = GRAVITY_COMMENT;
1755 if ($thr_uri != "") {
1756 $datarray["parent-uri"] = $thr_uri;
1758 $datarray["parent-uri"] = $parent_item["uri"];
1761 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1763 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1764 $datarray["source"] = $xml;
1766 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1768 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1770 $body = Markdown::toBBCode($text);
1772 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1774 self::fetchGuid($datarray);
1776 // If we are the origin of the parent we store the original data.
1777 // We notify our followers during the item storage.
1778 if ($parent_item["origin"]) {
1779 $datarray['diaspora_signed_text'] = json_encode($data);
1782 $message_id = Item::insert($datarray);
1784 if ($message_id <= 0) {
1789 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1790 if ($datarray['uid'] == 0) {
1791 Item::distribute($message_id, json_encode($data));
1799 * @brief processes and stores private messages
1801 * @param array $importer Array of the importer user
1802 * @param array $contact The contact of the message
1803 * @param object $data The message object
1804 * @param array $msg Array of the processed message, author handle and key
1805 * @param object $mesg The private message
1806 * @param array $conversation The conversation record to which this message belongs
1808 * @return bool "true" if it was successful
1809 * @throws \Exception
1811 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1813 $author = Strings::escapeTags(XML::unescape($data->author));
1814 $guid = Strings::escapeTags(XML::unescape($data->guid));
1815 $subject = Strings::escapeTags(XML::unescape($data->subject));
1817 // "diaspora_handle" is the element name from the old version
1818 // "author" is the element name from the new version
1819 if ($mesg->author) {
1820 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1821 } elseif ($mesg->diaspora_handle) {
1822 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1827 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1828 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1829 $msg_text = XML::unescape($mesg->text);
1830 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1832 if ($msg_conversation_guid != $guid) {
1833 Logger::log("message conversation guid does not belong to the current conversation.");
1837 $body = Markdown::toBBCode($msg_text);
1838 $message_uri = $msg_author.":".$msg_guid;
1840 $person = self::personByHandle($msg_author);
1844 if (DBA::exists('mail', ['guid' => $msg_guid, 'uid' => $importer["uid"]])) {
1845 Logger::log("duplicate message already delivered.", Logger::DEBUG);
1849 DBA::insert('mail', [
1850 'uid' => $importer['uid'],
1851 'guid' => $msg_guid,
1852 'convid' => $conversation['id'],
1853 'from-name' => $person['name'],
1854 'from-photo' => $person['photo'],
1855 'from-url' => $person['url'],
1856 'contact-id' => $contact['id'],
1857 'title' => $subject,
1861 'uri' => $message_uri,
1862 'parent-uri' => $author . ':' . $guid,
1863 'created' => $msg_created_at
1866 $message_id = DBA::lastInsertId();
1870 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1873 "type" => NOTIFY_MAIL,
1874 "notify_flags" => $importer["notify-flags"],
1875 "language" => $importer["language"],
1876 "to_name" => $importer["username"],
1877 "to_email" => $importer["email"],
1878 "uid" => $importer["uid"],
1879 "item" => ["id" => $message_id, "title" => $subject, "subject" => $subject, "body" => $body],
1880 "parent" => $conversation["id"],
1881 "source_name" => $person["name"],
1882 "source_link" => $person["url"],
1883 "source_photo" => $person["photo"],
1884 "verb" => ACTIVITY_POST,
1892 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1894 * @param array $importer Array of the importer user
1895 * @param array $msg Array of the processed message, author handle and key
1896 * @param object $data The message object
1898 * @return bool Success
1899 * @throws \Exception
1901 private static function receiveConversation(array $importer, $msg, $data)
1903 $author = Strings::escapeTags(XML::unescape($data->author));
1904 $guid = Strings::escapeTags(XML::unescape($data->guid));
1905 $subject = Strings::escapeTags(XML::unescape($data->subject));
1906 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1907 $participants = Strings::escapeTags(XML::unescape($data->participants));
1909 $messages = $data->message;
1911 if (!count($messages)) {
1912 Logger::log("empty conversation");
1916 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1921 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1922 if (!DBA::isResult($conversation)) {
1924 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1925 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1926 intval($importer["uid"]),
1928 DBA::escape($author),
1929 DBA::escape($created_at),
1930 DBA::escape(DateTimeFormat::utcNow()),
1931 DBA::escape($subject),
1932 DBA::escape($participants)
1935 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1938 if (!$conversation) {
1939 Logger::log("unable to create conversation.");
1943 foreach ($messages as $mesg) {
1944 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1951 * @brief Processes "like" messages
1953 * @param array $importer Array of the importer user
1954 * @param string $sender The sender of the message
1955 * @param object $data The message object
1957 * @return int The message id of the generated like or "false" if there was an error
1958 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1959 * @throws \ImagickException
1961 private static function receiveLike(array $importer, $sender, $data)
1963 $author = Strings::escapeTags(XML::unescape($data->author));
1964 $guid = Strings::escapeTags(XML::unescape($data->guid));
1965 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1966 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1967 $positive = Strings::escapeTags(XML::unescape($data->positive));
1969 // likes on comments aren't supported by Diaspora - only on posts
1970 // But maybe this will be supported in the future, so we will accept it.
1971 if (!in_array($parent_type, ["Post", "Comment"])) {
1975 $contact = self::allowedContactByHandle($importer, $sender, true);
1980 $message_id = self::messageExists($importer["uid"], $guid);
1985 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1986 if (!$parent_item) {
1990 $person = self::personByHandle($author);
1991 if (!is_array($person)) {
1992 Logger::log("unable to find author details");
1996 // Fetch the contact id - if we know this contact
1997 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1999 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2000 // We would accept this anyhow.
2001 if ($positive == "true") {
2002 $verb = ACTIVITY_LIKE;
2004 $verb = ACTIVITY_DISLIKE;
2009 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2011 $datarray["uid"] = $importer["uid"];
2012 $datarray["contact-id"] = $author_contact["cid"];
2013 $datarray["network"] = $author_contact["network"];
2015 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2016 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2018 $datarray["guid"] = $guid;
2019 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2021 $datarray["verb"] = $verb;
2022 $datarray["gravity"] = GRAVITY_ACTIVITY;
2023 $datarray["parent-uri"] = $parent_item["uri"];
2025 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2027 $datarray["body"] = $verb;
2029 // Diaspora doesn't provide a date for likes
2030 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2032 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2033 if ($parent_item["id"] != $parent_item["parent"]) {
2034 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2035 $origin = $toplevel["origin"];
2037 $origin = $parent_item["origin"];
2040 // If we are the origin of the parent we store the original data.
2041 // We notify our followers during the item storage.
2043 $datarray['diaspora_signed_text'] = json_encode($data);
2046 $message_id = Item::insert($datarray);
2048 if ($message_id <= 0) {
2053 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2054 if ($datarray['uid'] == 0) {
2055 Item::distribute($message_id, json_encode($data));
2063 * @brief Processes private messages
2065 * @param array $importer Array of the importer user
2066 * @param object $data The message object
2068 * @return bool Success?
2069 * @throws \Exception
2071 private static function receiveMessage(array $importer, $data)
2073 $author = Strings::escapeTags(XML::unescape($data->author));
2074 $guid = Strings::escapeTags(XML::unescape($data->guid));
2075 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2076 $text = XML::unescape($data->text);
2077 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2079 $contact = self::allowedContactByHandle($importer, $author, true);
2084 $conversation = null;
2086 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2087 $conversation = DBA::selectFirst('conv', [], $condition);
2089 if (!DBA::isResult($conversation)) {
2090 Logger::log("conversation not available.");
2094 $message_uri = $author.":".$guid;
2096 $person = self::personByHandle($author);
2098 Logger::log("unable to find author details");
2102 $body = Markdown::toBBCode($text);
2104 $body = self::replacePeopleGuid($body, $person["url"]);
2108 if (DBA::exists('mail', ['guid' => $guid, 'uid' => $importer["uid"]])) {
2109 Logger::log("duplicate message already delivered.", Logger::DEBUG);
2113 DBA::insert('mail', [
2114 'uid' => $importer['uid'],
2116 'convid' => $conversation['id'],
2117 'from-name' => $person['name'],
2118 'from-photo' => $person['photo'],
2119 'from-url' => $person['url'],
2120 'contact-id' => $contact['id'],
2121 'title' => $conversation['subject'],
2125 'uri' => $message_uri,
2126 'parent-uri' => $author.":".$conversation['guid'],
2127 'created' => $created_at
2130 $message_id = DBA::lastInsertId();
2134 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2137 "type" => NOTIFY_MAIL,
2138 "notify_flags" => $importer["notify-flags"],
2139 "language" => $importer["language"],
2140 "to_name" => $importer["username"],
2141 "to_email" => $importer["email"],
2142 "uid" => $importer["uid"],
2143 "item" => ["id" => $message_id, "title" => $conversation["subject"], "subject" => $conversation["subject"], "body" => $body],
2144 "parent" => $conversation["id"],
2145 "source_name" => $person["name"],
2146 "source_link" => $person["url"],
2147 "source_photo" => $person["photo"],
2148 "verb" => ACTIVITY_POST,
2156 * @brief Processes participations - unsupported by now
2158 * @param array $importer Array of the importer user
2159 * @param object $data The message object
2161 * @return bool always true
2162 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2163 * @throws \ImagickException
2165 private static function receiveParticipation(array $importer, $data)
2167 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2168 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2170 $contact_id = Contact::getIdForURL($author);
2172 Logger::log('Contact not found: '.$author);
2176 $person = self::personByHandle($author);
2177 if (!is_array($person)) {
2178 Logger::log("Person not found: ".$author);
2182 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2183 if (!DBA::isResult($item)) {
2184 Logger::log('Item not found, no origin or private: '.$parent_guid);
2188 $author_parts = explode('@', $author);
2189 if (isset($author_parts[1])) {
2190 $server = $author_parts[1];
2192 // Should never happen
2196 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2198 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2199 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2202 // Send all existing comments and likes to the requesting server
2203 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2204 while ($comment = Item::fetch($comments)) {
2205 if ($comment['id'] == $comment['parent']) {
2208 if ($comment['verb'] == ACTIVITY_POST) {
2209 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2211 $cmd = $comment['self'] ? 'like' : 'comment-import';
2213 Logger::log("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, Logger::DEBUG);
2214 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2216 DBA::close($comments);
2222 * @brief Processes photos - unneeded
2224 * @param array $importer Array of the importer user
2225 * @param object $data The message object
2227 * @return bool always true
2229 private static function receivePhoto(array $importer, $data)
2231 // There doesn't seem to be a reason for this function,
2232 // since the photo data is transmitted in the status message as well
2237 * @brief Processes poll participations - unssupported
2239 * @param array $importer Array of the importer user
2240 * @param object $data The message object
2242 * @return bool always true
2244 private static function receivePollParticipation(array $importer, $data)
2246 // We don't support polls by now
2251 * @brief Processes incoming profile updates
2253 * @param array $importer Array of the importer user
2254 * @param object $data The message object
2256 * @return bool Success
2257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2258 * @throws \ImagickException
2260 private static function receiveProfile(array $importer, $data)
2262 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2264 $contact = self::contactByHandle($importer["uid"], $author);
2269 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2270 $image_url = XML::unescape($data->image_url);
2271 $birthday = XML::unescape($data->birthday);
2272 $gender = XML::unescape($data->gender);
2273 $about = Markdown::toBBCode(XML::unescape($data->bio));
2274 $location = Markdown::toBBCode(XML::unescape($data->location));
2275 $searchable = (XML::unescape($data->searchable) == "true");
2276 $nsfw = (XML::unescape($data->nsfw) == "true");
2277 $tags = XML::unescape($data->tag_string);
2279 $tags = explode("#", $tags);
2282 foreach ($tags as $tag) {
2283 $tag = trim(strtolower($tag));
2289 $keywords = implode(", ", $keywords);
2291 $handle_parts = explode("@", $author);
2292 $nick = $handle_parts[0];
2295 $name = $handle_parts[0];
2298 if (preg_match("|^https?://|", $image_url) === 0) {
2299 $image_url = "http://".$handle_parts[1].$image_url;
2302 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2304 // Generic birthday. We don't know the timezone. The year is irrelevant.
2306 $birthday = str_replace("1000", "1901", $birthday);
2308 if ($birthday != "") {
2309 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2312 // this is to prevent multiple birthday notifications in a single year
2313 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2315 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2316 $birthday = $contact["bd"];
2319 $fields = ['name' => $name, 'location' => $location,
2320 'name-date' => DateTimeFormat::utcNow(),
2321 'about' => $about, 'gender' => $gender,
2322 'addr' => $author, 'nick' => $nick,
2323 'keywords' => $keywords];
2325 if (!empty($birthday)) {
2326 $fields['bd'] = $birthday;
2329 DBA::update('contact', $fields, ['id' => $contact['id']]);
2331 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2332 "photo" => $image_url, "name" => $name, "location" => $location,
2333 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2334 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2335 "hide" => !$searchable, "nsfw" => $nsfw];
2337 $gcid = GContact::update($gcontact);
2339 GContact::link($gcid, $importer["uid"], $contact["id"]);
2341 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2347 * @brief Processes incoming friend requests
2349 * @param array $importer Array of the importer user
2350 * @param array $contact The contact that send the request
2352 * @throws \Exception
2354 private static function receiveRequestMakeFriend(array $importer, array $contact)
2356 if ($contact["rel"] == Contact::SHARING) {
2359 ['rel' => Contact::FRIEND, 'writable' => true],
2360 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2366 * @brief Processes incoming sharing notification
2368 * @param array $importer Array of the importer user
2369 * @param object $data The message object
2371 * @return bool Success
2372 * @throws \Exception
2374 private static function receiveContactRequest(array $importer, $data)
2376 $author = XML::unescape($data->author);
2377 $recipient = XML::unescape($data->recipient);
2379 if (!$author || !$recipient) {
2383 // the current protocol version doesn't know these fields
2384 // That means that we will assume their existance
2385 if (isset($data->following)) {
2386 $following = (XML::unescape($data->following) == "true");
2391 if (isset($data->sharing)) {
2392 $sharing = (XML::unescape($data->sharing) == "true");
2397 $contact = self::contactByHandle($importer["uid"], $author);
2399 // perhaps we were already sharing with this person. Now they're sharing with us.
2400 // That makes us friends.
2403 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2404 self::receiveRequestMakeFriend($importer, $contact);
2406 // refetch the contact array
2407 $contact = self::contactByHandle($importer["uid"], $author);
2409 // If we are now friends, we are sending a share message.
2410 // Normally we needn't to do so, but the first message could have been vanished.
2411 if (in_array($contact["rel"], [Contact::FRIEND])) {
2412 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2413 if (DBA::isResult($user)) {
2414 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2415 self::sendShare($user, $contact);
2420 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2421 Contact::removeFollower($importer, $contact);
2426 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2427 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2429 } elseif (!$following && !$sharing) {
2430 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2432 } elseif (!$following && $sharing) {
2433 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2434 } elseif ($following && $sharing) {
2435 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2436 } elseif ($following && !$sharing) {
2437 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2440 $ret = self::personByHandle($author);
2442 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2443 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2447 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2450 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2451 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2452 intval($importer["uid"]),
2453 DBA::escape($ret["network"]),
2454 DBA::escape($ret["addr"]),
2455 DateTimeFormat::utcNow(),
2456 DBA::escape($ret["url"]),
2457 DBA::escape(Strings::normaliseLink($ret["url"])),
2458 DBA::escape($batch),
2459 DBA::escape($ret["name"]),
2460 DBA::escape($ret["nick"]),
2461 DBA::escape($ret["photo"]),
2462 DBA::escape($ret["pubkey"]),
2463 DBA::escape($ret["notify"]),
2464 DBA::escape($ret["poll"]),
2469 // find the contact record we just created
2471 $contact_record = self::contactByHandle($importer["uid"], $author);
2473 if (!$contact_record) {
2474 Logger::log("unable to locate newly created contact record.");
2478 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2480 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2482 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2484 if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
2485 Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2487 $hash = Strings::getRandomHex().(string)time(); // Generate a confirm_key
2490 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2491 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2492 intval($importer["uid"]),
2493 intval($contact_record["id"]),
2496 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2498 DBA::escape(DateTimeFormat::utcNow())
2501 // automatic friend approval
2503 Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2505 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2508 * technically they are sharing with us (Contact::SHARING),
2509 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2510 * we are going to change the relationship and make them a follower.
2512 if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
2513 $new_relation = Contact::FRIEND;
2514 } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
2515 $new_relation = Contact::SHARING;
2517 $new_relation = Contact::FOLLOWER;
2521 "UPDATE `contact` SET `rel` = %d,
2529 intval($new_relation),
2530 DBA::escape(DateTimeFormat::utcNow()),
2531 DBA::escape(DateTimeFormat::utcNow()),
2532 intval($contact_record["id"])
2535 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2536 if (DBA::isResult($user)) {
2537 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2538 self::sendShare($user, $contact_record);
2540 // Send the profile data, maybe it weren't transmitted before
2541 self::sendProfile($importer["uid"], [$contact_record]);
2549 * @brief Fetches a message with a given guid
2551 * @param string $guid message guid
2552 * @param string $orig_author handle of the original post
2553 * @return array The fetched item
2554 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2555 * @throws \ImagickException
2557 public static function originalItem($guid, $orig_author)
2560 Logger::log('Empty guid. Quitting.');
2564 // Do we already have this item?
2565 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2566 'author-name', 'author-link', 'author-avatar'];
2567 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2568 $item = Item::selectFirst($fields, $condition);
2570 if (DBA::isResult($item)) {
2571 Logger::log("reshared message ".$guid." already exists on system.");
2573 // Maybe it is already a reshared item?
2574 // Then refetch the content, if it is a reshare from a reshare.
2575 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2576 if (self::isReshare($item["body"], true)) {
2578 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2579 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2581 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2583 // Add OEmbed and other information to the body
2584 $item["body"] = add_page_info_to_body($item["body"], false, true);
2592 if (!DBA::isResult($item)) {
2593 if (empty($orig_author)) {
2594 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2598 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2599 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2600 $stored = self::storeByGuid($guid, $server);
2603 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2604 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2605 $stored = self::storeByGuid($guid, $server);
2609 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2610 'author-name', 'author-link', 'author-avatar'];
2611 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2612 $item = Item::selectFirst($fields, $condition);
2614 if (DBA::isResult($item)) {
2615 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2616 if (self::isReshare($item["body"], false)) {
2617 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2618 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2629 * @brief Processes a reshare message
2631 * @param array $importer Array of the importer user
2632 * @param object $data The message object
2633 * @param string $xml The original XML of the message
2635 * @return int the message id
2636 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2637 * @throws \ImagickException
2639 private static function receiveReshare(array $importer, $data, $xml)
2641 $author = Strings::escapeTags(XML::unescape($data->author));
2642 $guid = Strings::escapeTags(XML::unescape($data->guid));
2643 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2644 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2645 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2646 /// @todo handle unprocessed property "provider_display_name"
2647 $public = Strings::escapeTags(XML::unescape($data->public));
2649 $contact = self::allowedContactByHandle($importer, $author, false);
2654 $message_id = self::messageExists($importer["uid"], $guid);
2659 $original_item = self::originalItem($root_guid, $root_author);
2660 if (!$original_item) {
2664 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2668 $datarray["uid"] = $importer["uid"];
2669 $datarray["contact-id"] = $contact["id"];
2670 $datarray["network"] = Protocol::DIASPORA;
2672 $datarray["author-link"] = $contact["url"];
2673 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2675 $datarray["owner-link"] = $datarray["author-link"];
2676 $datarray["owner-id"] = $datarray["author-id"];
2678 $datarray["guid"] = $guid;
2679 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2681 $datarray["verb"] = ACTIVITY_POST;
2682 $datarray["gravity"] = GRAVITY_PARENT;
2684 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2685 $datarray["source"] = $xml;
2687 $prefix = share_header(
2688 $original_item["author-name"],
2689 $original_item["author-link"],
2690 $original_item["author-avatar"],
2691 $original_item["guid"],
2692 $original_item["created"],
2695 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2697 $datarray["tag"] = $original_item["tag"];
2698 $datarray["app"] = $original_item["app"];
2700 $datarray["plink"] = self::plink($author, $guid);
2701 $datarray["private"] = (($public == "false") ? 1 : 0);
2702 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2704 $datarray["object-type"] = $original_item["object-type"];
2706 self::fetchGuid($datarray);
2707 $message_id = Item::insert($datarray);
2709 self::sendParticipation($contact, $datarray);
2712 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2713 if ($datarray['uid'] == 0) {
2714 Item::distribute($message_id);
2723 * @brief Processes retractions
2725 * @param array $importer Array of the importer user
2726 * @param array $contact The contact of the item owner
2727 * @param object $data The message object
2729 * @return bool success
2730 * @throws \Exception
2732 private static function itemRetraction(array $importer, array $contact, $data)
2734 $author = Strings::escapeTags(XML::unescape($data->author));
2735 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2736 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2738 $person = self::personByHandle($author);
2739 if (!is_array($person)) {
2740 Logger::log("unable to find author detail for ".$author);
2744 if (empty($contact["url"])) {
2745 $contact["url"] = $person["url"];
2748 // Fetch items that are about to be deleted
2749 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2751 // When we receive a public retraction, we delete every item that we find.
2752 if ($importer['uid'] == 0) {
2753 $condition = ['guid' => $target_guid, 'deleted' => false];
2755 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2758 $r = Item::select($fields, $condition);
2759 if (!DBA::isResult($r)) {
2760 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2764 while ($item = Item::fetch($r)) {
2765 if (strstr($item['file'], '[')) {
2766 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2770 // Fetch the parent item
2771 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2773 // Only delete it if the parent author really fits
2774 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2775 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2779 Item::delete(['id' => $item['id']]);
2781 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2788 * @brief Receives retraction messages
2790 * @param array $importer Array of the importer user
2791 * @param string $sender The sender of the message
2792 * @param object $data The message object
2794 * @return bool Success
2795 * @throws \Exception
2797 private static function receiveRetraction(array $importer, $sender, $data)
2799 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2801 $contact = self::contactByHandle($importer["uid"], $sender);
2802 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2803 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2811 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2813 switch ($target_type) {
2818 case "StatusMessage":
2819 return self::itemRetraction($importer, $contact, $data);
2821 case "PollParticipation":
2823 // Currently unsupported
2827 Logger::log("Unknown target type ".$target_type);
2834 * @brief Receives status messages
2836 * @param array $importer Array of the importer user
2837 * @param SimpleXMLElement $data The message object
2838 * @param string $xml The original XML of the message
2840 * @return int The message id of the newly created item
2841 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2842 * @throws \ImagickException
2844 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2846 $author = Strings::escapeTags(XML::unescape($data->author));
2847 $guid = Strings::escapeTags(XML::unescape($data->guid));
2848 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2849 $public = Strings::escapeTags(XML::unescape($data->public));
2850 $text = XML::unescape($data->text);
2851 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2853 $contact = self::allowedContactByHandle($importer, $author, false);
2858 $message_id = self::messageExists($importer["uid"], $guid);
2864 if ($data->location) {
2865 foreach ($data->location->children() as $fieldname => $data) {
2866 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2870 $body = Markdown::toBBCode($text);
2874 // Attach embedded pictures to the body
2876 foreach ($data->photo as $photo) {
2877 $body = "[img]".XML::unescape($photo->remote_photo_path).
2878 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2881 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2883 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2885 // Add OEmbed and other information to the body
2886 if (!self::isRedmatrix($contact["url"])) {
2887 $body = add_page_info_to_body($body, false, true);
2891 /// @todo enable support for polls
2892 //if ($data->poll) {
2893 // foreach ($data->poll AS $poll)
2898 /// @todo enable support for events
2900 $datarray["uid"] = $importer["uid"];
2901 $datarray["contact-id"] = $contact["id"];
2902 $datarray["network"] = Protocol::DIASPORA;
2904 $datarray["author-link"] = $contact["url"];
2905 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2907 $datarray["owner-link"] = $datarray["author-link"];
2908 $datarray["owner-id"] = $datarray["author-id"];
2910 $datarray["guid"] = $guid;
2911 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2913 $datarray["verb"] = ACTIVITY_POST;
2914 $datarray["gravity"] = GRAVITY_PARENT;
2916 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2917 $datarray["source"] = $xml;
2919 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2921 if ($provider_display_name != "") {
2922 $datarray["app"] = $provider_display_name;
2925 $datarray["plink"] = self::plink($author, $guid);
2926 $datarray["private"] = (($public == "false") ? 1 : 0);
2927 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2929 if (isset($address["address"])) {
2930 $datarray["location"] = $address["address"];
2933 if (isset($address["lat"]) && isset($address["lng"])) {
2934 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2937 self::fetchGuid($datarray);
2938 $message_id = Item::insert($datarray);
2940 self::sendParticipation($contact, $datarray);
2943 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2944 if ($datarray['uid'] == 0) {
2945 Item::distribute($message_id);
2953 /* ************************************************************************************** *
2954 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2955 * ************************************************************************************** */
2958 * @brief returnes the handle of a contact
2960 * @param array $contact contact array
2962 * @return string the handle in the format user@domain.tld
2963 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2965 private static function myHandle(array $contact)
2967 if (!empty($contact["addr"])) {
2968 return $contact["addr"];
2971 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2972 // So - just in case - we build the the address here.
2973 if ($contact["nickname"] != "") {
2974 $nick = $contact["nickname"];
2976 $nick = $contact["nick"];
2979 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2984 * @brief Creates the data for a private message in the new format
2986 * @param string $msg The message that is to be transmitted
2987 * @param array $user The record of the sender
2988 * @param array $contact Target of the communication
2989 * @param string $prvkey The private key of the sender
2990 * @param string $pubkey The public key of the receiver
2992 * @return string The encrypted data
2993 * @throws \Exception
2995 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2997 Logger::log("Message: ".$msg, Logger::DATA);
2999 // without a public key nothing will work
3001 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3005 $aes_key = openssl_random_pseudo_bytes(32);
3006 $b_aes_key = base64_encode($aes_key);
3007 $iv = openssl_random_pseudo_bytes(16);
3008 $b_iv = base64_encode($iv);
3010 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3012 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3014 $encrypted_key_bundle = "";
3015 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3017 $json_object = json_encode(
3018 ["aes_key" => base64_encode($encrypted_key_bundle),
3019 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3022 return $json_object;
3026 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3028 * @param string $msg The message that is to be transmitted
3029 * @param array $user The record of the sender
3031 * @return string The envelope
3032 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3034 public static function buildMagicEnvelope($msg, array $user)
3036 $b64url_data = Strings::base64UrlEncode($msg);
3037 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3039 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3040 $type = "application/xml";
3041 $encoding = "base64url";
3042 $alg = "RSA-SHA256";
3043 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3045 // Fallback if the private key wasn't transmitted in the expected field
3046 if ($user['uprvkey'] == "") {
3047 $user['uprvkey'] = $user['prvkey'];
3050 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3051 $sig = Strings::base64UrlEncode($signature);
3053 $xmldata = ["me:env" => ["me:data" => $data,
3054 "@attributes" => ["type" => $type],
3055 "me:encoding" => $encoding,
3058 "@attributes2" => ["key_id" => $key_id]]];
3060 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3062 return XML::fromArray($xmldata, $xml, false, $namespaces);
3066 * @brief Create the envelope for a message
3068 * @param string $msg The message that is to be transmitted
3069 * @param array $user The record of the sender
3070 * @param array $contact Target of the communication
3071 * @param string $prvkey The private key of the sender
3072 * @param string $pubkey The public key of the receiver
3073 * @param bool $public Is the message public?
3075 * @return string The message that will be transmitted to other servers
3076 * @throws \Exception
3078 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3080 // The message is put into an envelope with the sender's signature
3081 $envelope = self::buildMagicEnvelope($msg, $user);
3083 // Private messages are put into a second envelope, encrypted with the receivers public key
3085 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3092 * @brief Creates a signature for a message
3094 * @param array $owner the array of the owner of the message
3095 * @param array $message The message that is to be signed
3097 * @return string The signature
3099 private static function signature($owner, $message)
3102 unset($sigmsg["author_signature"]);
3103 unset($sigmsg["parent_author_signature"]);
3105 $signed_text = implode(";", $sigmsg);
3107 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3111 * @brief Transmit a message to a target server
3113 * @param array $owner the array of the item owner
3114 * @param array $contact Target of the communication
3115 * @param string $envelope The message that is to be transmitted
3116 * @param bool $public_batch Is it a public post?
3117 * @param bool $queue_run Is the transmission called from the queue?
3118 * @param string $guid message guid
3120 * @param bool $no_queue
3121 * @return int Result of the transmission
3122 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3123 * @throws \ImagickException
3125 public static function transmit(array $owner, array $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3127 $enabled = intval(Config::get("system", "diaspora_enabled"));
3132 $logid = Strings::getRandomHex(4);
3134 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3136 // We always try to use the data from the fcontact table.
3137 // This is important for transmitting data to Friendica servers.
3138 if (!empty($contact['addr'])) {
3139 $fcontact = self::personByHandle($contact['addr']);
3140 if (!empty($fcontact)) {
3141 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3146 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3150 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3152 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3155 if (!intval(Config::get("system", "diaspora_test"))) {
3156 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3158 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3159 $return_code = $postResult->getReturnCode();
3161 Logger::log("test_mode");
3166 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3168 if (!$return_code || (($return_code == 503) && (stristr($postResult->getHeader(), "retry-after")))) {
3169 if (!$no_queue && !empty($contact['contact-type']) && ($contact['contact-type'] != Contact::TYPE_RELAY)) {
3170 Logger::log("queue message");
3171 // queue message for redelivery
3172 Queue::add($contact["id"], Protocol::DIASPORA, $envelope, $public_batch, $guid);
3175 // The message could not be delivered. We mark the contact as "dead"
3176 Contact::markForArchival($contact);
3177 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3178 // We successfully delivered a message, the contact is alive
3179 Contact::unmarkForArchival($contact);
3182 return $return_code ? $return_code : -1;
3187 * @brief Build the post xml
3189 * @param string $type The message type
3190 * @param array $message The message data
3192 * @return string The post XML
3194 public static function buildPostXml($type, $message)
3196 $data = [$type => $message];
3198 return XML::fromArray($data, $xml);
3202 * @brief Builds and transmit messages
3204 * @param array $owner the array of the item owner
3205 * @param array $contact Target of the communication
3206 * @param string $type The message type
3207 * @param array $message The message data
3208 * @param bool $public_batch Is it a public post?
3209 * @param string $guid message guid
3210 * @param bool $spool Should the transmission be spooled or transmitted?
3212 * @return int Result of the transmission
3213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3214 * @throws \ImagickException
3216 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3218 $msg = self::buildPostXml($type, $message);
3220 Logger::log('message: '.$msg, Logger::DATA);
3221 Logger::log('send guid '.$guid, Logger::DEBUG);
3223 // Fallback if the private key wasn't transmitted in the expected field
3224 if (empty($owner['uprvkey'])) {
3225 $owner['uprvkey'] = $owner['prvkey'];
3228 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3231 Queue::add($contact['id'], Protocol::DIASPORA, $envelope, $public_batch, $guid);
3234 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3237 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3239 return $return_code;
3243 * @brief sends a participation (Used to get all further updates)
3245 * @param array $contact Target of the communication
3246 * @param array $item Item array
3248 * @return int The result of the transmission
3249 * @throws \Exception
3251 private static function sendParticipation(array $contact, array $item)
3253 // Don't send notifications for private postings
3254 if ($item['private']) {
3258 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3260 $result = Cache::get($cachekey);
3261 if (!is_null($result)) {
3265 // Fetch some user id to have a valid handle to transmit the participation.
3266 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3267 // If the item belongs to a user, we take this user id.
3268 if ($item['uid'] == 0) {
3269 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3270 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3271 $owner = User::getOwnerDataById($first_user['uid']);
3273 $owner = User::getOwnerDataById($item['uid']);
3276 $author = self::myHandle($owner);
3278 $message = ["author" => $author,
3279 "guid" => System::createUUID(),
3280 "parent_type" => "Post",
3281 "parent_guid" => $item["guid"]];
3283 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3285 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3286 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3288 return self::buildAndTransmit($owner, $contact, "participation", $message);
3292 * @brief sends an account migration
3294 * @param array $owner the array of the item owner
3295 * @param array $contact Target of the communication
3296 * @param int $uid User ID
3298 * @return int The result of the transmission
3299 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3300 * @throws \ImagickException
3302 public static function sendAccountMigration(array $owner, array $contact, $uid)
3304 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3305 $profile = self::createProfileData($uid);
3307 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3308 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3310 $message = ["author" => $old_handle,
3311 "profile" => $profile,
3312 "signature" => $signature];
3314 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3316 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3320 * @brief Sends a "share" message
3322 * @param array $owner the array of the item owner
3323 * @param array $contact Target of the communication
3325 * @return int The result of the transmission
3326 * @throws \Exception
3328 public static function sendShare(array $owner, array $contact)
3331 * @todo support the different possible combinations of "following" and "sharing"
3332 * Currently, Diaspora only interprets the "sharing" field
3334 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3338 switch ($contact["rel"]) {
3339 case Contact::FRIEND:
3343 case Contact::SHARING:
3347 case Contact::FOLLOWER:
3353 $message = ["author" => self::myHandle($owner),
3354 "recipient" => $contact["addr"],
3355 "following" => "true",
3356 "sharing" => "true"];
3358 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3360 return self::buildAndTransmit($owner, $contact, "contact", $message);
3364 * @brief sends an "unshare"
3366 * @param array $owner the array of the item owner
3367 * @param array $contact Target of the communication
3369 * @return int The result of the transmission
3370 * @throws \Exception
3372 public static function sendUnshare(array $owner, array $contact)
3374 $message = ["author" => self::myHandle($owner),
3375 "recipient" => $contact["addr"],
3376 "following" => "false",
3377 "sharing" => "false"];
3379 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3381 return self::buildAndTransmit($owner, $contact, "contact", $message);
3385 * @brief Checks a message body if it is a reshare
3387 * @param string $body The message body that is to be check
3388 * @param bool $complete Should it be a complete check or a simple check?
3390 * @return array|bool Reshare details or "false" if no reshare
3391 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3392 * @throws \ImagickException
3394 public static function isReshare($body, $complete = true)
3396 $body = trim($body);
3398 // Skip if it isn't a pure repeated messages
3399 // Does it start with a share?
3400 if ((strpos($body, "[share") > 0) && $complete) {
3404 // Does it end with a share?
3405 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3409 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3410 // Skip if there is no shared message in there
3411 if ($body == $attributes) {
3415 // If we don't do the complete check we quit here
3418 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3419 if (!empty($matches[1])) {
3420 $guid = $matches[1];
3423 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3424 if (!empty($matches[1])) {
3425 $guid = $matches[1];
3428 if (($guid != "") && $complete) {
3429 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3430 $item = Item::selectFirst(['contact-id'], $condition);
3431 if (DBA::isResult($item)) {
3433 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3434 $ret["root_guid"] = $guid;
3436 } elseif ($complete) {
3437 // We are resharing something that isn't a DFRN or Diaspora post.
3438 // So we have to return "false" on "$complete" to not trigger a reshare.
3441 } elseif (($guid == "") && $complete) {
3445 $ret["root_guid"] = $guid;
3448 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3449 if (!empty($matches[1])) {
3450 $profile = $matches[1];
3453 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3454 if (!empty($matches[1])) {
3455 $profile = $matches[1];
3460 if ($profile != "") {
3461 if (Contact::getIdForURL($profile)) {
3462 $author = Contact::getDetailsByURL($profile);
3463 $ret["root_handle"] = $author['addr'];
3467 if (empty($ret) && !$complete) {
3475 * @brief Create an event array
3477 * @param integer $event_id The id of the event
3479 * @return array with event data
3480 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3482 private static function buildEvent($event_id)
3484 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3485 if (!DBA::isResult($r)) {
3493 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3494 if (!DBA::isResult($r)) {
3500 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3501 if (!DBA::isResult($r)) {
3507 $eventdata['author'] = self::myHandle($owner);
3509 if ($event['guid']) {
3510 $eventdata['guid'] = $event['guid'];
3513 $mask = DateTimeFormat::ATOM;
3515 /// @todo - establish "all day" events in Friendica
3516 $eventdata["all_day"] = "false";
3518 $eventdata['timezone'] = 'UTC';
3519 if (!$event['adjust'] && $user['timezone']) {
3520 $eventdata['timezone'] = $user['timezone'];
3523 if ($event['start']) {
3524 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3526 if ($event['finish'] && !$event['nofinish']) {
3527 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3529 if ($event['summary']) {
3530 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3532 if ($event['desc']) {
3533 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3535 if ($event['location']) {
3536 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3537 $coord = Map::getCoordinates($event['location']);
3540 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3541 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3542 $location["lat"] = $coord['lat'];
3543 $location["lng"] = $coord['lon'];
3545 $location["lat"] = 0;
3546 $location["lng"] = 0;
3548 $eventdata['location'] = $location;
3555 * @brief Create a post (status message or reshare)
3557 * @param array $item The item that will be exported
3558 * @param array $owner the array of the item owner
3561 * 'type' -> Message type ("status_message" or "reshare")
3562 * 'message' -> Array of XML elements of the status
3563 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3564 * @throws \ImagickException
3566 public static function buildStatus(array $item, array $owner)
3568 $cachekey = "diaspora:buildStatus:".$item['guid'];
3570 $result = Cache::get($cachekey);
3571 if (!is_null($result)) {
3575 $myaddr = self::myHandle($owner);
3577 $public = ($item["private"] ? "false" : "true");
3579 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3581 // Detect a share element and do a reshare
3582 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3583 $message = ["author" => $myaddr,
3584 "guid" => $item["guid"],
3585 "created_at" => $created,
3586 "root_author" => $ret["root_handle"],
3587 "root_guid" => $ret["root_guid"],
3588 "provider_display_name" => $item["app"],
3589 "public" => $public];
3593 $title = $item["title"];
3594 $body = $item["body"];
3596 if ($item['author-link'] != $item['owner-link']) {
3597 require_once 'mod/share.php';
3598 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3599 "", $item['created'], $item['plink']) . $body . '[/share]';
3602 // convert to markdown
3603 $body = html_entity_decode(BBCode::toMarkdown($body));
3606 if (strlen($title)) {
3607 $body = "## ".html_entity_decode($title)."\n\n".$body;
3610 if ($item["attach"]) {
3611 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3613 $body .= "\n".L10n::t("Attachments:")."\n";
3614 foreach ($matches as $mtch) {
3615 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3622 if ($item["location"] != "")
3623 $location["address"] = $item["location"];
3625 if ($item["coord"] != "") {
3626 $coord = explode(" ", $item["coord"]);
3627 $location["lat"] = $coord[0];
3628 $location["lng"] = $coord[1];
3631 $message = ["author" => $myaddr,
3632 "guid" => $item["guid"],
3633 "created_at" => $created,
3634 "public" => $public,
3636 "provider_display_name" => $item["app"],
3637 "location" => $location];
3639 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3640 if (!isset($location["lat"]) || !isset($location["lng"])) {
3641 unset($message["location"]);
3644 if ($item['event-id'] > 0) {
3645 $event = self::buildEvent($item['event-id']);
3646 if (count($event)) {
3647 $message['event'] = $event;
3649 if (!empty($event['location']['address']) &&
3650 !empty($event['location']['lat']) &&
3651 !empty($event['location']['lng'])) {
3652 $message['location'] = $event['location'];
3655 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3656 // $message['text'] = '';
3660 $type = "status_message";
3663 $msg = ["type" => $type, "message" => $message];
3665 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3670 private static function prependParentAuthorMention($body, $profile_url)
3672 $profile = Contact::getDetailsByURL($profile_url);
3673 if (!empty($profile['addr'])
3674 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3675 && !strstr($body, $profile['addr'])
3676 && !strstr($body, $profile_url)
3678 $body = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url] ' . $body;
3685 * @brief Sends a post
3687 * @param array $item The item that will be exported
3688 * @param array $owner the array of the item owner
3689 * @param array $contact Target of the communication
3690 * @param bool $public_batch Is it a public post?
3692 * @return int The result of the transmission
3693 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3694 * @throws \ImagickException
3696 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3698 $status = self::buildStatus($item, $owner);
3700 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3704 * @brief Creates a "like" object
3706 * @param array $item The item that will be exported
3707 * @param array $owner the array of the item owner
3709 * @return array The data for a "like"
3710 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3712 private static function constructLike(array $item, array $owner)
3714 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3715 if (!DBA::isResult($parent)) {
3719 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3721 if ($item['verb'] === ACTIVITY_LIKE) {
3723 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3724 $positive = "false";
3727 return(["author" => self::myHandle($owner),
3728 "guid" => $item["guid"],
3729 "parent_guid" => $parent["guid"],
3730 "parent_type" => $target_type,
3731 "positive" => $positive,
3732 "author_signature" => ""]);
3736 * @brief Creates an "EventParticipation" object
3738 * @param array $item The item that will be exported
3739 * @param array $owner the array of the item owner
3741 * @return array The data for an "EventParticipation"
3742 * @throws \Exception
3744 private static function constructAttend(array $item, array $owner)
3746 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3747 if (!DBA::isResult($parent)) {
3751 switch ($item['verb']) {
3752 case ACTIVITY_ATTEND:
3753 $attend_answer = 'accepted';
3755 case ACTIVITY_ATTENDNO:
3756 $attend_answer = 'declined';
3758 case ACTIVITY_ATTENDMAYBE:
3759 $attend_answer = 'tentative';
3762 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3766 return(["author" => self::myHandle($owner),
3767 "guid" => $item["guid"],
3768 "parent_guid" => $parent["guid"],
3769 "status" => $attend_answer,
3770 "author_signature" => ""]);
3774 * @brief Creates the object for a comment
3776 * @param array $item The item that will be exported
3777 * @param array $owner the array of the item owner
3779 * @return array The data for a comment
3780 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3782 private static function constructComment(array $item, array $owner)
3784 $cachekey = "diaspora:constructComment:".$item['guid'];
3786 $result = Cache::get($cachekey);
3787 if (!is_null($result)) {
3791 $parent = Item::selectFirst(['guid', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3792 if (!DBA::isResult($parent)) {
3796 $body = $item["body"];
3798 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
3799 $body = self::prependParentAuthorMention($body, $parent['author-link']);
3802 $text = html_entity_decode(BBCode::toMarkdown($body));
3803 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3805 $comment = ["author" => self::myHandle($owner),
3806 "guid" => $item["guid"],
3807 "created_at" => $created,
3808 "parent_guid" => $parent["guid"],
3810 "author_signature" => ""];
3812 // Send the thread parent guid only if it is a threaded comment
3813 if ($item['thr-parent'] != $item['parent-uri']) {
3814 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3817 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3823 * @brief Send a like or a comment
3825 * @param array $item The item that will be exported
3826 * @param array $owner the array of the item owner
3827 * @param array $contact Target of the communication
3828 * @param bool $public_batch Is it a public post?
3830 * @return int The result of the transmission
3831 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3832 * @throws \ImagickException
3834 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3836 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3837 $message = self::constructAttend($item, $owner);
3838 $type = "event_participation";
3839 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3840 $message = self::constructLike($item, $owner);
3842 } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW])) {
3843 $message = self::constructComment($item, $owner);
3847 if (empty($message)) {
3851 $message["author_signature"] = self::signature($owner, $message);
3853 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3857 * @brief Creates a message from a signature record entry
3859 * @param array $item The item that will be exported
3860 * @return array The message
3862 private static function messageFromSignature(array $item)
3864 // Split the signed text
3865 $signed_parts = explode(";", $item['signed_text']);
3867 if ($item["deleted"]) {
3868 $message = ["author" => $item['signer'],
3869 "target_guid" => $signed_parts[0],
3870 "target_type" => $signed_parts[1]];
3871 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3872 $message = ["author" => $signed_parts[4],
3873 "guid" => $signed_parts[1],
3874 "parent_guid" => $signed_parts[3],
3875 "parent_type" => $signed_parts[2],
3876 "positive" => $signed_parts[0],
3877 "author_signature" => $item['signature'],
3878 "parent_author_signature" => ""];
3880 // Remove the comment guid
3881 $guid = array_shift($signed_parts);
3883 // Remove the parent guid
3884 $parent_guid = array_shift($signed_parts);
3886 // Remove the handle
3887 $handle = array_pop($signed_parts);
3890 "author" => $handle,
3892 "parent_guid" => $parent_guid,
3893 "text" => implode(";", $signed_parts),
3894 "author_signature" => $item['signature'],
3895 "parent_author_signature" => ""
3902 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3904 * @param array $item The item that will be exported
3905 * @param array $owner the array of the item owner
3906 * @param array $contact Target of the communication
3907 * @param bool $public_batch Is it a public post?
3909 * @return int The result of the transmission
3910 * @throws \Exception
3912 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3914 if ($item["deleted"]) {
3915 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3916 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3922 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3924 // Old way - is used by the internal Friendica functions
3925 /// @todo Change all signatur storing functions to the new format
3926 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
3927 $message = self::messageFromSignature($item);
3929 $msg = json_decode($item['signed_text'], true);
3932 if (is_array($msg)) {
3933 foreach ($msg as $field => $data) {
3934 if (!$item["deleted"]) {
3935 if ($field == "diaspora_handle") {
3938 if ($field == "target_type") {
3939 $field = "parent_type";
3943 $message[$field] = $data;
3946 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3950 $message["parent_author_signature"] = self::signature($owner, $message);
3952 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
3954 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3958 * @brief Sends a retraction (deletion) of a message, like or comment
3960 * @param array $item The item that will be exported
3961 * @param array $owner the array of the item owner
3962 * @param array $contact Target of the communication
3963 * @param bool $public_batch Is it a public post?
3964 * @param bool $relay Is the retraction transmitted from a relay?
3966 * @return int The result of the transmission
3967 * @throws \Exception
3969 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3971 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3973 $msg_type = "retraction";
3975 if ($item['id'] == $item['parent']) {
3976 $target_type = "Post";
3977 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3978 $target_type = "Like";
3980 $target_type = "Comment";
3983 $message = ["author" => $itemaddr,
3984 "target_guid" => $item['guid'],
3985 "target_type" => $target_type];
3987 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
3989 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3993 * @brief Sends a mail
3995 * @param array $item The item that will be exported
3996 * @param array $owner The owner
3997 * @param array $contact Target of the communication
3999 * @return int The result of the transmission
4000 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4001 * @throws \ImagickException
4003 public static function sendMail(array $item, array $owner, array $contact)
4005 $myaddr = self::myHandle($owner);
4007 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4008 if (!DBA::isResult($cnv)) {
4009 Logger::log("conversation not found.");
4013 $body = BBCode::toMarkdown($item["body"]);
4014 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4017 "author" => $myaddr,
4018 "guid" => $item["guid"],
4019 "conversation_guid" => $cnv["guid"],
4021 "created_at" => $created,
4024 if ($item["reply"]) {
4029 "author" => $cnv["creator"],
4030 "guid" => $cnv["guid"],
4031 "subject" => $cnv["subject"],
4032 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4033 "participants" => $cnv["recips"],
4037 $type = "conversation";
4040 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4044 * @brief Split a name into first name and last name
4046 * @param string $name The name
4048 * @return array The array with "first" and "last"
4050 public static function splitName($name) {
4051 $name = trim($name);
4053 // Is the name longer than 64 characters? Then cut the rest of it.
4054 if (strlen($name) > 64) {
4055 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4056 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4058 $name = substr($name, 0, 64);
4062 // Take the first word as first name
4063 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4064 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4065 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4066 return ['first' => $first, 'last' => $last];
4069 // Take the last word as last name
4070 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4071 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4073 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4074 return ['first' => $first, 'last' => $last];
4077 // Take the first 32 characters if there is no space in the first 32 characters
4078 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4079 $first = substr($name, 0, 32);
4080 $last = substr($name, 32);
4081 return ['first' => $first, 'last' => $last];
4084 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4085 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4087 // Check if the last name is longer than 32 characters
4088 if (strlen($last) > 32) {
4089 if (strpos($last, ' ') <= 32) {
4090 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4092 $last = substr($last, 0, 32);
4096 return ['first' => $first, 'last' => $last];
4100 * @brief Create profile data
4102 * @param int $uid The user id
4104 * @return array The profile data
4105 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4107 private static function createProfileData($uid)
4110 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4112 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4113 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4114 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4123 $handle = $profile["addr"];
4125 $split_name = self::splitName($profile['name']);
4126 $first = $split_name['first'];
4127 $last = $split_name['last'];
4129 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4130 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4131 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4132 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4138 if ($searchable === 'true') {
4141 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4142 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4146 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4149 $about = $profile['about'];
4150 $about = strip_tags(BBCode::convert($about));
4152 $location = Profile::formatLocation($profile);
4154 if ($profile['pub_keywords']) {
4155 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4156 $kw = str_replace(' ', ' ', $kw);
4157 $arr = explode(' ', $kw);
4159 for ($x = 0; $x < 5; $x ++) {
4160 if (!empty($arr[$x])) {
4161 $tags .= '#'. trim($arr[$x]) .' ';
4166 $tags = trim($tags);
4169 return ["author" => $handle,
4170 "first_name" => $first,
4171 "last_name" => $last,
4172 "image_url" => $large,
4173 "image_url_medium" => $medium,
4174 "image_url_small" => $small,
4176 "gender" => $profile['gender'],
4178 "location" => $location,
4179 "searchable" => $searchable,
4181 "tag_string" => $tags];
4185 * @brief Sends profile data
4187 * @param int $uid The user id
4188 * @param bool $recips optional, default false
4190 * @throws \Exception
4192 public static function sendProfile($uid, $recips = false)
4198 $owner = User::getOwnerDataById($uid);
4205 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4206 AND `uid` = %d AND `rel` != %d",
4207 DBA::escape(Protocol::DIASPORA),
4209 intval(Contact::SHARING)
4217 $message = self::createProfileData($uid);
4219 foreach ($recips as $recip) {
4220 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4221 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4226 * @brief Creates the signature for likes that are created on our system
4228 * @param integer $uid The user of that comment
4229 * @param array $item Item array
4231 * @return array Signed content
4232 * @throws \Exception
4234 public static function createLikeSignature($uid, array $item)
4236 $owner = User::getOwnerDataById($uid);
4237 if (empty($owner)) {
4238 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4242 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4246 $message = self::constructLike($item, $owner);
4247 if ($message === false) {
4251 $message["author_signature"] = self::signature($owner, $message);
4257 * @brief Creates the signature for Comments that are created on our system
4259 * @param integer $uid The user of that comment
4260 * @param array $item Item array
4262 * @return array Signed content
4263 * @throws \Exception
4265 public static function createCommentSignature($uid, array $item)
4267 $owner = User::getOwnerDataById($uid);
4268 if (empty($owner)) {
4269 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4273 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4274 $item['thr-parent'] = $item['parent-uri'];
4276 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4277 if (!DBA::isResult($parent)) {
4281 $item['parent-uri'] = $parent['parent-uri'];
4283 $message = self::constructComment($item, $owner);
4284 if ($message === false) {
4288 $message["author_signature"] = self::signature($owner, $message);