3 * @file src/Protocol/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "validPosting" and interpret only the new protocol.
11 namespace Friendica\Protocol;
13 use Friendica\Content\Feature;
14 use Friendica\Content\Text\BBCode;
15 use Friendica\Content\Text\Markdown;
16 use Friendica\Core\Cache;
17 use Friendica\Core\Config;
18 use Friendica\Core\L10n;
19 use Friendica\Core\Logger;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Conversation;
27 use Friendica\Model\GContact;
28 use Friendica\Model\Group;
29 use Friendica\Model\Item;
30 use Friendica\Model\Mail;
31 use Friendica\Model\Profile;
32 use Friendica\Model\User;
33 use Friendica\Network\Probe;
34 use Friendica\Util\Crypto;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Map;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
39 use Friendica\Util\XML;
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', 'protocol', '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`, `contact`.`protocol`,
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['protocol'])) {
228 $contact['protocol'] = $contact['network'];
231 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
232 $contact['batch'] = $contact['fbatch'];
234 unset($contact['fbatch']);
237 foreach ($contacts as $entry) {
238 if ($entry['batch'] == $contact['batch']) {
244 $contacts[] = $contact;
253 * @brief repairs a signature that was double encoded
255 * The function is unused at the moment. It was copied from the old implementation.
257 * @param string $signature The signature
258 * @param string $handle The handle of the signature owner
259 * @param integer $level This value is only set inside this function to avoid endless loops
261 * @return string the repaired signature
264 private static function repairSignature($signature, $handle = "", $level = 1)
266 if ($signature == "") {
270 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
271 $signature = base64_decode($signature);
272 Logger::log("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, Logger::DEBUG);
274 // Do a recursive call to be able to fix even multiple levels
276 $signature = self::repairSignature($signature, $handle, ++$level);
284 * @brief verify the envelope and return the verified data
286 * @param string $envelope The magic envelope
288 * @return string verified data
289 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
290 * @throws \ImagickException
292 private static function verifyMagicEnvelope($envelope)
294 $basedom = XML::parseString($envelope);
296 if (!is_object($basedom)) {
297 Logger::log("Envelope is no XML file");
301 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
303 if (sizeof($children) == 0) {
304 Logger::log("XML has no children");
310 $data = Strings::base64UrlDecode($children->data);
311 $type = $children->data->attributes()->type[0];
313 $encoding = $children->encoding;
315 $alg = $children->alg;
317 $sig = Strings::base64UrlDecode($children->sig);
318 $key_id = $children->sig->attributes()->key_id[0];
320 $handle = Strings::base64UrlDecode($key_id);
323 $b64url_data = Strings::base64UrlEncode($data);
324 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
326 $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
329 Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
333 $key = self::key($handle);
335 Logger::log("Couldn't get a key for handle " . $handle . ". Discarding.");
339 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
341 Logger::log('Message from ' . $handle . ' did not verify. Discarding.');
349 * @brief encrypts data via AES
351 * @param string $key The AES key
352 * @param string $iv The IV (is used for CBC encoding)
353 * @param string $data The data that is to be encrypted
355 * @return string encrypted data
357 private static function aesEncrypt($key, $iv, $data)
359 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
363 * @brief decrypts data via AES
365 * @param string $key The AES key
366 * @param string $iv The IV (is used for CBC encoding)
367 * @param string $encrypted The encrypted data
369 * @return string decrypted data
371 private static function aesDecrypt($key, $iv, $encrypted)
373 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
377 * @brief: Decodes incoming Diaspora message in the new format
379 * @param array $importer Array of the importer user
380 * @param string $raw raw post message
381 * @param boolean $no_exit Don't do an http exit on error
384 * 'message' -> decoded Diaspora XML message
385 * 'author' -> author diaspora handle
386 * 'key' -> author public key (converted to pkcs#8)
387 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
388 * @throws \ImagickException
390 public static function decodeRaw(array $importer, $raw, $no_exit = false)
392 $data = json_decode($raw);
394 // Is it a private post? Then decrypt the outer Salmon
395 if (is_object($data)) {
396 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
397 $ciphertext = base64_decode($data->encrypted_magic_envelope);
399 $outer_key_bundle = '';
400 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
401 $j_outer_key_bundle = json_decode($outer_key_bundle);
403 if (!is_object($j_outer_key_bundle)) {
404 Logger::log('Outer Salmon did not verify. Discarding.');
408 throw new \Friendica\Network\HTTPException\BadRequestException();
412 $outer_iv = base64_decode($j_outer_key_bundle->iv);
413 $outer_key = base64_decode($j_outer_key_bundle->key);
415 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
420 $basedom = XML::parseString($xml);
422 if (!is_object($basedom)) {
423 Logger::log('Received data does not seem to be an XML. Discarding. '.$xml);
427 throw new \Friendica\Network\HTTPException\BadRequestException();
431 $base = $basedom->children(NAMESPACE_SALMON_ME);
433 // Not sure if this cleaning is needed
434 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
436 // Build the signed data
437 $type = $base->data[0]->attributes()->type[0];
438 $encoding = $base->encoding;
440 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
442 // This is the signature
443 $signature = Strings::base64UrlDecode($base->sig);
445 // Get the senders' public key
446 $key_id = $base->sig[0]->attributes()->key_id[0];
447 $author_addr = base64_decode($key_id);
448 if ($author_addr == '') {
449 Logger::log('No author could be decoded. Discarding. Message: ' . $xml);
453 throw new \Friendica\Network\HTTPException\BadRequestException();
457 $key = self::key($author_addr);
459 Logger::log("Couldn't get a key for handle " . $author_addr . ". Discarding.");
463 throw new \Friendica\Network\HTTPException\BadRequestException();
467 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
469 Logger::log('Message did not verify. Discarding.');
473 throw new \Friendica\Network\HTTPException\BadRequestException();
477 return ['message' => (string)Strings::base64UrlDecode($base->data),
478 'author' => XML::unescape($author_addr),
479 'key' => (string)$key];
483 * @brief: Decodes incoming Diaspora message in the deprecated format
485 * @param array $importer Array of the importer user
486 * @param string $xml urldecoded Diaspora salmon
489 * 'message' -> decoded Diaspora XML message
490 * 'author' -> author diaspora handle
491 * 'key' -> author public key (converted to pkcs#8)
492 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
493 * @throws \ImagickException
495 public static function decode(array $importer, $xml)
498 $basedom = XML::parseString($xml);
500 if (!is_object($basedom)) {
501 Logger::log("XML is not parseable.");
504 $children = $basedom->children('https://joindiaspora.com/protocol');
506 $inner_aes_key = null;
509 if ($children->header) {
511 $author_link = str_replace('acct:', '', $children->header->author_id);
513 // This happens with posts from a relais
515 Logger::log("This is no private post in the old format", Logger::DEBUG);
519 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
521 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
522 $ciphertext = base64_decode($encrypted_header->ciphertext);
524 $outer_key_bundle = '';
525 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
527 $j_outer_key_bundle = json_decode($outer_key_bundle);
529 $outer_iv = base64_decode($j_outer_key_bundle->iv);
530 $outer_key = base64_decode($j_outer_key_bundle->key);
532 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
534 Logger::log('decrypted: '.$decrypted, Logger::DEBUG);
535 $idom = XML::parseString($decrypted);
537 $inner_iv = base64_decode($idom->iv);
538 $inner_aes_key = base64_decode($idom->aes_key);
540 $author_link = str_replace('acct:', '', $idom->author_id);
543 $dom = $basedom->children(NAMESPACE_SALMON_ME);
545 // figure out where in the DOM tree our data is hiding
548 if ($dom->provenance->data) {
549 $base = $dom->provenance;
550 } elseif ($dom->env->data) {
552 } elseif ($dom->data) {
557 Logger::log('unable to locate salmon data in xml');
558 throw new \Friendica\Network\HTTPException\BadRequestException();
562 // Stash the signature away for now. We have to find their key or it won't be good for anything.
563 $signature = Strings::base64UrlDecode($base->sig);
567 // strip whitespace so our data element will return to one big base64 blob
568 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
571 // stash away some other stuff for later
573 $type = $base->data[0]->attributes()->type[0];
574 $keyhash = $base->sig[0]->attributes()->keyhash[0];
575 $encoding = $base->encoding;
579 $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
583 $data = Strings::base64UrlDecode($data);
587 $inner_decrypted = $data;
589 // Decode the encrypted blob
590 $inner_encrypted = base64_decode($data);
591 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
595 Logger::log('Could not retrieve author URI.');
596 throw new \Friendica\Network\HTTPException\BadRequestException();
598 // Once we have the author URI, go to the web and try to find their public key
599 // (first this will look it up locally if it is in the fcontact cache)
600 // This will also convert diaspora public key from pkcs#1 to pkcs#8
602 Logger::log('Fetching key for '.$author_link);
603 $key = self::key($author_link);
606 Logger::log('Could not retrieve author key.');
607 throw new \Friendica\Network\HTTPException\BadRequestException();
610 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
613 Logger::log('Message did not verify. Discarding.');
614 throw new \Friendica\Network\HTTPException\BadRequestException();
617 Logger::log('Message verified.');
619 return ['message' => (string)$inner_decrypted,
620 'author' => XML::unescape($author_link),
621 'key' => (string)$key];
626 * @brief Dispatches public messages and find the fitting receivers
628 * @param array $msg The post that will be dispatched
630 * @return int The message id of the generated message, "true" or "false" if there was an error
631 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
632 * @throws \ImagickException
634 public static function dispatchPublic($msg)
636 $enabled = intval(Config::get("system", "diaspora_enabled"));
638 Logger::log("diaspora is disabled");
642 if (!($fields = self::validPosting($msg))) {
643 Logger::log("Invalid posting");
647 $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
648 $success = self::dispatch($importer, $msg, $fields);
654 * @brief Dispatches the different message types to the different functions
656 * @param array $importer Array of the importer user
657 * @param array $msg The post that will be dispatched
658 * @param SimpleXMLElement $fields SimpleXML object that contains the message
660 * @return int The message id of the generated message, "true" or "false" if there was an error
661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
662 * @throws \ImagickException
664 public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
666 // The sender is the handle of the contact that sent the message.
667 // This will often be different with relayed messages (for example "like" and "comment")
668 $sender = $msg["author"];
670 // This is only needed for private postings since this is already done for public ones before
671 if (is_null($fields)) {
673 if (!($fields = self::validPosting($msg))) {
674 Logger::log("Invalid posting");
681 $type = $fields->getName();
683 Logger::log("Received message type ".$type." from ".$sender." for user ".$importer["uid"], Logger::DEBUG);
686 case "account_migration":
688 Logger::log('Message with type ' . $type . ' is not private, quitting.');
691 return self::receiveAccountMigration($importer, $fields);
693 case "account_deletion":
694 return self::receiveAccountDeletion($fields);
697 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
701 Logger::log('Message with type ' . $type . ' is not private, quitting.');
704 return self::receiveContactRequest($importer, $fields);
708 Logger::log('Message with type ' . $type . ' is not private, quitting.');
711 return self::receiveConversation($importer, $msg, $fields);
714 return self::receiveLike($importer, $sender, $fields);
718 Logger::log('Message with type ' . $type . ' is not private, quitting.');
721 return self::receiveMessage($importer, $fields);
723 case "participation":
725 Logger::log('Message with type ' . $type . ' is not private, quitting.');
728 return self::receiveParticipation($importer, $fields);
730 case "photo": // Not implemented
731 return self::receivePhoto($importer, $fields);
733 case "poll_participation": // Not implemented
734 return self::receivePollParticipation($importer, $fields);
738 Logger::log('Message with type ' . $type . ' is not private, quitting.');
741 return self::receiveProfile($importer, $fields);
744 return self::receiveReshare($importer, $fields, $msg["message"]);
747 return self::receiveRetraction($importer, $sender, $fields);
749 case "status_message":
750 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
753 Logger::log("Unknown message type ".$type);
759 * @brief Checks if a posting is valid and fetches the data fields.
761 * This function does not only check the signature.
762 * It also does the conversion between the old and the new diaspora format.
764 * @param array $msg Array with the XML, the sender handle and the sender signature
766 * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
767 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
768 * @throws \ImagickException
770 private static function validPosting($msg)
772 $data = XML::parseString($msg["message"]);
774 if (!is_object($data)) {
775 Logger::log("No valid XML ".$msg["message"], Logger::DEBUG);
779 // Is this the new or the old version?
780 if ($data->getName() == "XML") {
782 foreach ($data->post->children() as $child) {
790 $type = $element->getName();
793 Logger::log("Got message type ".$type.": ".$msg["message"], Logger::DATA);
795 // All retractions are handled identically from now on.
796 // In the new version there will only be "retraction".
797 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
798 $type = "retraction";
800 if ($type == "request") {
804 $fields = new SimpleXMLElement("<".$type."/>");
807 $author_signature = null;
808 $parent_author_signature = null;
810 foreach ($element->children() as $fieldname => $entry) {
812 // Translation for the old XML structure
813 if ($fieldname == "diaspora_handle") {
814 $fieldname = "author";
816 if ($fieldname == "participant_handles") {
817 $fieldname = "participants";
819 if (in_array($type, ["like", "participation"])) {
820 if ($fieldname == "target_type") {
821 $fieldname = "parent_type";
824 if ($fieldname == "sender_handle") {
825 $fieldname = "author";
827 if ($fieldname == "recipient_handle") {
828 $fieldname = "recipient";
830 if ($fieldname == "root_diaspora_id") {
831 $fieldname = "root_author";
833 if ($type == "status_message") {
834 if ($fieldname == "raw_message") {
838 if ($type == "retraction") {
839 if ($fieldname == "post_guid") {
840 $fieldname = "target_guid";
842 if ($fieldname == "type") {
843 $fieldname = "target_type";
848 if (($fieldname == "author_signature") && ($entry != "")) {
849 $author_signature = base64_decode($entry);
850 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
851 $parent_author_signature = base64_decode($entry);
852 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
853 if ($signed_data != "") {
857 $signed_data .= $entry;
859 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
860 || ($orig_type == "relayable_retraction")
862 XML::copy($entry, $fields, $fieldname);
866 // This is something that shouldn't happen at all.
867 if (in_array($type, ["status_message", "reshare", "profile"])) {
868 if ($msg["author"] != $fields->author) {
869 Logger::log("Message handle is not the same as envelope sender. Quitting this message.");
874 // Only some message types have signatures. So we quit here for the other types.
875 if (!in_array($type, ["comment", "like"])) {
878 // No author_signature? This is a must, so we quit.
879 if (!isset($author_signature)) {
880 Logger::log("No author signature for type ".$type." - Message: ".$msg["message"], Logger::DEBUG);
884 if (isset($parent_author_signature)) {
885 $key = self::key($msg["author"]);
887 Logger::log("No key found for parent author ".$msg["author"], Logger::DEBUG);
891 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
892 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);
897 $key = self::key($fields->author);
899 Logger::log("No key found for author ".$fields->author, Logger::DEBUG);
903 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
904 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);
912 * @brief Fetches the public key for a given handle
914 * @param string $handle The handle
916 * @return string The public key
917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
918 * @throws \ImagickException
920 private static function key($handle)
922 $handle = strval($handle);
924 Logger::log("Fetching diaspora key for: ".$handle);
926 $r = self::personByHandle($handle);
935 * @brief Fetches data for a given handle
937 * @param string $handle The handle
939 * @return array the queried data
940 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
941 * @throws \ImagickException
943 public static function personByHandle($handle)
947 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
948 if (DBA::isResult($person)) {
949 Logger::debug("In cache " . print_r($person, true));
951 // update record occasionally so it doesn't get stale
952 $d = strtotime($person["updated"]." +00:00");
953 if ($d < strtotime("now - 14 days")) {
957 if ($person["guid"] == "") {
962 if (!DBA::isResult($person) || $update) {
963 Logger::log("create or refresh", Logger::DEBUG);
964 $r = Probe::uri($handle, Protocol::DIASPORA);
966 // Note that Friendica contacts will return a "Diaspora person"
967 // if Diaspora connectivity is enabled on their server
968 if ($r && ($r["network"] === Protocol::DIASPORA)) {
969 self::updateFContact($r);
971 // Fetch the updated or added contact
972 $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
973 if (!DBA::isResult($person)) {
984 * @brief Updates the fcontact table
986 * @param array $arr The fcontact data
989 private static function updateFContact($arr)
991 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
992 'request' => $arr["request"], 'nick' => $arr["nick"],
993 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
994 'batch' => $arr["batch"], 'notify' => $arr["notify"],
995 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
996 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
997 'updated' => DateTimeFormat::utcNow()];
999 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
1001 DBA::update('fcontact', $fields, $condition, true);
1005 * @brief get a handle (user@domain.tld) from a given contact id
1007 * @param int $contact_id The id in the contact table
1008 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1010 * @return string the handle
1011 * @throws \Exception
1013 private static function handleFromContact($contact_id, $pcontact_id = 0)
1017 Logger::log("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, Logger::DEBUG);
1019 if ($pcontact_id != 0) {
1020 $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
1022 if (DBA::isResult($contact) && !empty($contact["addr"])) {
1023 return strtolower($contact["addr"]);
1028 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1032 if (DBA::isResult($r)) {
1035 Logger::log("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], Logger::DEBUG);
1037 if ($contact['addr'] != "") {
1038 $handle = $contact['addr'];
1040 $baseurl_start = strpos($contact['url'], '://') + 3;
1041 // allows installations in a subdirectory--not sure how Diaspora will handle
1042 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1043 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1044 $handle = $contact['nick'].'@'.$baseurl;
1048 return strtolower($handle);
1052 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1055 * @param mixed $fcontact_guid Hexadecimal string guid
1057 * @return string the contact url or null
1058 * @throws \Exception
1060 public static function urlFromContactGuid($fcontact_guid)
1062 Logger::log("fcontact guid is ".$fcontact_guid, Logger::DEBUG);
1065 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1066 DBA::escape(Protocol::DIASPORA),
1067 DBA::escape($fcontact_guid)
1070 if (DBA::isResult($r)) {
1071 return $r[0]['url'];
1078 * @brief Get a contact id for a given handle
1080 * @todo Move to Friendica\Model\Contact
1082 * @param int $uid The user id
1083 * @param string $handle The handle in the format user@domain.tld
1085 * @return array Contact data
1086 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1087 * @throws \ImagickException
1089 private static function contactByHandle($uid, $handle)
1091 $cid = Contact::getIdForURL($handle, $uid);
1093 $handle_parts = explode("@", $handle);
1094 $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1095 $cid = Contact::getIdForURL($nurl_sql, $uid);
1099 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1103 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1104 if (!DBA::isResult($contact)) {
1105 // This here shouldn't happen at all
1106 Logger::log("Haven't found a contact for user " . $uid . " and handle " . $handle, Logger::DEBUG);
1114 * @brief Check if posting is allowed for this contact
1116 * @param array $importer Array of the importer user
1117 * @param array $contact The contact that is checked
1118 * @param bool $is_comment Is the check for a comment?
1120 * @return bool is the contact allowed to post?
1122 private static function postAllow(array $importer, array $contact, $is_comment = false)
1125 * Perhaps we were already sharing with this person. Now they're sharing with us.
1126 * That makes us friends.
1127 * Normally this should have handled by getting a request - but this could get lost
1129 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1130 // It is not removed by now. Possibly the code is needed?
1131 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
1134 // array('rel' => Contact::FRIEND, 'writable' => true),
1135 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1138 // $contact["rel"] = Contact::FRIEND;
1139 // Logger::log("defining user ".$contact["nick"]." as friend");
1142 // Contact server is blocked
1143 if (Network::isUrlBlocked($contact['url'])) {
1145 // We don't seem to like that person
1146 } elseif ($contact["blocked"]) {
1147 // Maybe blocked, don't accept.
1149 // We are following this person?
1150 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1151 // Yes, then it is fine.
1153 // Is it a post to a community?
1154 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
1157 // Is the message a global user or a comment?
1158 } elseif (($importer["uid"] == 0) || $is_comment) {
1159 // Messages for the global users and comments are always accepted
1167 * @brief Fetches the contact id for a handle and checks if posting is allowed
1169 * @param array $importer Array of the importer user
1170 * @param string $handle The checked handle in the format user@domain.tld
1171 * @param bool $is_comment Is the check for a comment?
1173 * @return array The contact data
1174 * @throws \Exception
1176 private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1178 $contact = self::contactByHandle($importer["uid"], $handle);
1180 Logger::log("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1181 // If a contact isn't found, we accept it anyway if it is a comment
1182 if ($is_comment && ($importer["uid"] != 0)) {
1183 return self::contactByHandle(0, $handle);
1184 } elseif ($is_comment) {
1191 if (!self::postAllow($importer, $contact, $is_comment)) {
1192 Logger::log("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1199 * @brief Does the message already exists on the system?
1201 * @param int $uid The user id
1202 * @param string $guid The guid of the message
1204 * @return int|bool message id if the message already was stored into the system - or false.
1205 * @throws \Exception
1207 private static function messageExists($uid, $guid)
1209 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1210 if (DBA::isResult($item)) {
1211 Logger::log("message ".$guid." already exists for user ".$uid);
1219 * @brief Checks for links to posts in a message
1221 * @param array $item The item array
1224 private static function fetchGuid(array $item)
1226 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1227 preg_replace_callback(
1229 function ($match) use ($item) {
1230 self::fetchGuidSub($match, $item);
1235 preg_replace_callback(
1236 "&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1237 function ($match) use ($item) {
1238 self::fetchGuidSub($match, $item);
1245 * @brief Checks for relative /people/* links in an item body to match local
1246 * contacts or prepends the remote host taken from the author link.
1248 * @param string $body The item body to replace links from
1249 * @param string $author_link The author link for missing local contact fallback
1251 * @return string the replaced string
1253 public static function replacePeopleGuid($body, $author_link)
1255 $return = preg_replace_callback(
1256 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1257 function ($match) use ($author_link) {
1259 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1260 // 1 => '0123456789abcdef'
1262 $handle = self::urlFromContactGuid($match[1]);
1265 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1267 // No local match, restoring absolute remote URL from author scheme and host
1268 $author_url = parse_url($author_link);
1269 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1281 * @brief sub function of "fetchGuid" which checks for links in messages
1283 * @param array $match array containing a link that has to be checked for a message link
1284 * @param array $item The item array
1286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1287 * @throws \ImagickException
1289 private static function fetchGuidSub($match, $item)
1291 if (!self::storeByGuid($match[1], $item["author-link"])) {
1292 self::storeByGuid($match[1], $item["owner-link"]);
1297 * @brief Fetches an item with a given guid from a given server
1299 * @param string $guid the message guid
1300 * @param string $server The server address
1301 * @param int $uid The user id of the user
1303 * @return int the message id of the stored message or false
1304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1305 * @throws \ImagickException
1307 private static function storeByGuid($guid, $server, $uid = 0)
1309 $serverparts = parse_url($server);
1311 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1315 $server = $serverparts["scheme"]."://".$serverparts["host"];
1317 Logger::log("Trying to fetch item ".$guid." from ".$server, Logger::DEBUG);
1319 $msg = self::message($guid, $server);
1325 Logger::log("Successfully fetched item ".$guid." from ".$server, Logger::DEBUG);
1327 // Now call the dispatcher
1328 return self::dispatchPublic($msg);
1332 * @brief Fetches a message from a server
1334 * @param string $guid message guid
1335 * @param string $server The url of the server
1336 * @param int $level Endless loop prevention
1339 * 'message' => The message XML
1340 * 'author' => The author handle
1341 * 'key' => The public key of the author
1342 * @throws \Exception
1344 private static function message($guid, $server, $level = 0)
1350 // This will work for new Diaspora servers and Friendica servers from 3.5
1351 $source_url = $server."/fetch/post/".urlencode($guid);
1353 Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
1355 $envelope = Network::fetchUrl($source_url);
1357 Logger::log("Envelope was fetched.", Logger::DEBUG);
1358 $x = self::verifyMagicEnvelope($envelope);
1360 Logger::log("Envelope could not be verified.", Logger::DEBUG);
1362 Logger::log("Envelope was verified.", Logger::DEBUG);
1372 $source_xml = XML::parseString($x);
1374 if (!is_object($source_xml)) {
1378 if ($source_xml->post->reshare) {
1379 // Reshare of a reshare - old Diaspora version
1380 Logger::log("Message is a reshare", Logger::DEBUG);
1381 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1382 } elseif ($source_xml->getName() == "reshare") {
1383 // Reshare of a reshare - new Diaspora version
1384 Logger::log("Message is a new reshare", Logger::DEBUG);
1385 return self::message($source_xml->root_guid, $server, ++$level);
1390 // Fetch the author - for the old and the new Diaspora version
1391 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1392 $author = (string)$source_xml->post->status_message->diaspora_handle;
1393 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1394 $author = (string)$source_xml->author;
1397 // If this isn't a "status_message" then quit
1399 Logger::log("Message doesn't seem to be a status message", Logger::DEBUG);
1403 $msg = ["message" => $x, "author" => $author];
1405 $msg["key"] = self::key($msg["author"]);
1411 * @brief Fetches the item record of a given guid
1413 * @param int $uid The user id
1414 * @param string $guid message guid
1415 * @param string $author The handle of the item
1416 * @param array $contact The contact of the item owner
1418 * @return array the item record
1419 * @throws \Exception
1421 private static function parentItem($uid, $guid, $author, array $contact)
1423 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1424 'author-name', 'author-link', 'author-avatar',
1425 'owner-name', 'owner-link', 'owner-avatar'];
1426 $condition = ['uid' => $uid, 'guid' => $guid];
1427 $item = Item::selectFirst($fields, $condition);
1429 if (!DBA::isResult($item)) {
1430 $person = self::personByHandle($author);
1431 $result = self::storeByGuid($guid, $person["url"], $uid);
1433 // We don't have an url for items that arrived at the public dispatcher
1434 if (!$result && !empty($contact["url"])) {
1435 $result = self::storeByGuid($guid, $contact["url"], $uid);
1439 Logger::log("Fetched missing item ".$guid." - result: ".$result, Logger::DEBUG);
1441 $item = Item::selectFirst($fields, $condition);
1445 if (!DBA::isResult($item)) {
1446 Logger::log("parent item not found: parent: ".$guid." - user: ".$uid);
1449 Logger::log("parent item found: parent: ".$guid." - user: ".$uid);
1455 * @brief returns contact details
1457 * @param array $def_contact The default contact if the person isn't found
1458 * @param array $person The record of the person
1459 * @param int $uid The user id
1462 * 'cid' => contact id
1463 * 'network' => network type
1464 * @throws \Exception
1466 private static function authorContactByUrl($def_contact, $person, $uid)
1468 $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
1469 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1470 if (DBA::isResult($contact)) {
1471 $cid = $contact["id"];
1472 $network = $contact["network"];
1474 $cid = $def_contact["id"];
1475 $network = Protocol::DIASPORA;
1478 return ["cid" => $cid, "network" => $network];
1482 * @brief Is the profile a hubzilla profile?
1484 * @param string $url The profile link
1486 * @return bool is it a hubzilla server?
1488 public static function isRedmatrix($url)
1490 return(strstr($url, "/channel/"));
1494 * @brief Generate a post link with a given handle and message guid
1496 * @param string $addr The user handle
1497 * @param string $guid message guid
1498 * @param string $parent_guid optional parent guid
1500 * @return string the post link
1501 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1502 * @throws \ImagickException
1504 private static function plink($addr, $guid, $parent_guid = '')
1506 $contact = Contact::getDetailsByAddr($addr);
1510 if ($parent_guid != '') {
1511 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1513 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1517 if ($contact["network"] == Protocol::DFRN) {
1518 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1521 if (self::isRedmatrix($contact["url"])) {
1522 return $contact["url"] . "/?f=&mid=" . $guid;
1525 if ($parent_guid != '') {
1526 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1528 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1533 * @brief Receives account migration
1535 * @param array $importer Array of the importer user
1536 * @param object $data The message object
1538 * @return bool Success
1539 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1540 * @throws \ImagickException
1542 private static function receiveAccountMigration(array $importer, $data)
1544 $old_handle = Strings::escapeTags(XML::unescape($data->author));
1545 $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
1546 $signature = Strings::escapeTags(XML::unescape($data->signature));
1548 $contact = self::contactByHandle($importer["uid"], $old_handle);
1550 Logger::log("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1554 Logger::log("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1557 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1558 $key = self::key($old_handle);
1559 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1560 Logger::log('No valid signature for migration.');
1564 // Update the profile
1565 self::receiveProfile($importer, $data->profile);
1567 // change the technical stuff in contact and gcontact
1568 $data = Probe::uri($new_handle);
1569 if ($data['network'] == Protocol::PHANTOM) {
1570 Logger::log('Account for '.$new_handle." couldn't be probed.");
1574 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1575 'name' => $data['name'], 'nick' => $data['nick'],
1576 'addr' => $data['addr'], 'batch' => $data['batch'],
1577 'notify' => $data['notify'], 'poll' => $data['poll'],
1578 'network' => $data['network']];
1580 DBA::update('contact', $fields, ['addr' => $old_handle]);
1582 $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
1583 'name' => $data['name'], 'nick' => $data['nick'],
1584 'addr' => $data['addr'], 'connect' => $data['addr'],
1585 'notify' => $data['notify'], 'photo' => $data['photo'],
1586 'server_url' => $data['baseurl'], 'network' => $data['network']];
1588 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1590 Logger::log('Contacts are updated.');
1596 * @brief Processes an account deletion
1598 * @param object $data The message object
1600 * @return bool Success
1601 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1603 private static function receiveAccountDeletion($data)
1605 $author = Strings::escapeTags(XML::unescape($data->author));
1607 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1608 while ($contact = DBA::fetch($contacts)) {
1609 Contact::remove($contact["id"]);
1612 DBA::delete('gcontact', ['addr' => $author]);
1614 Logger::log('Removed contacts for ' . $author);
1620 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1622 * @param string $author Author handle
1623 * @param string $guid Message guid
1624 * @param boolean $onlyfound Only return uri when found in the database
1626 * @return string The constructed uri or the one from our database
1627 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1628 * @throws \ImagickException
1630 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1632 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1633 if (DBA::isResult($item)) {
1634 return $item["uri"];
1635 } elseif (!$onlyfound) {
1636 $person = self::personByHandle($author);
1638 $parts = parse_url($person['url']);
1639 unset($parts['path']);
1640 $host_url = Network::unparseURL($parts);
1642 return $host_url . '/objects/' . $guid;
1649 * @brief Fetch the guid from our database with a given uri
1651 * @param string $uri Message uri
1652 * @param string $uid Author handle
1654 * @return string The post guid
1655 * @throws \Exception
1657 private static function getGuidFromUri($uri, $uid)
1659 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1660 if (DBA::isResult($item)) {
1661 return $item["guid"];
1668 * @brief Find the best importer for a comment, like, ...
1670 * @param string $guid The guid of the item
1672 * @return array|boolean the origin owner of that post - or false
1673 * @throws \Exception
1675 private static function importerForGuid($guid)
1677 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1678 if (DBA::isResult($item)) {
1679 Logger::log("Found user ".$item['uid']." as owner of item ".$guid, Logger::DEBUG);
1680 $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1681 if (DBA::isResult($contact)) {
1689 * @brief Processes an incoming comment
1691 * @param array $importer Array of the importer user
1692 * @param string $sender The sender of the message
1693 * @param object $data The message object
1694 * @param string $xml The original XML of the message
1696 * @return int The message id of the generated comment or "false" if there was an error
1697 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1698 * @throws \ImagickException
1700 private static function receiveComment(array $importer, $sender, $data, $xml)
1702 $author = Strings::escapeTags(XML::unescape($data->author));
1703 $guid = Strings::escapeTags(XML::unescape($data->guid));
1704 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1705 $text = XML::unescape($data->text);
1707 if (isset($data->created_at)) {
1708 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1710 $created_at = DateTimeFormat::utcNow();
1713 if (isset($data->thread_parent_guid)) {
1714 $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
1715 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1720 $contact = self::allowedContactByHandle($importer, $sender, true);
1725 $message_id = self::messageExists($importer["uid"], $guid);
1730 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1731 if (!$parent_item) {
1735 $person = self::personByHandle($author);
1736 if (!is_array($person)) {
1737 Logger::log("unable to find author details");
1741 // Fetch the contact id - if we know this contact
1742 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1746 $datarray["uid"] = $importer["uid"];
1747 $datarray["contact-id"] = $author_contact["cid"];
1748 $datarray["network"] = $author_contact["network"];
1750 $datarray["author-link"] = $person["url"];
1751 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1753 $datarray["owner-link"] = $contact["url"];
1754 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1756 $datarray["guid"] = $guid;
1757 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1759 $datarray["verb"] = ACTIVITY_POST;
1760 $datarray["gravity"] = GRAVITY_COMMENT;
1762 if ($thr_uri != "") {
1763 $datarray["parent-uri"] = $thr_uri;
1765 $datarray["parent-uri"] = $parent_item["uri"];
1768 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1770 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1771 $datarray["source"] = $xml;
1773 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1775 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1777 $body = Markdown::toBBCode($text);
1779 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1781 self::fetchGuid($datarray);
1783 // If we are the origin of the parent we store the original data.
1784 // We notify our followers during the item storage.
1785 if ($parent_item["origin"]) {
1786 $datarray['diaspora_signed_text'] = json_encode($data);
1789 $message_id = Item::insert($datarray);
1791 if ($message_id <= 0) {
1796 Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1797 if ($datarray['uid'] == 0) {
1798 Item::distribute($message_id, json_encode($data));
1806 * @brief processes and stores private messages
1808 * @param array $importer Array of the importer user
1809 * @param array $contact The contact of the message
1810 * @param object $data The message object
1811 * @param array $msg Array of the processed message, author handle and key
1812 * @param object $mesg The private message
1813 * @param array $conversation The conversation record to which this message belongs
1815 * @return bool "true" if it was successful
1816 * @throws \Exception
1818 private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1820 $author = Strings::escapeTags(XML::unescape($data->author));
1821 $guid = Strings::escapeTags(XML::unescape($data->guid));
1822 $subject = Strings::escapeTags(XML::unescape($data->subject));
1824 // "diaspora_handle" is the element name from the old version
1825 // "author" is the element name from the new version
1826 if ($mesg->author) {
1827 $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1828 } elseif ($mesg->diaspora_handle) {
1829 $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1834 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1835 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1836 $msg_text = XML::unescape($mesg->text);
1837 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1839 if ($msg_conversation_guid != $guid) {
1840 Logger::log("message conversation guid does not belong to the current conversation.");
1844 $body = Markdown::toBBCode($msg_text);
1845 $message_uri = $msg_author.":".$msg_guid;
1847 $person = self::personByHandle($msg_author);
1849 return Mail::insert([
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,
1859 'uri' => $message_uri,
1860 'parent-uri' => $author . ':' . $guid,
1861 'created' => $msg_created_at
1866 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1868 * @param array $importer Array of the importer user
1869 * @param array $msg Array of the processed message, author handle and key
1870 * @param object $data The message object
1872 * @return bool Success
1873 * @throws \Exception
1875 private static function receiveConversation(array $importer, $msg, $data)
1877 $author = Strings::escapeTags(XML::unescape($data->author));
1878 $guid = Strings::escapeTags(XML::unescape($data->guid));
1879 $subject = Strings::escapeTags(XML::unescape($data->subject));
1880 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1881 $participants = Strings::escapeTags(XML::unescape($data->participants));
1883 $messages = $data->message;
1885 if (!count($messages)) {
1886 Logger::log("empty conversation");
1890 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1895 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1896 if (!DBA::isResult($conversation)) {
1898 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1899 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1900 intval($importer["uid"]),
1902 DBA::escape($author),
1903 DBA::escape($created_at),
1904 DBA::escape(DateTimeFormat::utcNow()),
1905 DBA::escape($subject),
1906 DBA::escape($participants)
1909 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1912 if (!$conversation) {
1913 Logger::log("unable to create conversation.");
1917 foreach ($messages as $mesg) {
1918 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1925 * @brief Processes "like" messages
1927 * @param array $importer Array of the importer user
1928 * @param string $sender The sender of the message
1929 * @param object $data The message object
1931 * @return int The message id of the generated like or "false" if there was an error
1932 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1933 * @throws \ImagickException
1935 private static function receiveLike(array $importer, $sender, $data)
1937 $author = Strings::escapeTags(XML::unescape($data->author));
1938 $guid = Strings::escapeTags(XML::unescape($data->guid));
1939 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1940 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1941 $positive = Strings::escapeTags(XML::unescape($data->positive));
1943 // likes on comments aren't supported by Diaspora - only on posts
1944 // But maybe this will be supported in the future, so we will accept it.
1945 if (!in_array($parent_type, ["Post", "Comment"])) {
1949 $contact = self::allowedContactByHandle($importer, $sender, true);
1954 $message_id = self::messageExists($importer["uid"], $guid);
1959 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1960 if (!$parent_item) {
1964 $person = self::personByHandle($author);
1965 if (!is_array($person)) {
1966 Logger::log("unable to find author details");
1970 // Fetch the contact id - if we know this contact
1971 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1973 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1974 // We would accept this anyhow.
1975 if ($positive == "true") {
1976 $verb = ACTIVITY_LIKE;
1978 $verb = ACTIVITY_DISLIKE;
1983 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1985 $datarray["uid"] = $importer["uid"];
1986 $datarray["contact-id"] = $author_contact["cid"];
1987 $datarray["network"] = $author_contact["network"];
1989 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1990 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1992 $datarray["guid"] = $guid;
1993 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1995 $datarray["verb"] = $verb;
1996 $datarray["gravity"] = GRAVITY_ACTIVITY;
1997 $datarray["parent-uri"] = $parent_item["uri"];
1999 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2001 $datarray["body"] = $verb;
2003 // Diaspora doesn't provide a date for likes
2004 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2006 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2007 if ($parent_item["id"] != $parent_item["parent"]) {
2008 $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
2009 $origin = $toplevel["origin"];
2011 $origin = $parent_item["origin"];
2014 // If we are the origin of the parent we store the original data.
2015 // We notify our followers during the item storage.
2017 $datarray['diaspora_signed_text'] = json_encode($data);
2020 $message_id = Item::insert($datarray);
2022 if ($message_id <= 0) {
2027 Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2028 if ($datarray['uid'] == 0) {
2029 Item::distribute($message_id, json_encode($data));
2037 * @brief Processes private messages
2039 * @param array $importer Array of the importer user
2040 * @param object $data The message object
2042 * @return bool Success?
2043 * @throws \Exception
2045 private static function receiveMessage(array $importer, $data)
2047 $author = Strings::escapeTags(XML::unescape($data->author));
2048 $guid = Strings::escapeTags(XML::unescape($data->guid));
2049 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2050 $text = XML::unescape($data->text);
2051 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2053 $contact = self::allowedContactByHandle($importer, $author, true);
2058 $conversation = null;
2060 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2061 $conversation = DBA::selectFirst('conv', [], $condition);
2063 if (!DBA::isResult($conversation)) {
2064 Logger::log("conversation not available.");
2068 $message_uri = $author.":".$guid;
2070 $person = self::personByHandle($author);
2072 Logger::log("unable to find author details");
2076 $body = Markdown::toBBCode($text);
2078 $body = self::replacePeopleGuid($body, $person["url"]);
2080 return Mail::insert([
2081 'uid' => $importer['uid'],
2083 'convid' => $conversation['id'],
2084 'from-name' => $person['name'],
2085 'from-photo' => $person['photo'],
2086 'from-url' => $person['url'],
2087 'contact-id' => $contact['id'],
2088 'title' => $conversation['subject'],
2091 'uri' => $message_uri,
2092 'parent-uri' => $author.":".$conversation['guid'],
2093 'created' => $created_at
2098 * @brief Processes participations - unsupported by now
2100 * @param array $importer Array of the importer user
2101 * @param object $data The message object
2103 * @return bool always true
2104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2105 * @throws \ImagickException
2107 private static function receiveParticipation(array $importer, $data)
2109 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2110 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2112 $contact_id = Contact::getIdForURL($author);
2114 Logger::log('Contact not found: '.$author);
2118 $person = self::personByHandle($author);
2119 if (!is_array($person)) {
2120 Logger::log("Person not found: ".$author);
2124 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2125 if (!DBA::isResult($item)) {
2126 Logger::log('Item not found, no origin or private: '.$parent_guid);
2130 $author_parts = explode('@', $author);
2131 if (isset($author_parts[1])) {
2132 $server = $author_parts[1];
2134 // Should never happen
2138 Logger::log('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, Logger::DEBUG);
2140 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2141 DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2144 // Send all existing comments and likes to the requesting server
2145 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2146 while ($comment = Item::fetch($comments)) {
2147 if ($comment['id'] == $comment['parent']) {
2150 if ($comment['verb'] == ACTIVITY_POST) {
2151 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2153 $cmd = $comment['self'] ? 'like' : 'comment-import';
2155 Logger::log("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, Logger::DEBUG);
2156 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2158 DBA::close($comments);
2164 * @brief Processes photos - unneeded
2166 * @param array $importer Array of the importer user
2167 * @param object $data The message object
2169 * @return bool always true
2171 private static function receivePhoto(array $importer, $data)
2173 // There doesn't seem to be a reason for this function,
2174 // since the photo data is transmitted in the status message as well
2179 * @brief Processes poll participations - unssupported
2181 * @param array $importer Array of the importer user
2182 * @param object $data The message object
2184 * @return bool always true
2186 private static function receivePollParticipation(array $importer, $data)
2188 // We don't support polls by now
2193 * @brief Processes incoming profile updates
2195 * @param array $importer Array of the importer user
2196 * @param object $data The message object
2198 * @return bool Success
2199 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2200 * @throws \ImagickException
2202 private static function receiveProfile(array $importer, $data)
2204 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2206 $contact = self::contactByHandle($importer["uid"], $author);
2211 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2212 $image_url = XML::unescape($data->image_url);
2213 $birthday = XML::unescape($data->birthday);
2214 $gender = XML::unescape($data->gender);
2215 $about = Markdown::toBBCode(XML::unescape($data->bio));
2216 $location = Markdown::toBBCode(XML::unescape($data->location));
2217 $searchable = (XML::unescape($data->searchable) == "true");
2218 $nsfw = (XML::unescape($data->nsfw) == "true");
2219 $tags = XML::unescape($data->tag_string);
2221 $tags = explode("#", $tags);
2224 foreach ($tags as $tag) {
2225 $tag = trim(strtolower($tag));
2231 $keywords = implode(", ", $keywords);
2233 $handle_parts = explode("@", $author);
2234 $nick = $handle_parts[0];
2237 $name = $handle_parts[0];
2240 if (preg_match("|^https?://|", $image_url) === 0) {
2241 $image_url = "http://".$handle_parts[1].$image_url;
2244 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2246 // Generic birthday. We don't know the timezone. The year is irrelevant.
2248 $birthday = str_replace("1000", "1901", $birthday);
2250 if ($birthday != "") {
2251 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2254 // this is to prevent multiple birthday notifications in a single year
2255 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2257 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2258 $birthday = $contact["bd"];
2261 $fields = ['name' => $name, 'location' => $location,
2262 'name-date' => DateTimeFormat::utcNow(),
2263 'about' => $about, 'gender' => $gender,
2264 'addr' => $author, 'nick' => $nick,
2265 'keywords' => $keywords];
2267 if (!empty($birthday)) {
2268 $fields['bd'] = $birthday;
2271 DBA::update('contact', $fields, ['id' => $contact['id']]);
2273 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2274 "photo" => $image_url, "name" => $name, "location" => $location,
2275 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2276 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2277 "hide" => !$searchable, "nsfw" => $nsfw];
2279 $gcid = GContact::update($gcontact);
2281 GContact::link($gcid, $importer["uid"], $contact["id"]);
2283 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2289 * @brief Processes incoming friend requests
2291 * @param array $importer Array of the importer user
2292 * @param array $contact The contact that send the request
2294 * @throws \Exception
2296 private static function receiveRequestMakeFriend(array $importer, array $contact)
2298 if ($contact["rel"] == Contact::SHARING) {
2301 ['rel' => Contact::FRIEND, 'writable' => true],
2302 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2308 * @brief Processes incoming sharing notification
2310 * @param array $importer Array of the importer user
2311 * @param object $data The message object
2313 * @return bool Success
2314 * @throws \Exception
2316 private static function receiveContactRequest(array $importer, $data)
2318 $author = XML::unescape($data->author);
2319 $recipient = XML::unescape($data->recipient);
2321 if (!$author || !$recipient) {
2325 // the current protocol version doesn't know these fields
2326 // That means that we will assume their existance
2327 if (isset($data->following)) {
2328 $following = (XML::unescape($data->following) == "true");
2333 if (isset($data->sharing)) {
2334 $sharing = (XML::unescape($data->sharing) == "true");
2339 $contact = self::contactByHandle($importer["uid"], $author);
2341 // perhaps we were already sharing with this person. Now they're sharing with us.
2342 // That makes us friends.
2345 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2346 self::receiveRequestMakeFriend($importer, $contact);
2348 // refetch the contact array
2349 $contact = self::contactByHandle($importer["uid"], $author);
2351 // If we are now friends, we are sending a share message.
2352 // Normally we needn't to do so, but the first message could have been vanished.
2353 if (in_array($contact["rel"], [Contact::FRIEND])) {
2354 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2355 if (DBA::isResult($user)) {
2356 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2357 self::sendShare($user, $contact);
2362 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2363 Contact::removeFollower($importer, $contact);
2368 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2369 Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2371 } elseif (!$following && !$sharing) {
2372 Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2374 } elseif (!$following && $sharing) {
2375 Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2376 } elseif ($following && $sharing) {
2377 Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2378 } elseif ($following && !$sharing) {
2379 Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2382 $ret = self::personByHandle($author);
2384 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2385 Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2389 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2392 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2393 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2394 intval($importer["uid"]),
2395 DBA::escape($ret["network"]),
2396 DBA::escape($ret["addr"]),
2397 DateTimeFormat::utcNow(),
2398 DBA::escape($ret["url"]),
2399 DBA::escape(Strings::normaliseLink($ret["url"])),
2400 DBA::escape($batch),
2401 DBA::escape($ret["name"]),
2402 DBA::escape($ret["nick"]),
2403 DBA::escape($ret["photo"]),
2404 DBA::escape($ret["pubkey"]),
2405 DBA::escape($ret["notify"]),
2406 DBA::escape($ret["poll"]),
2411 // find the contact record we just created
2413 $contact_record = self::contactByHandle($importer["uid"], $author);
2415 if (!$contact_record) {
2416 Logger::log("unable to locate newly created contact record.");
2420 Logger::log("Author ".$author." was added as contact number ".$contact_record["id"].".", Logger::DEBUG);
2422 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2424 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2426 if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
2427 Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
2429 $hash = Strings::getRandomHex().(string)time(); // Generate a confirm_key
2432 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2433 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2434 intval($importer["uid"]),
2435 intval($contact_record["id"]),
2438 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2440 DBA::escape(DateTimeFormat::utcNow())
2443 // automatic friend approval
2445 Logger::log("Does an automatic friend approval for author ".$author.".", Logger::DEBUG);
2447 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2450 * technically they are sharing with us (Contact::SHARING),
2451 * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2452 * we are going to change the relationship and make them a follower.
2454 if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
2455 $new_relation = Contact::FRIEND;
2456 } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
2457 $new_relation = Contact::SHARING;
2459 $new_relation = Contact::FOLLOWER;
2463 "UPDATE `contact` SET `rel` = %d,
2471 intval($new_relation),
2472 DBA::escape(DateTimeFormat::utcNow()),
2473 DBA::escape(DateTimeFormat::utcNow()),
2474 intval($contact_record["id"])
2477 $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2478 if (DBA::isResult($user)) {
2479 Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2480 self::sendShare($user, $contact_record);
2482 // Send the profile data, maybe it weren't transmitted before
2483 self::sendProfile($importer["uid"], [$contact_record]);
2491 * @brief Fetches a message with a given guid
2493 * @param string $guid message guid
2494 * @param string $orig_author handle of the original post
2495 * @return array The fetched item
2496 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2497 * @throws \ImagickException
2499 public static function originalItem($guid, $orig_author)
2502 Logger::log('Empty guid. Quitting.');
2506 // Do we already have this item?
2507 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2508 'author-name', 'author-link', 'author-avatar'];
2509 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2510 $item = Item::selectFirst($fields, $condition);
2512 if (DBA::isResult($item)) {
2513 Logger::log("reshared message ".$guid." already exists on system.");
2515 // Maybe it is already a reshared item?
2516 // Then refetch the content, if it is a reshare from a reshare.
2517 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2518 if (self::isReshare($item["body"], true)) {
2520 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2521 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2523 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2525 // Add OEmbed and other information to the body
2526 $item["body"] = add_page_info_to_body($item["body"], false, true);
2534 if (!DBA::isResult($item)) {
2535 if (empty($orig_author)) {
2536 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2540 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2541 Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2542 $stored = self::storeByGuid($guid, $server);
2545 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2546 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2547 $stored = self::storeByGuid($guid, $server);
2551 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2552 'author-name', 'author-link', 'author-avatar'];
2553 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2554 $item = Item::selectFirst($fields, $condition);
2556 if (DBA::isResult($item)) {
2557 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2558 if (self::isReshare($item["body"], false)) {
2559 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2560 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2571 * @brief Stores a reshare activity
2573 * @param array $item Array of reshare post
2574 * @param integer $parent_message_id Id of the parent post
2575 * @param string $guid GUID string of reshare action
2576 * @param string $author Author handle
2578 private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2580 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2584 $datarray['uid'] = $item['uid'];
2585 $datarray['contact-id'] = $item['contact-id'];
2586 $datarray['network'] = $item['network'];
2588 $datarray['author-link'] = $item['author-link'];
2589 $datarray['author-id'] = $item['author-id'];
2591 $datarray['owner-link'] = $datarray['author-link'];
2592 $datarray['owner-id'] = $datarray['author-id'];
2594 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2595 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2596 $datarray['parent-uri'] = $parent['uri'];
2598 $datarray['verb'] = $datarray['body'] = ACTIVITY2_ANNOUNCE;
2599 $datarray['gravity'] = GRAVITY_ACTIVITY;
2600 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
2602 $datarray['protocol'] = $item['protocol'];
2604 $datarray['plink'] = self::plink($author, $datarray['guid']);
2605 $datarray['private'] = $item['private'];
2606 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2608 $message_id = Item::insert($datarray);
2611 Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2612 if ($datarray['uid'] == 0) {
2613 Item::distribute($message_id);
2619 * @brief Processes a reshare message
2621 * @param array $importer Array of the importer user
2622 * @param object $data The message object
2623 * @param string $xml The original XML of the message
2625 * @return int the message id
2626 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2627 * @throws \ImagickException
2629 private static function receiveReshare(array $importer, $data, $xml)
2631 $author = Strings::escapeTags(XML::unescape($data->author));
2632 $guid = Strings::escapeTags(XML::unescape($data->guid));
2633 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2634 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2635 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2636 /// @todo handle unprocessed property "provider_display_name"
2637 $public = Strings::escapeTags(XML::unescape($data->public));
2639 $contact = self::allowedContactByHandle($importer, $author, false);
2644 $message_id = self::messageExists($importer["uid"], $guid);
2649 $original_item = self::originalItem($root_guid, $root_author);
2650 if (!$original_item) {
2654 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2658 $datarray["uid"] = $importer["uid"];
2659 $datarray["contact-id"] = $contact["id"];
2660 $datarray["network"] = Protocol::DIASPORA;
2662 $datarray["author-link"] = $contact["url"];
2663 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2665 $datarray["owner-link"] = $datarray["author-link"];
2666 $datarray["owner-id"] = $datarray["author-id"];
2668 $datarray["guid"] = $guid;
2669 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2671 $datarray["verb"] = ACTIVITY_POST;
2672 $datarray["gravity"] = GRAVITY_PARENT;
2674 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2675 $datarray["source"] = $xml;
2677 $prefix = share_header(
2678 $original_item["author-name"],
2679 $original_item["author-link"],
2680 $original_item["author-avatar"],
2681 $original_item["guid"],
2682 $original_item["created"],
2685 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2687 $datarray["tag"] = $original_item["tag"];
2688 $datarray["app"] = $original_item["app"];
2690 $datarray["plink"] = self::plink($author, $guid);
2691 $datarray["private"] = (($public == "false") ? 1 : 0);
2692 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2694 $datarray["object-type"] = $original_item["object-type"];
2696 self::fetchGuid($datarray);
2697 $message_id = Item::insert($datarray);
2699 self::sendParticipation($contact, $datarray);
2701 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2702 if ($root_message_id) {
2703 self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2707 Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2708 if ($datarray['uid'] == 0) {
2709 Item::distribute($message_id);
2718 * @brief Processes retractions
2720 * @param array $importer Array of the importer user
2721 * @param array $contact The contact of the item owner
2722 * @param object $data The message object
2724 * @return bool success
2725 * @throws \Exception
2727 private static function itemRetraction(array $importer, array $contact, $data)
2729 $author = Strings::escapeTags(XML::unescape($data->author));
2730 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2731 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2733 $person = self::personByHandle($author);
2734 if (!is_array($person)) {
2735 Logger::log("unable to find author detail for ".$author);
2739 if (empty($contact["url"])) {
2740 $contact["url"] = $person["url"];
2743 // Fetch items that are about to be deleted
2744 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2746 // When we receive a public retraction, we delete every item that we find.
2747 if ($importer['uid'] == 0) {
2748 $condition = ['guid' => $target_guid, 'deleted' => false];
2750 $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2753 $r = Item::select($fields, $condition);
2754 if (!DBA::isResult($r)) {
2755 Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2759 while ($item = Item::fetch($r)) {
2760 if (strstr($item['file'], '[')) {
2761 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2765 // Fetch the parent item
2766 $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2768 // Only delete it if the parent author really fits
2769 if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2770 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2774 Item::delete(['id' => $item['id']]);
2776 Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2783 * @brief Receives retraction messages
2785 * @param array $importer Array of the importer user
2786 * @param string $sender The sender of the message
2787 * @param object $data The message object
2789 * @return bool Success
2790 * @throws \Exception
2792 private static function receiveRetraction(array $importer, $sender, $data)
2794 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2796 $contact = self::contactByHandle($importer["uid"], $sender);
2797 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2798 Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2806 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2808 switch ($target_type) {
2813 case "StatusMessage":
2814 return self::itemRetraction($importer, $contact, $data);
2816 case "PollParticipation":
2818 // Currently unsupported
2822 Logger::log("Unknown target type ".$target_type);
2829 * @brief Receives status messages
2831 * @param array $importer Array of the importer user
2832 * @param SimpleXMLElement $data The message object
2833 * @param string $xml The original XML of the message
2835 * @return int The message id of the newly created item
2836 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2837 * @throws \ImagickException
2839 private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2841 $author = Strings::escapeTags(XML::unescape($data->author));
2842 $guid = Strings::escapeTags(XML::unescape($data->guid));
2843 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2844 $public = Strings::escapeTags(XML::unescape($data->public));
2845 $text = XML::unescape($data->text);
2846 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2848 $contact = self::allowedContactByHandle($importer, $author, false);
2853 $message_id = self::messageExists($importer["uid"], $guid);
2859 if ($data->location) {
2860 foreach ($data->location->children() as $fieldname => $data) {
2861 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2865 $body = Markdown::toBBCode($text);
2869 // Attach embedded pictures to the body
2871 foreach ($data->photo as $photo) {
2872 $body = "[img]".XML::unescape($photo->remote_photo_path).
2873 XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2876 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2878 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2880 // Add OEmbed and other information to the body
2881 if (!self::isRedmatrix($contact["url"])) {
2882 $body = add_page_info_to_body($body, false, true);
2886 /// @todo enable support for polls
2887 //if ($data->poll) {
2888 // foreach ($data->poll AS $poll)
2893 /// @todo enable support for events
2895 $datarray["uid"] = $importer["uid"];
2896 $datarray["contact-id"] = $contact["id"];
2897 $datarray["network"] = Protocol::DIASPORA;
2899 $datarray["author-link"] = $contact["url"];
2900 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2902 $datarray["owner-link"] = $datarray["author-link"];
2903 $datarray["owner-id"] = $datarray["author-id"];
2905 $datarray["guid"] = $guid;
2906 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2908 $datarray["verb"] = ACTIVITY_POST;
2909 $datarray["gravity"] = GRAVITY_PARENT;
2911 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2912 $datarray["source"] = $xml;
2914 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2916 if ($provider_display_name != "") {
2917 $datarray["app"] = $provider_display_name;
2920 $datarray["plink"] = self::plink($author, $guid);
2921 $datarray["private"] = (($public == "false") ? 1 : 0);
2922 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2924 if (isset($address["address"])) {
2925 $datarray["location"] = $address["address"];
2928 if (isset($address["lat"]) && isset($address["lng"])) {
2929 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2932 self::fetchGuid($datarray);
2933 $message_id = Item::insert($datarray);
2935 self::sendParticipation($contact, $datarray);
2938 Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2939 if ($datarray['uid'] == 0) {
2940 Item::distribute($message_id);
2948 /* ************************************************************************************** *
2949 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2950 * ************************************************************************************** */
2953 * @brief returnes the handle of a contact
2955 * @param array $contact contact array
2957 * @return string the handle in the format user@domain.tld
2958 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2960 private static function myHandle(array $contact)
2962 if (!empty($contact["addr"])) {
2963 return $contact["addr"];
2966 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2967 // So - just in case - we build the the address here.
2968 if ($contact["nickname"] != "") {
2969 $nick = $contact["nickname"];
2971 $nick = $contact["nick"];
2974 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2979 * @brief Creates the data for a private message in the new format
2981 * @param string $msg The message that is to be transmitted
2982 * @param array $user The record of the sender
2983 * @param array $contact Target of the communication
2984 * @param string $prvkey The private key of the sender
2985 * @param string $pubkey The public key of the receiver
2987 * @return string The encrypted data
2988 * @throws \Exception
2990 public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2992 Logger::log("Message: ".$msg, Logger::DATA);
2994 // without a public key nothing will work
2996 Logger::log("pubkey missing: contact id: ".$contact["id"]);
3000 $aes_key = openssl_random_pseudo_bytes(32);
3001 $b_aes_key = base64_encode($aes_key);
3002 $iv = openssl_random_pseudo_bytes(16);
3003 $b_iv = base64_encode($iv);
3005 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3007 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3009 $encrypted_key_bundle = "";
3010 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3012 $json_object = json_encode(
3013 ["aes_key" => base64_encode($encrypted_key_bundle),
3014 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3017 return $json_object;
3021 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3023 * @param string $msg The message that is to be transmitted
3024 * @param array $user The record of the sender
3026 * @return string The envelope
3027 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3029 public static function buildMagicEnvelope($msg, array $user)
3031 $b64url_data = Strings::base64UrlEncode($msg);
3032 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3034 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3035 $type = "application/xml";
3036 $encoding = "base64url";
3037 $alg = "RSA-SHA256";
3038 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3040 // Fallback if the private key wasn't transmitted in the expected field
3041 if ($user['uprvkey'] == "") {
3042 $user['uprvkey'] = $user['prvkey'];
3045 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3046 $sig = Strings::base64UrlEncode($signature);
3048 $xmldata = ["me:env" => ["me:data" => $data,
3049 "@attributes" => ["type" => $type],
3050 "me:encoding" => $encoding,
3053 "@attributes2" => ["key_id" => $key_id]]];
3055 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3057 return XML::fromArray($xmldata, $xml, false, $namespaces);
3061 * @brief Create the envelope for a message
3063 * @param string $msg The message that is to be transmitted
3064 * @param array $user The record of the sender
3065 * @param array $contact Target of the communication
3066 * @param string $prvkey The private key of the sender
3067 * @param string $pubkey The public key of the receiver
3068 * @param bool $public Is the message public?
3070 * @return string The message that will be transmitted to other servers
3071 * @throws \Exception
3073 public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3075 // The message is put into an envelope with the sender's signature
3076 $envelope = self::buildMagicEnvelope($msg, $user);
3078 // Private messages are put into a second envelope, encrypted with the receivers public key
3080 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3087 * @brief Creates a signature for a message
3089 * @param array $owner the array of the owner of the message
3090 * @param array $message The message that is to be signed
3092 * @return string The signature
3094 private static function signature($owner, $message)
3097 unset($sigmsg["author_signature"]);
3098 unset($sigmsg["parent_author_signature"]);
3100 $signed_text = implode(";", $sigmsg);
3102 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3106 * @brief Transmit a message to a target server
3108 * @param array $owner the array of the item owner
3109 * @param array $contact Target of the communication
3110 * @param string $envelope The message that is to be transmitted
3111 * @param bool $public_batch Is it a public post?
3112 * @param string $guid message guid
3113 * @param bool $no_defer Don't defer a failing delivery
3115 * @return int Result of the transmission
3116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3117 * @throws \ImagickException
3119 public static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "", $no_defer = false)
3121 $enabled = intval(Config::get("system", "diaspora_enabled"));
3126 $logid = Strings::getRandomHex(4);
3128 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3130 // We always try to use the data from the fcontact table.
3131 // This is important for transmitting data to Friendica servers.
3132 if (!empty($contact['addr'])) {
3133 $fcontact = self::personByHandle($contact['addr']);
3134 if (!empty($fcontact)) {
3135 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3140 Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3144 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3146 if (!intval(Config::get("system", "diaspora_test"))) {
3147 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3149 $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3150 $return_code = $postResult->getReturnCode();
3152 Logger::log("test_mode");
3156 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3158 if (!$return_code || (($return_code == 503) && (stristr($postResult->getHeader(), "retry-after")))) {
3159 if (!$no_defer && !empty($contact['contact-type']) && ($contact['contact-type'] != Contact::TYPE_RELAY)) {
3160 Logger::info('defer message', ['log' => $logid, 'guid' => $guid, 'destination' => $dest_url]);
3161 // defer message for redelivery
3165 // The message could not be delivered. We mark the contact as "dead"
3166 Contact::markForArchival($contact);
3167 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3168 // We successfully delivered a message, the contact is alive
3169 Contact::unmarkForArchival($contact);
3172 return $return_code ? $return_code : -1;
3177 * @brief Build the post xml
3179 * @param string $type The message type
3180 * @param array $message The message data
3182 * @return string The post XML
3184 public static function buildPostXml($type, $message)
3186 $data = [$type => $message];
3188 return XML::fromArray($data, $xml);
3192 * @brief Builds and transmit messages
3194 * @param array $owner the array of the item owner
3195 * @param array $contact Target of the communication
3196 * @param string $type The message type
3197 * @param array $message The message data
3198 * @param bool $public_batch Is it a public post?
3199 * @param string $guid message guid
3200 * @param bool $no_defer Don't defer a failing delivery
3202 * @return int Result of the transmission
3203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3204 * @throws \ImagickException
3206 private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $no_defer = false)
3208 $msg = self::buildPostXml($type, $message);
3210 Logger::log('message: '.$msg, Logger::DATA);
3211 Logger::log('send guid '.$guid, Logger::DEBUG);
3213 // Fallback if the private key wasn't transmitted in the expected field
3214 if (empty($owner['uprvkey'])) {
3215 $owner['uprvkey'] = $owner['prvkey'];
3218 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3220 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid, $no_defer);
3222 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3224 return $return_code;
3228 * @brief sends a participation (Used to get all further updates)
3230 * @param array $contact Target of the communication
3231 * @param array $item Item array
3233 * @return int The result of the transmission
3234 * @throws \Exception
3236 private static function sendParticipation(array $contact, array $item)
3238 // Don't send notifications for private postings
3239 if ($item['private']) {
3243 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3245 $result = Cache::get($cachekey);
3246 if (!is_null($result)) {
3250 // Fetch some user id to have a valid handle to transmit the participation.
3251 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3252 // If the item belongs to a user, we take this user id.
3253 if ($item['uid'] == 0) {
3254 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3255 $first_user = DBA::selectFirst('user', ['uid'], $condition);
3256 $owner = User::getOwnerDataById($first_user['uid']);
3258 $owner = User::getOwnerDataById($item['uid']);
3261 $author = self::myHandle($owner);
3263 $message = ["author" => $author,
3264 "guid" => System::createUUID(),
3265 "parent_type" => "Post",
3266 "parent_guid" => $item["guid"]];
3268 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3270 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3271 Cache::set($cachekey, $item["guid"], Cache::QUARTER_HOUR);
3273 return self::buildAndTransmit($owner, $contact, "participation", $message);
3277 * @brief sends an account migration
3279 * @param array $owner the array of the item owner
3280 * @param array $contact Target of the communication
3281 * @param int $uid User ID
3283 * @return int The result of the transmission
3284 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3285 * @throws \ImagickException
3287 public static function sendAccountMigration(array $owner, array $contact, $uid)
3289 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3290 $profile = self::createProfileData($uid);
3292 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3293 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3295 $message = ["author" => $old_handle,
3296 "profile" => $profile,
3297 "signature" => $signature];
3299 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3301 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3305 * @brief Sends a "share" message
3307 * @param array $owner the array of the item owner
3308 * @param array $contact Target of the communication
3310 * @return int The result of the transmission
3311 * @throws \Exception
3313 public static function sendShare(array $owner, array $contact)
3316 * @todo support the different possible combinations of "following" and "sharing"
3317 * Currently, Diaspora only interprets the "sharing" field
3319 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3323 switch ($contact["rel"]) {
3324 case Contact::FRIEND:
3328 case Contact::SHARING:
3332 case Contact::FOLLOWER:
3338 $message = ["author" => self::myHandle($owner),
3339 "recipient" => $contact["addr"],
3340 "following" => "true",
3341 "sharing" => "true"];
3343 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3345 return self::buildAndTransmit($owner, $contact, "contact", $message);
3349 * @brief sends an "unshare"
3351 * @param array $owner the array of the item owner
3352 * @param array $contact Target of the communication
3354 * @return int The result of the transmission
3355 * @throws \Exception
3357 public static function sendUnshare(array $owner, array $contact)
3359 $message = ["author" => self::myHandle($owner),
3360 "recipient" => $contact["addr"],
3361 "following" => "false",
3362 "sharing" => "false"];
3364 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3366 return self::buildAndTransmit($owner, $contact, "contact", $message);
3370 * @brief Checks a message body if it is a reshare
3372 * @param string $body The message body that is to be check
3373 * @param bool $complete Should it be a complete check or a simple check?
3375 * @return array|bool Reshare details or "false" if no reshare
3376 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3377 * @throws \ImagickException
3379 public static function isReshare($body, $complete = true)
3381 $body = trim($body);
3383 // Skip if it isn't a pure repeated messages
3384 // Does it start with a share?
3385 if ((strpos($body, "[share") > 0) && $complete) {
3389 // Does it end with a share?
3390 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3394 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3395 // Skip if there is no shared message in there
3396 if ($body == $attributes) {
3400 // If we don't do the complete check we quit here
3403 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3404 if (!empty($matches[1])) {
3405 $guid = $matches[1];
3408 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3409 if (!empty($matches[1])) {
3410 $guid = $matches[1];
3413 if (($guid != "") && $complete) {
3414 $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3415 $item = Item::selectFirst(['contact-id'], $condition);
3416 if (DBA::isResult($item)) {
3418 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3419 $ret["root_guid"] = $guid;
3421 } elseif ($complete) {
3422 // We are resharing something that isn't a DFRN or Diaspora post.
3423 // So we have to return "false" on "$complete" to not trigger a reshare.
3426 } elseif (($guid == "") && $complete) {
3430 $ret["root_guid"] = $guid;
3433 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3434 if (!empty($matches[1])) {
3435 $profile = $matches[1];
3438 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3439 if (!empty($matches[1])) {
3440 $profile = $matches[1];
3445 if ($profile != "") {
3446 if (Contact::getIdForURL($profile)) {
3447 $author = Contact::getDetailsByURL($profile);
3448 $ret["root_handle"] = $author['addr'];
3452 if (empty($ret) && !$complete) {
3460 * @brief Create an event array
3462 * @param integer $event_id The id of the event
3464 * @return array with event data
3465 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3467 private static function buildEvent($event_id)
3469 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3470 if (!DBA::isResult($r)) {
3478 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3479 if (!DBA::isResult($r)) {
3485 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3486 if (!DBA::isResult($r)) {
3492 $eventdata['author'] = self::myHandle($owner);
3494 if ($event['guid']) {
3495 $eventdata['guid'] = $event['guid'];
3498 $mask = DateTimeFormat::ATOM;
3500 /// @todo - establish "all day" events in Friendica
3501 $eventdata["all_day"] = "false";
3503 $eventdata['timezone'] = 'UTC';
3504 if (!$event['adjust'] && $user['timezone']) {
3505 $eventdata['timezone'] = $user['timezone'];
3508 if ($event['start']) {
3509 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3511 if ($event['finish'] && !$event['nofinish']) {
3512 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3514 if ($event['summary']) {
3515 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3517 if ($event['desc']) {
3518 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3520 if ($event['location']) {
3521 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3522 $coord = Map::getCoordinates($event['location']);
3525 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3526 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3527 $location["lat"] = $coord['lat'];
3528 $location["lng"] = $coord['lon'];
3530 $location["lat"] = 0;
3531 $location["lng"] = 0;
3533 $eventdata['location'] = $location;
3540 * @brief Create a post (status message or reshare)
3542 * @param array $item The item that will be exported
3543 * @param array $owner the array of the item owner
3546 * 'type' -> Message type ("status_message" or "reshare")
3547 * 'message' -> Array of XML elements of the status
3548 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3549 * @throws \ImagickException
3551 public static function buildStatus(array $item, array $owner)
3553 $cachekey = "diaspora:buildStatus:".$item['guid'];
3555 $result = Cache::get($cachekey);
3556 if (!is_null($result)) {
3560 $myaddr = self::myHandle($owner);
3562 $public = ($item["private"] ? "false" : "true");
3564 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3566 // Detect a share element and do a reshare
3567 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3568 $message = ["author" => $myaddr,
3569 "guid" => $item["guid"],
3570 "created_at" => $created,
3571 "root_author" => $ret["root_handle"],
3572 "root_guid" => $ret["root_guid"],
3573 "provider_display_name" => $item["app"],
3574 "public" => $public];
3578 $title = $item["title"];
3579 $body = $item["body"];
3581 if ($item['author-link'] != $item['owner-link']) {
3582 require_once 'mod/share.php';
3583 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3584 "", $item['created'], $item['plink']) . $body . '[/share]';
3587 // convert to markdown
3588 $body = html_entity_decode(BBCode::toMarkdown($body));
3591 if (strlen($title)) {
3592 $body = "## ".html_entity_decode($title)."\n\n".$body;
3595 if ($item["attach"]) {
3596 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3598 $body .= "\n".L10n::t("Attachments:")."\n";
3599 foreach ($matches as $mtch) {
3600 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3607 if ($item["location"] != "")
3608 $location["address"] = $item["location"];
3610 if ($item["coord"] != "") {
3611 $coord = explode(" ", $item["coord"]);
3612 $location["lat"] = $coord[0];
3613 $location["lng"] = $coord[1];
3616 $message = ["author" => $myaddr,
3617 "guid" => $item["guid"],
3618 "created_at" => $created,
3619 "public" => $public,
3621 "provider_display_name" => $item["app"],
3622 "location" => $location];
3624 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3625 if (!isset($location["lat"]) || !isset($location["lng"])) {
3626 unset($message["location"]);
3629 if ($item['event-id'] > 0) {
3630 $event = self::buildEvent($item['event-id']);
3631 if (count($event)) {
3632 $message['event'] = $event;
3634 if (!empty($event['location']['address']) &&
3635 !empty($event['location']['lat']) &&
3636 !empty($event['location']['lng'])) {
3637 $message['location'] = $event['location'];
3640 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3641 // $message['text'] = '';
3645 $type = "status_message";
3648 $msg = ["type" => $type, "message" => $message];
3650 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
3655 private static function prependParentAuthorMention($body, $profile_url)
3657 $profile = Contact::getDetailsByURL($profile_url);
3658 if (!empty($profile['addr'])
3659 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3660 && !strstr($body, $profile['addr'])
3661 && !strstr($body, $profile_url)
3663 $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3670 * @brief Sends a post
3672 * @param array $item The item that will be exported
3673 * @param array $owner the array of the item owner
3674 * @param array $contact Target of the communication
3675 * @param bool $public_batch Is it a public post?
3677 * @return int The result of the transmission
3678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3679 * @throws \ImagickException
3681 public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3683 $status = self::buildStatus($item, $owner);
3685 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3689 * @brief Creates a "like" object
3691 * @param array $item The item that will be exported
3692 * @param array $owner the array of the item owner
3694 * @return array The data for a "like"
3695 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3697 private static function constructLike(array $item, array $owner)
3699 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3700 if (!DBA::isResult($parent)) {
3704 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3706 if ($item['verb'] === ACTIVITY_LIKE) {
3708 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3709 $positive = "false";
3712 return(["author" => self::myHandle($owner),
3713 "guid" => $item["guid"],
3714 "parent_guid" => $parent["guid"],
3715 "parent_type" => $target_type,
3716 "positive" => $positive,
3717 "author_signature" => ""]);
3721 * @brief Creates an "EventParticipation" object
3723 * @param array $item The item that will be exported
3724 * @param array $owner the array of the item owner
3726 * @return array The data for an "EventParticipation"
3727 * @throws \Exception
3729 private static function constructAttend(array $item, array $owner)
3731 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3732 if (!DBA::isResult($parent)) {
3736 switch ($item['verb']) {
3737 case ACTIVITY_ATTEND:
3738 $attend_answer = 'accepted';
3740 case ACTIVITY_ATTENDNO:
3741 $attend_answer = 'declined';
3743 case ACTIVITY_ATTENDMAYBE:
3744 $attend_answer = 'tentative';
3747 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3751 return(["author" => self::myHandle($owner),
3752 "guid" => $item["guid"],
3753 "parent_guid" => $parent["guid"],
3754 "status" => $attend_answer,
3755 "author_signature" => ""]);
3759 * @brief Creates the object for a comment
3761 * @param array $item The item that will be exported
3762 * @param array $owner the array of the item owner
3764 * @return array|false The data for a comment
3765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3767 private static function constructComment(array $item, array $owner)
3769 $cachekey = "diaspora:constructComment:".$item['guid'];
3771 $result = Cache::get($cachekey);
3772 if (!is_null($result)) {
3776 $toplevel_item = Item::selectFirst(['guid', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3777 if (!DBA::isResult($toplevel_item)) {
3778 Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3782 $thread_parent_item = $toplevel_item;
3783 if ($item['thr-parent'] != $item['parent-uri']) {
3784 $thread_parent_item = Item::selectFirst(['guid', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3787 $body = $item["body"];
3789 if ((empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3790 && !Config::get('system', 'disable_implicit_mentions')
3792 $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3795 $text = html_entity_decode(BBCode::toMarkdown($body));
3796 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3799 "author" => self::myHandle($owner),
3800 "guid" => $item["guid"],
3801 "created_at" => $created,
3802 "parent_guid" => $toplevel_item["guid"],
3804 "author_signature" => ""
3807 // Send the thread parent guid only if it is a threaded comment
3808 if ($item['thr-parent'] != $item['parent-uri']) {
3809 $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3812 Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
3818 * @brief Send a like or a comment
3820 * @param array $item The item that will be exported
3821 * @param array $owner the array of the item owner
3822 * @param array $contact Target of the communication
3823 * @param bool $public_batch Is it a public post?
3825 * @return int The result of the transmission
3826 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3827 * @throws \ImagickException
3829 public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3831 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3832 $message = self::constructAttend($item, $owner);
3833 $type = "event_participation";
3834 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3835 $message = self::constructLike($item, $owner);
3837 } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW, ACTIVITY_TAG])) {
3838 $message = self::constructComment($item, $owner);
3842 if (empty($message)) {
3846 $message["author_signature"] = self::signature($owner, $message);
3848 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3852 * @brief Creates a message from a signature record entry
3854 * @param array $item The item that will be exported
3855 * @return array The message
3857 private static function messageFromSignature(array $item)
3859 // Split the signed text
3860 $signed_parts = explode(";", $item['signed_text']);
3862 if ($item["deleted"]) {
3863 $message = ["author" => $item['signer'],
3864 "target_guid" => $signed_parts[0],
3865 "target_type" => $signed_parts[1]];
3866 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3867 $message = ["author" => $signed_parts[4],
3868 "guid" => $signed_parts[1],
3869 "parent_guid" => $signed_parts[3],
3870 "parent_type" => $signed_parts[2],
3871 "positive" => $signed_parts[0],
3872 "author_signature" => $item['signature'],
3873 "parent_author_signature" => ""];
3875 // Remove the comment guid
3876 $guid = array_shift($signed_parts);
3878 // Remove the parent guid
3879 $parent_guid = array_shift($signed_parts);
3881 // Remove the handle
3882 $handle = array_pop($signed_parts);
3885 "author" => $handle,
3887 "parent_guid" => $parent_guid,
3888 "text" => implode(";", $signed_parts),
3889 "author_signature" => $item['signature'],
3890 "parent_author_signature" => ""
3897 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3899 * @param array $item The item that will be exported
3900 * @param array $owner the array of the item owner
3901 * @param array $contact Target of the communication
3902 * @param bool $public_batch Is it a public post?
3904 * @return int The result of the transmission
3905 * @throws \Exception
3907 public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3909 if ($item["deleted"]) {
3910 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3911 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3917 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3919 // Old way - is used by the internal Friendica functions
3920 /// @todo Change all signatur storing functions to the new format
3921 if ($item['signed_text'] && $item['signature'] && $item['signer']) {
3922 $message = self::messageFromSignature($item);
3924 $msg = json_decode($item['signed_text'], true);
3927 if (is_array($msg)) {
3928 foreach ($msg as $field => $data) {
3929 if (!$item["deleted"]) {
3930 if ($field == "diaspora_handle") {
3933 if ($field == "target_type") {
3934 $field = "parent_type";
3938 $message[$field] = $data;
3941 Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3945 $message["parent_author_signature"] = self::signature($owner, $message);
3947 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
3949 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3953 * @brief Sends a retraction (deletion) of a message, like or comment
3955 * @param array $item The item that will be exported
3956 * @param array $owner the array of the item owner
3957 * @param array $contact Target of the communication
3958 * @param bool $public_batch Is it a public post?
3959 * @param bool $relay Is the retraction transmitted from a relay?
3961 * @return int The result of the transmission
3962 * @throws \Exception
3964 public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3966 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3968 $msg_type = "retraction";
3970 if ($item['id'] == $item['parent']) {
3971 $target_type = "Post";
3972 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3973 $target_type = "Like";
3975 $target_type = "Comment";
3978 $message = ["author" => $itemaddr,
3979 "target_guid" => $item['guid'],
3980 "target_type" => $target_type];
3982 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
3984 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3988 * @brief Sends a mail
3990 * @param array $item The item that will be exported
3991 * @param array $owner The owner
3992 * @param array $contact Target of the communication
3994 * @return int The result of the transmission
3995 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3996 * @throws \ImagickException
3998 public static function sendMail(array $item, array $owner, array $contact)
4000 $myaddr = self::myHandle($owner);
4002 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4003 if (!DBA::isResult($cnv)) {
4004 Logger::log("conversation not found.");
4008 $body = BBCode::toMarkdown($item["body"]);
4009 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4012 "author" => $myaddr,
4013 "guid" => $item["guid"],
4014 "conversation_guid" => $cnv["guid"],
4016 "created_at" => $created,
4019 if ($item["reply"]) {
4024 "author" => $cnv["creator"],
4025 "guid" => $cnv["guid"],
4026 "subject" => $cnv["subject"],
4027 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4028 "participants" => $cnv["recips"],
4032 $type = "conversation";
4035 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4039 * @brief Split a name into first name and last name
4041 * @param string $name The name
4043 * @return array The array with "first" and "last"
4045 public static function splitName($name) {
4046 $name = trim($name);
4048 // Is the name longer than 64 characters? Then cut the rest of it.
4049 if (strlen($name) > 64) {
4050 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4051 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4053 $name = substr($name, 0, 64);
4057 // Take the first word as first name
4058 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4059 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4060 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4061 return ['first' => $first, 'last' => $last];
4064 // Take the last word as last name
4065 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4066 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4068 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4069 return ['first' => $first, 'last' => $last];
4072 // Take the first 32 characters if there is no space in the first 32 characters
4073 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4074 $first = substr($name, 0, 32);
4075 $last = substr($name, 32);
4076 return ['first' => $first, 'last' => $last];
4079 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4080 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4082 // Check if the last name is longer than 32 characters
4083 if (strlen($last) > 32) {
4084 if (strpos($last, ' ') <= 32) {
4085 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4087 $last = substr($last, 0, 32);
4091 return ['first' => $first, 'last' => $last];
4095 * @brief Create profile data
4097 * @param int $uid The user id
4099 * @return array The profile data
4100 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4102 private static function createProfileData($uid)
4105 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4107 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4108 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4109 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4118 $handle = $profile["addr"];
4120 $split_name = self::splitName($profile['name']);
4121 $first = $split_name['first'];
4122 $last = $split_name['last'];
4124 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4125 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4126 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4127 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4133 if ($searchable === 'true') {
4136 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4137 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4141 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4144 $about = $profile['about'];
4145 $about = strip_tags(BBCode::convert($about));
4147 $location = Profile::formatLocation($profile);
4149 if ($profile['pub_keywords']) {
4150 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4151 $kw = str_replace(' ', ' ', $kw);
4152 $arr = explode(' ', $kw);
4154 for ($x = 0; $x < 5; $x ++) {
4155 if (!empty($arr[$x])) {
4156 $tags .= '#'. trim($arr[$x]) .' ';
4161 $tags = trim($tags);
4164 return ["author" => $handle,
4165 "first_name" => $first,
4166 "last_name" => $last,
4167 "image_url" => $large,
4168 "image_url_medium" => $medium,
4169 "image_url_small" => $small,
4171 "gender" => $profile['gender'],
4173 "location" => $location,
4174 "searchable" => $searchable,
4176 "tag_string" => $tags];
4180 * @brief Sends profile data
4182 * @param int $uid The user id
4183 * @param bool $recips optional, default false
4185 * @throws \Exception
4187 public static function sendProfile($uid, $recips = false)
4193 $owner = User::getOwnerDataById($uid);
4200 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4201 AND `uid` = %d AND `rel` != %d",
4202 DBA::escape(Protocol::DIASPORA),
4204 intval(Contact::SHARING)
4212 $message = self::createProfileData($uid);
4214 foreach ($recips as $recip) {
4215 Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4216 self::buildAndTransmit($owner, $recip, "profile", $message, false, '', true);
4221 * @brief Creates the signature for likes that are created on our system
4223 * @param integer $uid The user of that comment
4224 * @param array $item Item array
4226 * @return array Signed content
4227 * @throws \Exception
4229 public static function createLikeSignature($uid, array $item)
4231 $owner = User::getOwnerDataById($uid);
4232 if (empty($owner)) {
4233 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4237 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4241 $message = self::constructLike($item, $owner);
4242 if ($message === false) {
4246 $message["author_signature"] = self::signature($owner, $message);
4252 * @brief Creates the signature for Comments that are created on our system
4254 * @param integer $uid The user of that comment
4255 * @param array $item Item array
4257 * @return array Signed content
4258 * @throws \Exception
4260 public static function createCommentSignature($uid, array $item)
4262 $owner = User::getOwnerDataById($uid);
4263 if (empty($owner)) {
4264 Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4268 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4269 $item['thr-parent'] = $item['parent-uri'];
4271 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4272 if (!DBA::isResult($parent)) {
4276 $item['parent-uri'] = $parent['parent-uri'];
4278 $message = self::constructComment($item, $owner);
4279 if ($message === false) {
4283 $message["author_signature"] = self::signature($owner, $message);