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\Text\BBCode;
14 use Friendica\Content\Text\Markdown;
15 use Friendica\Core\Cache;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\Queue;
28 use Friendica\Model\User;
29 use Friendica\Network\Probe;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Util\Map;
38 require_once 'include/dba.php';
39 require_once 'include/items.php';
42 * @brief This class contain functions to create and send Diaspora XML files
48 * @brief Return a list of relay servers
50 * The list contains not only the official relays but also servers that we serve directly
52 * @param integer $item_id The id of the item that is sent
53 * @param array $contacts The previously fetched contacts
55 * @return array of relay servers
57 public static function relayList($item_id, $contacts = [])
61 // Fetching relay servers
62 $serverdata = Config::get("system", "relay_server");
63 if ($serverdata != "") {
64 $servers = explode(",", $serverdata);
65 foreach ($servers as $server) {
66 $serverlist[$server] = trim($server);
70 if (Config::get("system", "relay_directly", false)) {
71 // Servers that want to get all content
72 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
73 while ($server = dba::fetch($servers)) {
74 $serverlist[$server['url']] = $server['url'];
77 // All tags of the current post
78 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $item_id];
79 $tags = dba::select('term', ['term'], $condition);
81 while ($tag = dba::fetch($tags)) {
82 $taglist[] = $tag['term'];
85 // All servers who wants content with this tag
87 if (!empty($taglist)) {
88 $tagserver = dba::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
89 while ($server = dba::fetch($tagserver)) {
90 $tagserverlist[] = $server['gserver-id'];
94 // All adresses with the given id
95 if (!empty($tagserverlist)) {
96 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
97 while ($server = dba::fetch($servers)) {
98 $serverlist[$server['url']] = $server['url'];
103 // Now we are collecting all relay contacts
104 foreach ($serverlist as $server_url) {
105 // We don't send messages to ourselves
106 if (link_compare($server_url, System::baseUrl())) {
109 $contact = self::getRelayContact($server_url);
110 if (is_bool($contact)) {
115 foreach ($contacts as $entry) {
116 if ($entry['batch'] == $contact['batch']) {
122 $contacts[] = $contact;
130 * @brief Return a contact for a given server address or creates a dummy entry
132 * @param string $server_url The url of the server
133 * @return array with the contact
135 private static function getRelayContact($server_url)
137 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
139 // Fetch the relay contact
140 $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
141 'contact-type' => ACCOUNT_TYPE_RELAY];
142 $contact = dba::selectFirst('contact', $fields, $condition);
144 if (DBM::is_result($contact)) {
145 if ($contact['archive'] || $contact['blocked']) {
150 self::setRelayContact($server_url);
152 $contact = dba::selectFirst('contact', $fields, $condition);
153 if (DBM::is_result($contact)) {
158 // It should never happen that we arrive here
163 * @brief Update or insert a relay contact
165 * @param string $server_url The url of the server
166 * @param array $network_fields Optional network specific fields
168 public static function setRelayContact($server_url, $network_fields = [])
170 $fields = ['created' => DateTimeFormat::utcNow(),
171 'name' => 'relay', 'nick' => 'relay',
172 'url' => $server_url, 'network' => NETWORK_DIASPORA,
173 'batch' => $server_url . '/receive/public',
174 'rel' => CONTACT_IS_FOLLOWER, 'blocked' => false,
175 'pending' => false, 'writable' => true];
177 $fields = array_merge($fields, $network_fields);
179 $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
180 'contact-type' => ACCOUNT_TYPE_RELAY];
182 if (dba::exists('contact', $condition)) {
183 unset($fields['created']);
186 dba::update('contact', $fields, $condition, true);
190 * @brief Return a list of participating contacts for a thread
192 * This is used for the participation feature.
193 * One of the parameters is a contact array.
194 * This is done to avoid duplicates.
196 * @param integer $thread The id of the thread
197 * @param array $contacts The previously fetched contacts
199 * @return array of relay servers
201 public static function participantsForThread($thread, $contacts)
203 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
204 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
205 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
206 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
207 WHERE `participation`.`iid` = ?", $thread);
209 while ($contact = dba::fetch($r)) {
210 if (!empty($contact['fnetwork'])) {
211 $contact['network'] = $contact['fnetwork'];
213 unset($contact['fnetwork']);
215 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
216 $contact['batch'] = $contact['fbatch'];
218 unset($contact['fbatch']);
221 foreach ($contacts as $entry) {
222 if ($entry['batch'] == $contact['batch']) {
228 $contacts[] = $contact;
237 * @brief repairs a signature that was double encoded
239 * The function is unused at the moment. It was copied from the old implementation.
241 * @param string $signature The signature
242 * @param string $handle The handle of the signature owner
243 * @param integer $level This value is only set inside this function to avoid endless loops
245 * @return string the repaired signature
247 private static function repairSignature($signature, $handle = "", $level = 1)
249 if ($signature == "") {
253 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
254 $signature = base64_decode($signature);
255 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
257 // Do a recursive call to be able to fix even multiple levels
259 $signature = self::repairSignature($signature, $handle, ++$level);
267 * @brief verify the envelope and return the verified data
269 * @param string $envelope The magic envelope
271 * @return string verified data
273 private static function verifyMagicEnvelope($envelope)
275 $basedom = XML::parseString($envelope);
277 if (!is_object($basedom)) {
278 logger("Envelope is no XML file");
282 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
284 if (sizeof($children) == 0) {
285 logger("XML has no children");
291 $data = base64url_decode($children->data);
292 $type = $children->data->attributes()->type[0];
294 $encoding = $children->encoding;
296 $alg = $children->alg;
298 $sig = base64url_decode($children->sig);
299 $key_id = $children->sig->attributes()->key_id[0];
301 $handle = base64url_decode($key_id);
304 $b64url_data = base64url_encode($data);
305 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
307 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
310 logger('No author could be decoded. Discarding. Message: ' . $envelope);
314 $key = self::key($handle);
316 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
320 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
322 logger('Message from ' . $handle . ' did not verify. Discarding.');
330 * @brief encrypts data via AES
332 * @param string $key The AES key
333 * @param string $iv The IV (is used for CBC encoding)
334 * @param string $data The data that is to be encrypted
336 * @return string encrypted data
338 private static function aesEncrypt($key, $iv, $data)
340 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
344 * @brief decrypts data via AES
346 * @param string $key The AES key
347 * @param string $iv The IV (is used for CBC encoding)
348 * @param string $encrypted The encrypted data
350 * @return string decrypted data
352 private static function aesDecrypt($key, $iv, $encrypted)
354 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
358 * @brief: Decodes incoming Diaspora message in the new format
360 * @param array $importer Array of the importer user
361 * @param string $raw raw post message
364 * 'message' -> decoded Diaspora XML message
365 * 'author' -> author diaspora handle
366 * 'key' -> author public key (converted to pkcs#8)
368 public static function decodeRaw($importer, $raw)
370 $data = json_decode($raw);
372 // Is it a private post? Then decrypt the outer Salmon
373 if (is_object($data)) {
374 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
375 $ciphertext = base64_decode($data->encrypted_magic_envelope);
377 $outer_key_bundle = '';
378 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
379 $j_outer_key_bundle = json_decode($outer_key_bundle);
381 if (!is_object($j_outer_key_bundle)) {
382 logger('Outer Salmon did not verify. Discarding.');
383 System::httpExit(400);
386 $outer_iv = base64_decode($j_outer_key_bundle->iv);
387 $outer_key = base64_decode($j_outer_key_bundle->key);
389 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
394 $basedom = XML::parseString($xml);
396 if (!is_object($basedom)) {
397 logger('Received data does not seem to be an XML. Discarding. '.$xml);
398 System::httpExit(400);
401 $base = $basedom->children(NAMESPACE_SALMON_ME);
403 // Not sure if this cleaning is needed
404 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
406 // Build the signed data
407 $type = $base->data[0]->attributes()->type[0];
408 $encoding = $base->encoding;
410 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
412 // This is the signature
413 $signature = base64url_decode($base->sig);
415 // Get the senders' public key
416 $key_id = $base->sig[0]->attributes()->key_id[0];
417 $author_addr = base64_decode($key_id);
418 if ($author_addr == '') {
419 logger('No author could be decoded. Discarding. Message: ' . $xml);
420 System::httpExit(400);
423 $key = self::key($author_addr);
425 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
426 System::httpExit(400);
429 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
431 logger('Message did not verify. Discarding.');
432 System::httpExit(400);
435 return ['message' => (string)base64url_decode($base->data),
436 'author' => unxmlify($author_addr),
437 'key' => (string)$key];
441 * @brief: Decodes incoming Diaspora message in the deprecated format
443 * @param array $importer Array of the importer user
444 * @param string $xml urldecoded Diaspora salmon
447 * 'message' -> decoded Diaspora XML message
448 * 'author' -> author diaspora handle
449 * 'key' -> author public key (converted to pkcs#8)
451 public static function decode($importer, $xml)
454 $basedom = XML::parseString($xml);
456 if (!is_object($basedom)) {
457 logger("XML is not parseable.");
460 $children = $basedom->children('https://joindiaspora.com/protocol');
462 $inner_aes_key = null;
465 if ($children->header) {
467 $author_link = str_replace('acct:', '', $children->header->author_id);
469 // This happens with posts from a relais
471 logger("This is no private post in the old format", LOGGER_DEBUG);
475 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
477 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
478 $ciphertext = base64_decode($encrypted_header->ciphertext);
480 $outer_key_bundle = '';
481 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
483 $j_outer_key_bundle = json_decode($outer_key_bundle);
485 $outer_iv = base64_decode($j_outer_key_bundle->iv);
486 $outer_key = base64_decode($j_outer_key_bundle->key);
488 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
490 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
491 $idom = XML::parseString($decrypted);
493 $inner_iv = base64_decode($idom->iv);
494 $inner_aes_key = base64_decode($idom->aes_key);
496 $author_link = str_replace('acct:', '', $idom->author_id);
499 $dom = $basedom->children(NAMESPACE_SALMON_ME);
501 // figure out where in the DOM tree our data is hiding
504 if ($dom->provenance->data) {
505 $base = $dom->provenance;
506 } elseif ($dom->env->data) {
508 } elseif ($dom->data) {
513 logger('unable to locate salmon data in xml');
514 System::httpExit(400);
518 // Stash the signature away for now. We have to find their key or it won't be good for anything.
519 $signature = base64url_decode($base->sig);
523 // strip whitespace so our data element will return to one big base64 blob
524 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
527 // stash away some other stuff for later
529 $type = $base->data[0]->attributes()->type[0];
530 $keyhash = $base->sig[0]->attributes()->keyhash[0];
531 $encoding = $base->encoding;
535 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
539 $data = base64url_decode($data);
543 $inner_decrypted = $data;
545 // Decode the encrypted blob
546 $inner_encrypted = base64_decode($data);
547 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
551 logger('Could not retrieve author URI.');
552 System::httpExit(400);
554 // Once we have the author URI, go to the web and try to find their public key
555 // (first this will look it up locally if it is in the fcontact cache)
556 // This will also convert diaspora public key from pkcs#1 to pkcs#8
558 logger('Fetching key for '.$author_link);
559 $key = self::key($author_link);
562 logger('Could not retrieve author key.');
563 System::httpExit(400);
566 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
569 logger('Message did not verify. Discarding.');
570 System::httpExit(400);
573 logger('Message verified.');
575 return ['message' => (string)$inner_decrypted,
576 'author' => unxmlify($author_link),
577 'key' => (string)$key];
582 * @brief Dispatches public messages and find the fitting receivers
584 * @param array $msg The post that will be dispatched
586 * @return int The message id of the generated message, "true" or "false" if there was an error
588 public static function dispatchPublic($msg)
590 $enabled = intval(Config::get("system", "diaspora_enabled"));
592 logger("diaspora is disabled");
596 if (!($fields = self::validPosting($msg))) {
597 logger("Invalid posting");
601 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
602 $success = self::dispatch($importer, $msg, $fields);
608 * @brief Dispatches the different message types to the different functions
610 * @param array $importer Array of the importer user
611 * @param array $msg The post that will be dispatched
612 * @param object $fields SimpleXML object that contains the message
614 * @return int The message id of the generated message, "true" or "false" if there was an error
616 public static function dispatch($importer, $msg, $fields = null)
618 // The sender is the handle of the contact that sent the message.
619 // This will often be different with relayed messages (for example "like" and "comment")
620 $sender = $msg["author"];
622 // This is only needed for private postings since this is already done for public ones before
623 if (is_null($fields)) {
625 if (!($fields = self::validPosting($msg))) {
626 logger("Invalid posting");
633 $type = $fields->getName();
635 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
638 case "account_migration":
640 logger('Message with type ' . $type . ' is not private, quitting.');
643 return self::receiveAccountMigration($importer, $fields);
645 case "account_deletion":
646 return self::receiveAccountDeletion($fields);
649 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
653 logger('Message with type ' . $type . ' is not private, quitting.');
656 return self::receiveContactRequest($importer, $fields);
660 logger('Message with type ' . $type . ' is not private, quitting.');
663 return self::receiveConversation($importer, $msg, $fields);
666 return self::receiveLike($importer, $sender, $fields);
670 logger('Message with type ' . $type . ' is not private, quitting.');
673 return self::receiveMessage($importer, $fields);
675 case "participation":
677 logger('Message with type ' . $type . ' is not private, quitting.');
680 return self::receiveParticipation($importer, $fields);
682 case "photo": // Not implemented
683 return self::receivePhoto($importer, $fields);
685 case "poll_participation": // Not implemented
686 return self::receivePollParticipation($importer, $fields);
690 logger('Message with type ' . $type . ' is not private, quitting.');
693 return self::receiveProfile($importer, $fields);
696 return self::receiveReshare($importer, $fields, $msg["message"]);
699 return self::receiveRetraction($importer, $sender, $fields);
701 case "status_message":
702 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
705 logger("Unknown message type ".$type);
713 * @brief Checks if a posting is valid and fetches the data fields.
715 * This function does not only check the signature.
716 * It also does the conversion between the old and the new diaspora format.
718 * @param array $msg Array with the XML, the sender handle and the sender signature
720 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
722 private static function validPosting($msg)
724 $data = XML::parseString($msg["message"]);
726 if (!is_object($data)) {
727 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
731 // Is this the new or the old version?
732 if ($data->getName() == "XML") {
734 foreach ($data->post->children() as $child) {
742 $type = $element->getName();
745 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
747 // All retractions are handled identically from now on.
748 // In the new version there will only be "retraction".
749 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
750 $type = "retraction";
752 if ($type == "request") {
756 $fields = new SimpleXMLElement("<".$type."/>");
759 $author_signature = null;
760 $parent_author_signature = null;
762 foreach ($element->children() as $fieldname => $entry) {
764 // Translation for the old XML structure
765 if ($fieldname == "diaspora_handle") {
766 $fieldname = "author";
768 if ($fieldname == "participant_handles") {
769 $fieldname = "participants";
771 if (in_array($type, ["like", "participation"])) {
772 if ($fieldname == "target_type") {
773 $fieldname = "parent_type";
776 if ($fieldname == "sender_handle") {
777 $fieldname = "author";
779 if ($fieldname == "recipient_handle") {
780 $fieldname = "recipient";
782 if ($fieldname == "root_diaspora_id") {
783 $fieldname = "root_author";
785 if ($type == "status_message") {
786 if ($fieldname == "raw_message") {
790 if ($type == "retraction") {
791 if ($fieldname == "post_guid") {
792 $fieldname = "target_guid";
794 if ($fieldname == "type") {
795 $fieldname = "target_type";
800 if (($fieldname == "author_signature") && ($entry != "")) {
801 $author_signature = base64_decode($entry);
802 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
803 $parent_author_signature = base64_decode($entry);
804 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
805 if ($signed_data != "") {
809 $signed_data .= $entry;
811 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
812 || ($orig_type == "relayable_retraction")
814 XML::copy($entry, $fields, $fieldname);
818 // This is something that shouldn't happen at all.
819 if (in_array($type, ["status_message", "reshare", "profile"])) {
820 if ($msg["author"] != $fields->author) {
821 logger("Message handle is not the same as envelope sender. Quitting this message.");
826 // Only some message types have signatures. So we quit here for the other types.
827 if (!in_array($type, ["comment", "like"])) {
830 // No author_signature? This is a must, so we quit.
831 if (!isset($author_signature)) {
832 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
836 if (isset($parent_author_signature)) {
837 $key = self::key($msg["author"]);
839 logger("No key found for parent author ".$msg["author"], LOGGER_DEBUG);
843 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
844 logger("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);
849 $key = self::key($fields->author);
851 logger("No key found for author ".$fields->author, LOGGER_DEBUG);
855 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
856 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
864 * @brief Fetches the public key for a given handle
866 * @param string $handle The handle
868 * @return string The public key
870 private static function key($handle)
872 $handle = strval($handle);
874 logger("Fetching diaspora key for: ".$handle);
876 $r = self::personByHandle($handle);
885 * @brief Fetches data for a given handle
887 * @param string $handle The handle
889 * @return array the queried data
891 public static function personByHandle($handle)
895 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
896 if (DBM::is_result($person)) {
897 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
899 // update record occasionally so it doesn't get stale
900 $d = strtotime($person["updated"]." +00:00");
901 if ($d < strtotime("now - 14 days")) {
905 if ($person["guid"] == "") {
910 if (!DBM::is_result($person) || $update) {
911 logger("create or refresh", LOGGER_DEBUG);
912 $r = Probe::uri($handle, NETWORK_DIASPORA);
914 // Note that Friendica contacts will return a "Diaspora person"
915 // if Diaspora connectivity is enabled on their server
916 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
917 self::addFContact($r, $update);
919 // Fetch the updated or added contact
920 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
921 if (!DBM::is_result($person)) {
931 * @brief Updates the fcontact table
933 * @param array $arr The fcontact data
934 * @param bool $update Update or insert?
936 * @return string The id of the fcontact entry
938 private static function addFContact($arr, $update = false)
942 "UPDATE `fcontact` SET
956 WHERE `url` = '%s' AND `network` = '%s'",
958 dbesc($arr["photo"]),
959 dbesc($arr["request"]),
961 dbesc(strtolower($arr["addr"])),
963 dbesc($arr["batch"]),
964 dbesc($arr["notify"]),
966 dbesc($arr["confirm"]),
967 dbesc($arr["alias"]),
968 dbesc($arr["pubkey"]),
969 dbesc(DateTimeFormat::utcNow()),
971 dbesc($arr["network"])
975 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
976 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
977 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
980 dbesc($arr["photo"]),
981 dbesc($arr["request"]),
985 dbesc($arr["batch"]),
986 dbesc($arr["notify"]),
988 dbesc($arr["confirm"]),
989 dbesc($arr["network"]),
990 dbesc($arr["alias"]),
991 dbesc($arr["pubkey"]),
992 dbesc(DateTimeFormat::utcNow())
1000 * @brief get a handle (user@domain.tld) from a given contact id
1002 * @param int $contact_id The id in the contact table
1003 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1005 * @return string the handle
1007 private static function handleFromContact($contact_id, $pcontact_id = 0)
1011 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
1013 if ($pcontact_id != 0) {
1015 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
1016 intval($pcontact_id)
1019 if (DBM::is_result($r)) {
1020 return strtolower($r[0]["addr"]);
1025 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1029 if (DBM::is_result($r)) {
1032 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
1034 if ($contact['addr'] != "") {
1035 $handle = $contact['addr'];
1037 $baseurl_start = strpos($contact['url'], '://') + 3;
1038 // allows installations in a subdirectory--not sure how Diaspora will handle
1039 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1040 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1041 $handle = $contact['nick'].'@'.$baseurl;
1045 return strtolower($handle);
1049 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1052 * @param mixed $fcontact_guid Hexadecimal string guid
1054 * @return string the contact url or null
1056 public static function urlFromContactGuid($fcontact_guid)
1058 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
1061 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1062 dbesc(NETWORK_DIASPORA),
1063 dbesc($fcontact_guid)
1066 if (DBM::is_result($r)) {
1067 return $r[0]['url'];
1074 * @brief Get a contact id for a given handle
1076 * @todo Move to Friendica\Model\Contact
1078 * @param int $uid The user id
1079 * @param string $handle The handle in the format user@domain.tld
1081 * @return int Contact id
1083 private static function contactByHandle($uid, $handle)
1085 // First do a direct search on the contact table
1087 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1092 if (DBM::is_result($r)) {
1096 * We haven't found it?
1097 * We use another function for it that will possibly create a contact entry.
1099 $cid = Contact::getIdForURL($handle, $uid);
1102 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1103 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1105 if (DBM::is_result($r)) {
1111 $handle_parts = explode("@", $handle);
1112 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1114 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1115 dbesc(NETWORK_DFRN),
1119 if (DBM::is_result($r)) {
1123 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1128 * @brief Check if posting is allowed for this contact
1130 * @param array $importer Array of the importer user
1131 * @param array $contact The contact that is checked
1132 * @param bool $is_comment Is the check for a comment?
1134 * @return bool is the contact allowed to post?
1136 private static function postAllow($importer, $contact, $is_comment = false)
1139 * Perhaps we were already sharing with this person. Now they're sharing with us.
1140 * That makes us friends.
1141 * Normally this should have handled by getting a request - but this could get lost
1143 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1144 // It is not removed by now. Possibly the code is needed?
1145 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1148 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1149 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1152 // $contact["rel"] = CONTACT_IS_FRIEND;
1153 // logger("defining user ".$contact["nick"]." as friend");
1156 // We don't seem to like that person
1157 if ($contact["blocked"]) {
1158 // Maybe blocked, don't accept.
1160 // We are following this person?
1161 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1162 // Yes, then it is fine.
1164 // Is it a post to a community?
1165 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && in_array($importer["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
1168 // Is the message a global user or a comment?
1169 } elseif (($importer["uid"] == 0) || $is_comment) {
1170 // Messages for the global users and comments are always accepted
1178 * @brief Fetches the contact id for a handle and checks if posting is allowed
1180 * @param array $importer Array of the importer user
1181 * @param string $handle The checked handle in the format user@domain.tld
1182 * @param bool $is_comment Is the check for a comment?
1184 * @return array The contact data
1186 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1188 $contact = self::contactByHandle($importer["uid"], $handle);
1190 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1191 // If a contact isn't found, we accept it anyway if it is a comment
1199 if (!self::postAllow($importer, $contact, $is_comment)) {
1200 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1207 * @brief Does the message already exists on the system?
1209 * @param int $uid The user id
1210 * @param string $guid The guid of the message
1212 * @return int|bool message id if the message already was stored into the system - or false.
1214 private static function messageExists($uid, $guid)
1217 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1222 if (DBM::is_result($r)) {
1223 logger("message ".$guid." already exists for user ".$uid);
1231 * @brief Checks for links to posts in a message
1233 * @param array $item The item array
1236 private static function fetchGuid($item)
1238 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1239 preg_replace_callback(
1241 function ($match) use ($item) {
1242 self::fetchGuidSub($match, $item);
1247 preg_replace_callback(
1248 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1249 function ($match) use ($item) {
1250 self::fetchGuidSub($match, $item);
1257 * @brief Checks for relative /people/* links in an item body to match local
1258 * contacts or prepends the remote host taken from the author link.
1260 * @param string $body The item body to replace links from
1261 * @param string $author_link The author link for missing local contact fallback
1263 * @return string the replaced string
1265 public static function replacePeopleGuid($body, $author_link)
1267 $return = preg_replace_callback(
1268 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1269 function ($match) use ($author_link) {
1271 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1272 // 1 => '0123456789abcdef'
1274 $handle = self::urlFromContactGuid($match[1]);
1277 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1279 // No local match, restoring absolute remote URL from author scheme and host
1280 $author_url = parse_url($author_link);
1281 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1293 * @brief sub function of "fetchGuid" which checks for links in messages
1295 * @param array $match array containing a link that has to be checked for a message link
1296 * @param array $item The item array
1299 private static function fetchGuidSub($match, $item)
1301 if (!self::storeByGuid($match[1], $item["author-link"])) {
1302 self::storeByGuid($match[1], $item["owner-link"]);
1307 * @brief Fetches an item with a given guid from a given server
1309 * @param string $guid the message guid
1310 * @param string $server The server address
1311 * @param int $uid The user id of the user
1313 * @return int the message id of the stored message or false
1315 private static function storeByGuid($guid, $server, $uid = 0)
1317 $serverparts = parse_url($server);
1318 $server = $serverparts["scheme"]."://".$serverparts["host"];
1320 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1322 $msg = self::message($guid, $server);
1328 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1330 // Now call the dispatcher
1331 return self::dispatchPublic($msg);
1335 * @brief Fetches a message from a server
1337 * @param string $guid message guid
1338 * @param string $server The url of the server
1339 * @param int $level Endless loop prevention
1342 * 'message' => The message XML
1343 * 'author' => The author handle
1344 * 'key' => The public key of the author
1346 private static function message($guid, $server, $level = 0)
1352 // This will work for new Diaspora servers and Friendica servers from 3.5
1353 $source_url = $server."/fetch/post/".urlencode($guid);
1355 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1357 $envelope = Network::fetchUrl($source_url);
1359 logger("Envelope was fetched.", LOGGER_DEBUG);
1360 $x = self::verifyMagicEnvelope($envelope);
1362 logger("Envelope could not be verified.", LOGGER_DEBUG);
1364 logger("Envelope was verified.", LOGGER_DEBUG);
1370 // This will work for older Diaspora and Friendica servers
1372 $source_url = $server."/p/".urlencode($guid).".xml";
1373 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1375 $x = Network::fetchUrl($source_url);
1381 $source_xml = XML::parseString($x);
1383 if (!is_object($source_xml)) {
1387 if ($source_xml->post->reshare) {
1388 // Reshare of a reshare - old Diaspora version
1389 logger("Message is a reshare", LOGGER_DEBUG);
1390 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1391 } elseif ($source_xml->getName() == "reshare") {
1392 // Reshare of a reshare - new Diaspora version
1393 logger("Message is a new reshare", LOGGER_DEBUG);
1394 return self::message($source_xml->root_guid, $server, ++$level);
1399 // Fetch the author - for the old and the new Diaspora version
1400 if ($source_xml->post->status_message->diaspora_handle) {
1401 $author = (string)$source_xml->post->status_message->diaspora_handle;
1402 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1403 $author = (string)$source_xml->author;
1406 // If this isn't a "status_message" then quit
1408 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1412 $msg = ["message" => $x, "author" => $author];
1414 $msg["key"] = self::key($msg["author"]);
1420 * @brief Fetches the item record of a given guid
1422 * @param int $uid The user id
1423 * @param string $guid message guid
1424 * @param string $author The handle of the item
1425 * @param array $contact The contact of the item owner
1427 * @return array the item record
1429 private static function parentItem($uid, $guid, $author, $contact)
1432 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1433 `author-name`, `author-link`, `author-avatar`,
1434 `owner-name`, `owner-link`, `owner-avatar`
1435 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1441 $result = self::storeByGuid($guid, $contact["url"], $uid);
1444 $person = self::personByHandle($author);
1445 $result = self::storeByGuid($guid, $person["url"], $uid);
1449 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1452 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1453 `author-name`, `author-link`, `author-avatar`,
1454 `owner-name`, `owner-link`, `owner-avatar`
1455 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1463 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1466 logger("parent item found: parent: ".$guid." - user: ".$uid);
1472 * @brief returns contact details
1474 * @param array $def_contact The default contact if the person isn't found
1475 * @param array $person The record of the person
1476 * @param int $uid The user id
1479 * 'cid' => contact id
1480 * 'network' => network type
1482 private static function authorContactByUrl($def_contact, $person, $uid)
1484 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1485 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1486 if (DBM::is_result($contact)) {
1487 $cid = $contact["id"];
1488 $network = $contact["network"];
1490 $cid = $def_contact["id"];
1491 $network = NETWORK_DIASPORA;
1494 return ["cid" => $cid, "network" => $network];
1498 * @brief Is the profile a hubzilla profile?
1500 * @param string $url The profile link
1502 * @return bool is it a hubzilla server?
1504 public static function isRedmatrix($url)
1506 return(strstr($url, "/channel/"));
1510 * @brief Generate a post link with a given handle and message guid
1512 * @param string $addr The user handle
1513 * @param string $guid message guid
1514 * @param string $parent_guid optional parent guid
1516 * @return string the post link
1518 private static function plink($addr, $guid, $parent_guid = '')
1520 $contact = Contact::getDetailsByAddr($addr);
1524 if ($parent_guid != '') {
1525 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1527 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1531 if ($contact["network"] == NETWORK_DFRN) {
1532 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1535 if (self::isRedmatrix($contact["url"])) {
1536 return $contact["url"] . "/?f=&mid=" . $guid;
1539 if ($parent_guid != '') {
1540 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1542 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1547 * @brief Receives account migration
1549 * @param array $importer Array of the importer user
1550 * @param object $data The message object
1552 * @return bool Success
1554 private static function receiveAccountMigration($importer, $data)
1556 $old_handle = notags(unxmlify($data->author));
1557 $new_handle = notags(unxmlify($data->profile->author));
1558 $signature = notags(unxmlify($data->signature));
1560 $contact = self::contactByHandle($importer["uid"], $old_handle);
1562 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1566 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1569 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1570 $key = self::key($old_handle);
1571 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1572 logger('No valid signature for migration.');
1576 // Update the profile
1577 self::receiveProfile($importer, $data->profile);
1579 // change the technical stuff in contact and gcontact
1580 $data = Probe::uri($new_handle);
1581 if ($data['network'] == NETWORK_PHANTOM) {
1582 logger('Account for '.$new_handle." couldn't be probed.");
1586 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1587 'name' => $data['name'], 'nick' => $data['nick'],
1588 'addr' => $data['addr'], 'batch' => $data['batch'],
1589 'notify' => $data['notify'], 'poll' => $data['poll'],
1590 'network' => $data['network']];
1592 dba::update('contact', $fields, ['addr' => $old_handle]);
1594 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1595 'name' => $data['name'], 'nick' => $data['nick'],
1596 'addr' => $data['addr'], 'connect' => $data['addr'],
1597 'notify' => $data['notify'], 'photo' => $data['photo'],
1598 'server_url' => $data['baseurl'], 'network' => $data['network']];
1600 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1602 logger('Contacts are updated.');
1605 /// @todo This is an extreme performance killer
1607 'owner-link' => [$contact["url"], $data["url"]],
1608 'author-link' => [$contact["url"], $data["url"]],
1610 foreach ($fields as $n => $f) {
1612 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1615 intval($importer["uid"])
1618 if (DBM::is_result($r)) {
1620 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1625 intval($importer["uid"])
1634 logger('Items are updated.');
1640 * @brief Processes an account deletion
1642 * @param object $data The message object
1644 * @return bool Success
1646 private static function receiveAccountDeletion($data)
1648 $author = notags(unxmlify($data->author));
1650 $contacts = dba::select('contact', ['id'], ['addr' => $author]);
1651 while ($contact = dba::fetch($contacts)) {
1652 Contact::remove($contact["id"]);
1655 dba::delete('gcontact', ['addr' => $author]);
1657 logger('Removed contacts for ' . $author);
1663 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1665 * @param string $author Author handle
1666 * @param string $guid Message guid
1667 * @param boolean $onlyfound Only return uri when found in the database
1669 * @return string The constructed uri or the one from our database
1671 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1673 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1674 if (DBM::is_result($r)) {
1675 return $r[0]["uri"];
1676 } elseif (!$onlyfound) {
1677 return $author.":".$guid;
1684 * @brief Fetch the guid from our database with a given uri
1686 * @param string $uri Message uri
1687 * @param string $uid Author handle
1689 * @return string The post guid
1691 private static function getGuidFromUri($uri, $uid)
1693 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1694 if (DBM::is_result($r)) {
1695 return $r[0]["guid"];
1702 * @brief Find the best importer for a comment, like, ...
1704 * @param string $guid The guid of the item
1706 * @return array|boolean the origin owner of that post - or false
1708 private static function importerForGuid($guid)
1710 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1712 if (DBM::is_result($item)) {
1713 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1714 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1715 if (DBM::is_result($contact)) {
1723 * @brief Processes an incoming comment
1725 * @param array $importer Array of the importer user
1726 * @param string $sender The sender of the message
1727 * @param object $data The message object
1728 * @param string $xml The original XML of the message
1730 * @return int The message id of the generated comment or "false" if there was an error
1732 private static function receiveComment($importer, $sender, $data, $xml)
1734 $author = notags(unxmlify($data->author));
1735 $guid = notags(unxmlify($data->guid));
1736 $parent_guid = notags(unxmlify($data->parent_guid));
1737 $text = unxmlify($data->text);
1739 if (isset($data->created_at)) {
1740 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1742 $created_at = DateTimeFormat::utcNow();
1745 if (isset($data->thread_parent_guid)) {
1746 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1747 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1752 $contact = self::allowedContactByHandle($importer, $sender, true);
1757 $message_id = self::messageExists($importer["uid"], $guid);
1762 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1763 if (!$parent_item) {
1767 $person = self::personByHandle($author);
1768 if (!is_array($person)) {
1769 logger("unable to find author details");
1773 // Fetch the contact id - if we know this contact
1774 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1778 $datarray["uid"] = $importer["uid"];
1779 $datarray["contact-id"] = $author_contact["cid"];
1780 $datarray["network"] = $author_contact["network"];
1782 $datarray["author-name"] = $person["name"];
1783 $datarray["author-link"] = $person["url"];
1784 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1786 $datarray["owner-name"] = $contact["name"];
1787 $datarray["owner-link"] = $contact["url"];
1788 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1790 $datarray["guid"] = $guid;
1791 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1793 $datarray["type"] = "remote-comment";
1794 $datarray["verb"] = ACTIVITY_POST;
1795 $datarray["gravity"] = GRAVITY_COMMENT;
1797 if ($thr_uri != "") {
1798 $datarray["parent-uri"] = $thr_uri;
1800 $datarray["parent-uri"] = $parent_item["uri"];
1803 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1805 $datarray["protocol"] = PROTOCOL_DIASPORA;
1806 $datarray["source"] = $xml;
1808 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1810 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1812 $body = Markdown::toBBCode($text);
1814 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1816 self::fetchGuid($datarray);
1818 $message_id = Item::insert($datarray);
1820 if ($message_id <= 0) {
1825 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1826 if ($datarray['uid'] == 0) {
1827 Item::distribute($message_id);
1831 // If we are the origin of the parent we store the original data and notify our followers
1832 if ($message_id && $parent_item["origin"]) {
1833 // Formerly we stored the signed text, the signature and the author in different fields.
1834 // We now store the raw data so that we are more flexible.
1835 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1838 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1845 * @brief processes and stores private messages
1847 * @param array $importer Array of the importer user
1848 * @param array $contact The contact of the message
1849 * @param object $data The message object
1850 * @param array $msg Array of the processed message, author handle and key
1851 * @param object $mesg The private message
1852 * @param array $conversation The conversation record to which this message belongs
1854 * @return bool "true" if it was successful
1856 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1858 $author = notags(unxmlify($data->author));
1859 $guid = notags(unxmlify($data->guid));
1860 $subject = notags(unxmlify($data->subject));
1862 // "diaspora_handle" is the element name from the old version
1863 // "author" is the element name from the new version
1864 if ($mesg->author) {
1865 $msg_author = notags(unxmlify($mesg->author));
1866 } elseif ($mesg->diaspora_handle) {
1867 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1872 $msg_guid = notags(unxmlify($mesg->guid));
1873 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1874 $msg_text = unxmlify($mesg->text);
1875 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1877 if ($msg_conversation_guid != $guid) {
1878 logger("message conversation guid does not belong to the current conversation.");
1882 $body = Markdown::toBBCode($msg_text);
1883 $message_uri = $msg_author.":".$msg_guid;
1885 $person = self::personByHandle($msg_author);
1890 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1892 intval($importer["uid"])
1894 if (DBM::is_result($r)) {
1895 logger("duplicate message already delivered.", LOGGER_DEBUG);
1900 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1901 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1902 intval($importer["uid"]),
1904 intval($conversation["id"]),
1905 dbesc($person["name"]),
1906 dbesc($person["photo"]),
1907 dbesc($person["url"]),
1908 intval($contact["id"]),
1913 dbesc($message_uri),
1914 dbesc($author.":".$guid),
1915 dbesc($msg_created_at)
1920 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1924 "type" => NOTIFY_MAIL,
1925 "notify_flags" => $importer["notify-flags"],
1926 "language" => $importer["language"],
1927 "to_name" => $importer["username"],
1928 "to_email" => $importer["email"],
1929 "uid" =>$importer["uid"],
1930 "item" => ["subject" => $subject, "body" => $body],
1931 "source_name" => $person["name"],
1932 "source_link" => $person["url"],
1933 "source_photo" => $person["thumb"],
1934 "verb" => ACTIVITY_POST,
1941 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1943 * @param array $importer Array of the importer user
1944 * @param array $msg Array of the processed message, author handle and key
1945 * @param object $data The message object
1947 * @return bool Success
1949 private static function receiveConversation($importer, $msg, $data)
1951 $author = notags(unxmlify($data->author));
1952 $guid = notags(unxmlify($data->guid));
1953 $subject = notags(unxmlify($data->subject));
1954 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1955 $participants = notags(unxmlify($data->participants));
1957 $messages = $data->message;
1959 if (!count($messages)) {
1960 logger("empty conversation");
1964 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1969 $conversation = null;
1972 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1973 intval($importer["uid"]),
1977 $conversation = $c[0];
1980 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1981 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1982 intval($importer["uid"]),
1986 dbesc(DateTimeFormat::utcNow()),
1988 dbesc($participants)
1992 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1993 intval($importer["uid"]),
1999 $conversation = $c[0];
2002 if (!$conversation) {
2003 logger("unable to create conversation.");
2007 foreach ($messages as $mesg) {
2008 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2015 * @brief Creates the body for a "like" message
2017 * @param array $contact The contact that send us the "like"
2018 * @param array $parent_item The item array of the parent item
2019 * @param string $guid message guid
2021 * @return string the body
2023 private static function constructLikeBody($contact, $parent_item, $guid)
2025 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
2027 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2028 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
2029 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
2031 return sprintf($bodyverb, $ulink, $alink, $plink);
2035 * @brief Creates a XML object for a "like"
2037 * @param array $importer Array of the importer user
2038 * @param array $parent_item The item array of the parent item
2040 * @return string The XML
2042 private static function constructLikeObject($importer, $parent_item)
2044 $objtype = ACTIVITY_OBJ_NOTE;
2045 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
2046 $parent_body = $parent_item["body"];
2048 $xmldata = ["object" => ["type" => $objtype,
2050 "id" => $parent_item["uri"],
2053 "content" => $parent_body]];
2055 return XML::fromArray($xmldata, $xml, true);
2059 * @brief Processes "like" messages
2061 * @param array $importer Array of the importer user
2062 * @param string $sender The sender of the message
2063 * @param object $data The message object
2065 * @return int The message id of the generated like or "false" if there was an error
2067 private static function receiveLike($importer, $sender, $data)
2069 $author = notags(unxmlify($data->author));
2070 $guid = notags(unxmlify($data->guid));
2071 $parent_guid = notags(unxmlify($data->parent_guid));
2072 $parent_type = notags(unxmlify($data->parent_type));
2073 $positive = notags(unxmlify($data->positive));
2075 // likes on comments aren't supported by Diaspora - only on posts
2076 // But maybe this will be supported in the future, so we will accept it.
2077 if (!in_array($parent_type, ["Post", "Comment"])) {
2081 $contact = self::allowedContactByHandle($importer, $sender, true);
2086 $message_id = self::messageExists($importer["uid"], $guid);
2091 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2092 if (!$parent_item) {
2096 $person = self::personByHandle($author);
2097 if (!is_array($person)) {
2098 logger("unable to find author details");
2102 // Fetch the contact id - if we know this contact
2103 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2105 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2106 // We would accept this anyhow.
2107 if ($positive == "true") {
2108 $verb = ACTIVITY_LIKE;
2110 $verb = ACTIVITY_DISLIKE;
2115 $datarray["protocol"] = PROTOCOL_DIASPORA;
2117 $datarray["uid"] = $importer["uid"];
2118 $datarray["contact-id"] = $author_contact["cid"];
2119 $datarray["network"] = $author_contact["network"];
2121 $datarray["author-name"] = $person["name"];
2122 $datarray["author-link"] = $person["url"];
2123 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2125 $datarray["owner-name"] = $contact["name"];
2126 $datarray["owner-link"] = $contact["url"];
2127 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2129 $datarray["guid"] = $guid;
2130 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2132 $datarray["type"] = "activity";
2133 $datarray["verb"] = $verb;
2134 $datarray["gravity"] = GRAVITY_LIKE;
2135 $datarray["parent-uri"] = $parent_item["uri"];
2137 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2138 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2140 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2142 $message_id = Item::insert($datarray);
2144 if ($message_id <= 0) {
2149 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2150 if ($datarray['uid'] == 0) {
2151 Item::distribute($message_id);
2155 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2156 if ($parent_item["id"] != $parent_item["parent"]) {
2157 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2158 $origin = $toplevel["origin"];
2160 $origin = $parent_item["origin"];
2163 // If we are the origin of the parent we store the original data and notify our followers
2164 if ($message_id && $origin) {
2165 // Formerly we stored the signed text, the signature and the author in different fields.
2166 // We now store the raw data so that we are more flexible.
2167 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2170 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2177 * @brief Processes private messages
2179 * @param array $importer Array of the importer user
2180 * @param object $data The message object
2182 * @return bool Success?
2184 private static function receiveMessage($importer, $data)
2186 $author = notags(unxmlify($data->author));
2187 $guid = notags(unxmlify($data->guid));
2188 $conversation_guid = notags(unxmlify($data->conversation_guid));
2189 $text = unxmlify($data->text);
2190 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2192 $contact = self::allowedContactByHandle($importer, $author, true);
2197 $conversation = null;
2200 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2201 intval($importer["uid"]),
2202 dbesc($conversation_guid)
2205 $conversation = $c[0];
2207 logger("conversation not available.");
2211 $message_uri = $author.":".$guid;
2213 $person = self::personByHandle($author);
2215 logger("unable to find author details");
2219 $body = Markdown::toBBCode($text);
2221 $body = self::replacePeopleGuid($body, $person["url"]);
2226 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2228 intval($importer["uid"])
2230 if (DBM::is_result($r)) {
2231 logger("duplicate message already delivered.", LOGGER_DEBUG);
2236 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2237 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2238 intval($importer["uid"]),
2240 intval($conversation["id"]),
2241 dbesc($person["name"]),
2242 dbesc($person["photo"]),
2243 dbesc($person["url"]),
2244 intval($contact["id"]),
2245 dbesc($conversation["subject"]),
2249 dbesc($message_uri),
2250 dbesc($author.":".$conversation["guid"]),
2256 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2261 * @brief Processes participations - unsupported by now
2263 * @param array $importer Array of the importer user
2264 * @param object $data The message object
2266 * @return bool always true
2268 private static function receiveParticipation($importer, $data)
2270 $author = strtolower(notags(unxmlify($data->author)));
2271 $parent_guid = notags(unxmlify($data->parent_guid));
2273 $contact_id = Contact::getIdForURL($author);
2275 logger('Contact not found: '.$author);
2279 $person = self::personByHandle($author);
2280 if (!is_array($person)) {
2281 logger("Person not found: ".$author);
2285 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2286 if (!DBM::is_result($item)) {
2287 logger('Item not found, no origin or private: '.$parent_guid);
2291 $author_parts = explode('@', $author);
2292 if (isset($author_parts[1])) {
2293 $server = $author_parts[1];
2295 // Should never happen
2299 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2301 if (!dba::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2302 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2305 // Send all existing comments and likes to the requesting server
2306 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2308 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2309 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2310 while ($comment = dba::fetch($comments)) {
2311 if ($comment['verb'] == ACTIVITY_POST) {
2312 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2314 $cmd = $comment['self'] ? 'like' : 'comment-import';
2316 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2317 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2319 dba::close($comments);
2325 * @brief Processes photos - unneeded
2327 * @param array $importer Array of the importer user
2328 * @param object $data The message object
2330 * @return bool always true
2332 private static function receivePhoto($importer, $data)
2334 // There doesn't seem to be a reason for this function,
2335 // since the photo data is transmitted in the status message as well
2340 * @brief Processes poll participations - unssupported
2342 * @param array $importer Array of the importer user
2343 * @param object $data The message object
2345 * @return bool always true
2347 private static function receivePollParticipation($importer, $data)
2349 // We don't support polls by now
2354 * @brief Processes incoming profile updates
2356 * @param array $importer Array of the importer user
2357 * @param object $data The message object
2359 * @return bool Success
2361 private static function receiveProfile($importer, $data)
2363 $author = strtolower(notags(unxmlify($data->author)));
2365 $contact = self::contactByHandle($importer["uid"], $author);
2370 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2371 $image_url = unxmlify($data->image_url);
2372 $birthday = unxmlify($data->birthday);
2373 $gender = unxmlify($data->gender);
2374 $about = Markdown::toBBCode(unxmlify($data->bio));
2375 $location = Markdown::toBBCode(unxmlify($data->location));
2376 $searchable = (unxmlify($data->searchable) == "true");
2377 $nsfw = (unxmlify($data->nsfw) == "true");
2378 $tags = unxmlify($data->tag_string);
2380 $tags = explode("#", $tags);
2383 foreach ($tags as $tag) {
2384 $tag = trim(strtolower($tag));
2390 $keywords = implode(", ", $keywords);
2392 $handle_parts = explode("@", $author);
2393 $nick = $handle_parts[0];
2396 $name = $handle_parts[0];
2399 if (preg_match("|^https?://|", $image_url) === 0) {
2400 $image_url = "http://".$handle_parts[1].$image_url;
2403 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2405 // Generic birthday. We don't know the timezone. The year is irrelevant.
2407 $birthday = str_replace("1000", "1901", $birthday);
2409 if ($birthday != "") {
2410 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2413 // this is to prevent multiple birthday notifications in a single year
2414 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2416 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2417 $birthday = $contact["bd"];
2421 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2422 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2426 dbesc(DateTimeFormat::utcNow()),
2432 intval($contact["id"]),
2433 intval($importer["uid"])
2436 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2437 "photo" => $image_url, "name" => $name, "location" => $location,
2438 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2439 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2440 "hide" => !$searchable, "nsfw" => $nsfw];
2442 $gcid = GContact::update($gcontact);
2444 GContact::link($gcid, $importer["uid"], $contact["id"]);
2446 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2452 * @brief Processes incoming friend requests
2454 * @param array $importer Array of the importer user
2455 * @param array $contact The contact that send the request
2458 private static function receiveRequestMakeFriend($importer, $contact)
2462 if ($contact["rel"] == CONTACT_IS_SHARING) {
2465 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2466 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2469 // send notification
2472 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2473 intval($importer["uid"])
2476 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2478 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2479 intval($importer["uid"])
2482 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2484 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2486 $arr["protocol"] = PROTOCOL_DIASPORA;
2487 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2488 $arr["uid"] = $importer["uid"];
2489 $arr["contact-id"] = $self[0]["id"];
2491 $arr["type"] = 'wall';
2492 $arr["gravity"] = 0;
2494 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2495 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2496 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2497 $arr["verb"] = ACTIVITY_FRIEND;
2498 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2500 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2501 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2502 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2503 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2505 $arr["object"] = self::constructNewFriendObject($contact);
2507 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2509 $arr["allow_cid"] = $user["allow_cid"];
2510 $arr["allow_gid"] = $user["allow_gid"];
2511 $arr["deny_cid"] = $user["deny_cid"];
2512 $arr["deny_gid"] = $user["deny_gid"];
2514 $i = Item::insert($arr);
2516 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2523 * @brief Creates a XML object for a "new friend" message
2525 * @param array $contact Array of the contact
2527 * @return string The XML
2529 private static function constructNewFriendObject($contact)
2531 $objtype = ACTIVITY_OBJ_PERSON;
2532 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2533 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2535 $xmldata = ["object" => ["type" => $objtype,
2536 "title" => $contact["name"],
2537 "id" => $contact["url"]."/".$contact["name"],
2540 return XML::fromArray($xmldata, $xml, true);
2544 * @brief Processes incoming sharing notification
2546 * @param array $importer Array of the importer user
2547 * @param object $data The message object
2549 * @return bool Success
2551 private static function receiveContactRequest($importer, $data)
2553 $author = unxmlify($data->author);
2554 $recipient = unxmlify($data->recipient);
2556 if (!$author || !$recipient) {
2560 // the current protocol version doesn't know these fields
2561 // That means that we will assume their existance
2562 if (isset($data->following)) {
2563 $following = (unxmlify($data->following) == "true");
2568 if (isset($data->sharing)) {
2569 $sharing = (unxmlify($data->sharing) == "true");
2574 $contact = self::contactByHandle($importer["uid"], $author);
2576 // perhaps we were already sharing with this person. Now they're sharing with us.
2577 // That makes us friends.
2580 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2581 self::receiveRequestMakeFriend($importer, $contact);
2583 // refetch the contact array
2584 $contact = self::contactByHandle($importer["uid"], $author);
2586 // If we are now friends, we are sending a share message.
2587 // Normally we needn't to do so, but the first message could have been vanished.
2588 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2589 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2591 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2592 $ret = self::sendShare($u[0], $contact);
2597 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2598 Contact::removeFollower($importer, $contact);
2603 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2604 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2606 } elseif (!$following && !$sharing) {
2607 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2609 } elseif (!$following && $sharing) {
2610 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2611 } elseif ($following && $sharing) {
2612 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2613 } elseif ($following && !$sharing) {
2614 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2617 $ret = self::personByHandle($author);
2619 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2620 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2624 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2627 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2628 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2629 intval($importer["uid"]),
2630 dbesc($ret["network"]),
2631 dbesc($ret["addr"]),
2632 DateTimeFormat::utcNow(),
2634 dbesc(normalise_link($ret["url"])),
2636 dbesc($ret["name"]),
2637 dbesc($ret["nick"]),
2638 dbesc($ret["photo"]),
2639 dbesc($ret["pubkey"]),
2640 dbesc($ret["notify"]),
2641 dbesc($ret["poll"]),
2646 // find the contact record we just created
2648 $contact_record = self::contactByHandle($importer["uid"], $author);
2650 if (!$contact_record) {
2651 logger("unable to locate newly created contact record.");
2655 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2657 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2659 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2661 if (in_array($importer["page-flags"], [PAGE_NORMAL, PAGE_PRVGROUP])) {
2662 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2664 $hash = random_string().(string)time(); // Generate a confirm_key
2667 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2668 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2669 intval($importer["uid"]),
2670 intval($contact_record["id"]),
2673 dbesc(L10n::t("Sharing notification from Diaspora network")),
2675 dbesc(DateTimeFormat::utcNow())
2678 // automatic friend approval
2680 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2682 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2684 // technically they are sharing with us (CONTACT_IS_SHARING),
2685 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2686 // we are going to change the relationship and make them a follower.
2688 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2689 $new_relation = CONTACT_IS_FRIEND;
2690 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2691 $new_relation = CONTACT_IS_SHARING;
2693 $new_relation = CONTACT_IS_FOLLOWER;
2697 "UPDATE `contact` SET `rel` = %d,
2705 intval($new_relation),
2706 dbesc(DateTimeFormat::utcNow()),
2707 dbesc(DateTimeFormat::utcNow()),
2708 intval($contact_record["id"])
2711 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2713 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2714 $ret = self::sendShare($u[0], $contact_record);
2716 // Send the profile data, maybe it weren't transmitted before
2717 self::sendProfile($importer["uid"], [$contact_record]);
2725 * @brief Fetches a message with a given guid
2727 * @param string $guid message guid
2728 * @param string $orig_author handle of the original post
2729 * @param string $author handle of the sharer
2731 * @return array The fetched item
2733 public static function originalItem($guid, $orig_author)
2736 logger('Empty guid. Quitting.');
2740 // Do we already have this item?
2741 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2742 'author-name', 'author-link', 'author-avatar'];
2743 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2744 $item = dba::selectfirst('item', $fields, $condition);
2746 if (DBM::is_result($item)) {
2747 logger("reshared message ".$guid." already exists on system.");
2749 // Maybe it is already a reshared item?
2750 // Then refetch the content, if it is a reshare from a reshare.
2751 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2752 if (self::isReshare($item["body"], true)) {
2754 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2755 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2757 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2759 // Add OEmbed and other information to the body
2760 $item["body"] = add_page_info_to_body($item["body"], false, true);
2768 if (!DBM::is_result($item)) {
2769 if (empty($orig_author)) {
2770 logger('Empty author for guid ' . $guid . '. Quitting.');
2774 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2775 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2776 $stored = self::storeByGuid($guid, $server);
2779 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2780 logger("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2781 $stored = self::storeByGuid($guid, $server);
2785 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2786 'author-name', 'author-link', 'author-avatar'];
2787 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2788 $item = dba::selectfirst('item', $fields, $condition);
2790 if (DBM::is_result($item)) {
2791 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2792 if (self::isReshare($item["body"], false)) {
2793 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2794 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2805 * @brief Processes a reshare message
2807 * @param array $importer Array of the importer user
2808 * @param object $data The message object
2809 * @param string $xml The original XML of the message
2811 * @return int the message id
2813 private static function receiveReshare($importer, $data, $xml)
2815 $author = notags(unxmlify($data->author));
2816 $guid = notags(unxmlify($data->guid));
2817 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2818 $root_author = notags(unxmlify($data->root_author));
2819 $root_guid = notags(unxmlify($data->root_guid));
2820 /// @todo handle unprocessed property "provider_display_name"
2821 $public = notags(unxmlify($data->public));
2823 $contact = self::allowedContactByHandle($importer, $author, false);
2828 $message_id = self::messageExists($importer["uid"], $guid);
2833 $original_item = self::originalItem($root_guid, $root_author);
2834 if (!$original_item) {
2838 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2842 $datarray["uid"] = $importer["uid"];
2843 $datarray["contact-id"] = $contact["id"];
2844 $datarray["network"] = NETWORK_DIASPORA;
2846 $datarray["author-name"] = $contact["name"];
2847 $datarray["author-link"] = $contact["url"];
2848 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2850 $datarray["owner-name"] = $datarray["author-name"];
2851 $datarray["owner-link"] = $datarray["author-link"];
2852 $datarray["owner-avatar"] = $datarray["author-avatar"];
2854 $datarray["guid"] = $guid;
2855 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2857 $datarray["verb"] = ACTIVITY_POST;
2858 $datarray["gravity"] = GRAVITY_PARENT;
2860 $datarray["protocol"] = PROTOCOL_DIASPORA;
2861 $datarray["source"] = $xml;
2863 $prefix = share_header(
2864 $original_item["author-name"],
2865 $original_item["author-link"],
2866 $original_item["author-avatar"],
2867 $original_item["guid"],
2868 $original_item["created"],
2871 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2873 $datarray["tag"] = $original_item["tag"];
2874 $datarray["app"] = $original_item["app"];
2876 $datarray["plink"] = self::plink($author, $guid);
2877 $datarray["private"] = (($public == "false") ? 1 : 0);
2878 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2880 $datarray["object-type"] = $original_item["object-type"];
2882 self::fetchGuid($datarray);
2883 $message_id = Item::insert($datarray);
2885 self::sendParticipation($contact, $datarray);
2888 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2889 if ($datarray['uid'] == 0) {
2890 Item::distribute($message_id);
2899 * @brief Processes retractions
2901 * @param array $importer Array of the importer user
2902 * @param array $contact The contact of the item owner
2903 * @param object $data The message object
2905 * @return bool success
2907 private static function itemRetraction($importer, $contact, $data)
2909 $author = notags(unxmlify($data->author));
2910 $target_guid = notags(unxmlify($data->target_guid));
2911 $target_type = notags(unxmlify($data->target_type));
2913 $person = self::personByHandle($author);
2914 if (!is_array($person)) {
2915 logger("unable to find author detail for ".$author);
2919 if (empty($contact["url"])) {
2920 $contact["url"] = $person["url"];
2923 // Fetch items that are about to be deleted
2924 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2926 // When we receive a public retraction, we delete every item that we find.
2927 if ($importer['uid'] == 0) {
2928 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2930 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2932 $r = dba::select('item', $fields, $condition);
2933 if (!DBM::is_result($r)) {
2934 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2938 while ($item = dba::fetch($r)) {
2939 // Fetch the parent item
2940 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2942 // Only delete it if the parent author really fits
2943 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2944 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2948 Item::deleteById($item["id"]);
2950 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2952 // Now check if the retraction needs to be relayed by us
2953 if ($parent["origin"]) {
2955 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2963 * @brief Receives retraction messages
2965 * @param array $importer Array of the importer user
2966 * @param string $sender The sender of the message
2967 * @param object $data The message object
2969 * @return bool Success
2971 private static function receiveRetraction($importer, $sender, $data)
2973 $target_type = notags(unxmlify($data->target_type));
2975 $contact = self::contactByHandle($importer["uid"], $sender);
2976 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2977 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2981 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2983 switch ($target_type) {
2988 case "StatusMessage":
2989 return self::itemRetraction($importer, $contact, $data);
2993 /// @todo What should we do with an "unshare"?
2994 // Removing the contact isn't correct since we still can read the public items
2995 Contact::remove($contact["id"]);
2999 logger("Unknown target type ".$target_type);
3006 * @brief Receives status messages
3008 * @param array $importer Array of the importer user
3009 * @param object $data The message object
3010 * @param string $xml The original XML of the message
3012 * @return int The message id of the newly created item
3014 private static function receiveStatusMessage($importer, $data, $xml)
3016 $author = notags(unxmlify($data->author));
3017 $guid = notags(unxmlify($data->guid));
3018 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
3019 $public = notags(unxmlify($data->public));
3020 $text = unxmlify($data->text);
3021 $provider_display_name = notags(unxmlify($data->provider_display_name));
3023 $contact = self::allowedContactByHandle($importer, $author, false);
3028 $message_id = self::messageExists($importer["uid"], $guid);
3034 if ($data->location) {
3035 foreach ($data->location->children() as $fieldname => $data) {
3036 $address[$fieldname] = notags(unxmlify($data));
3040 $body = Markdown::toBBCode($text);
3044 // Attach embedded pictures to the body
3046 foreach ($data->photo as $photo) {
3047 $body = "[img]".unxmlify($photo->remote_photo_path).
3048 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
3051 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
3053 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
3055 // Add OEmbed and other information to the body
3056 if (!self::isRedmatrix($contact["url"])) {
3057 $body = add_page_info_to_body($body, false, true);
3061 /// @todo enable support for polls
3062 //if ($data->poll) {
3063 // foreach ($data->poll AS $poll)
3068 /// @todo enable support for events
3070 $datarray["uid"] = $importer["uid"];
3071 $datarray["contact-id"] = $contact["id"];
3072 $datarray["network"] = NETWORK_DIASPORA;
3074 $datarray["author-name"] = $contact["name"];
3075 $datarray["author-link"] = $contact["url"];
3076 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
3078 $datarray["owner-name"] = $datarray["author-name"];
3079 $datarray["owner-link"] = $datarray["author-link"];
3080 $datarray["owner-avatar"] = $datarray["author-avatar"];
3082 $datarray["guid"] = $guid;
3083 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3085 $datarray["verb"] = ACTIVITY_POST;
3086 $datarray["gravity"] = GRAVITY_PARENT;
3088 $datarray["protocol"] = PROTOCOL_DIASPORA;
3089 $datarray["source"] = $xml;
3091 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3093 if ($provider_display_name != "") {
3094 $datarray["app"] = $provider_display_name;
3097 $datarray["plink"] = self::plink($author, $guid);
3098 $datarray["private"] = (($public == "false") ? 1 : 0);
3099 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3101 if (isset($address["address"])) {
3102 $datarray["location"] = $address["address"];
3105 if (isset($address["lat"]) && isset($address["lng"])) {
3106 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3109 self::fetchGuid($datarray);
3110 $message_id = Item::insert($datarray);
3112 self::sendParticipation($contact, $datarray);
3115 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3116 if ($datarray['uid'] == 0) {
3117 Item::distribute($message_id);
3125 /* ************************************************************************************** *
3126 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3127 * ************************************************************************************** */
3130 * @brief returnes the handle of a contact
3132 * @param array $contact contact array
3134 * @return string the handle in the format user@domain.tld
3136 private static function myHandle($contact)
3138 if ($contact["addr"] != "") {
3139 return $contact["addr"];
3142 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3143 // So - just in case - we build the the address here.
3144 if ($contact["nickname"] != "") {
3145 $nick = $contact["nickname"];
3147 $nick = $contact["nick"];
3150 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3155 * @brief Creates the data for a private message in the new format
3157 * @param string $msg The message that is to be transmitted
3158 * @param array $user The record of the sender
3159 * @param array $contact Target of the communication
3160 * @param string $prvkey The private key of the sender
3161 * @param string $pubkey The public key of the receiver
3163 * @return string The encrypted data
3165 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3167 logger("Message: ".$msg, LOGGER_DATA);
3169 // without a public key nothing will work
3171 logger("pubkey missing: contact id: ".$contact["id"]);
3175 $aes_key = openssl_random_pseudo_bytes(32);
3176 $b_aes_key = base64_encode($aes_key);
3177 $iv = openssl_random_pseudo_bytes(16);
3178 $b_iv = base64_encode($iv);
3180 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3182 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3184 $encrypted_key_bundle = "";
3185 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3187 $json_object = json_encode(
3188 ["aes_key" => base64_encode($encrypted_key_bundle),
3189 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3192 return $json_object;
3196 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3198 * @param string $msg The message that is to be transmitted
3199 * @param array $user The record of the sender
3201 * @return string The envelope
3203 public static function buildMagicEnvelope($msg, $user)
3205 $b64url_data = base64url_encode($msg);
3206 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3208 $key_id = base64url_encode(self::myHandle($user));
3209 $type = "application/xml";
3210 $encoding = "base64url";
3211 $alg = "RSA-SHA256";
3212 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3214 // Fallback if the private key wasn't transmitted in the expected field
3215 if ($user['uprvkey'] == "") {
3216 $user['uprvkey'] = $user['prvkey'];
3219 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3220 $sig = base64url_encode($signature);
3222 $xmldata = ["me:env" => ["me:data" => $data,
3223 "@attributes" => ["type" => $type],
3224 "me:encoding" => $encoding,
3227 "@attributes2" => ["key_id" => $key_id]]];
3229 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3231 return XML::fromArray($xmldata, $xml, false, $namespaces);
3235 * @brief Create the envelope for a message
3237 * @param string $msg The message that is to be transmitted
3238 * @param array $user The record of the sender
3239 * @param array $contact Target of the communication
3240 * @param string $prvkey The private key of the sender
3241 * @param string $pubkey The public key of the receiver
3242 * @param bool $public Is the message public?
3244 * @return string The message that will be transmitted to other servers
3246 public static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3248 // The message is put into an envelope with the sender's signature
3249 $envelope = self::buildMagicEnvelope($msg, $user);
3251 // Private messages are put into a second envelope, encrypted with the receivers public key
3253 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3260 * @brief Creates a signature for a message
3262 * @param array $owner the array of the owner of the message
3263 * @param array $message The message that is to be signed
3265 * @return string The signature
3267 private static function signature($owner, $message)
3270 unset($sigmsg["author_signature"]);
3271 unset($sigmsg["parent_author_signature"]);
3273 $signed_text = implode(";", $sigmsg);
3275 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3279 * @brief Transmit a message to a target server
3281 * @param array $owner the array of the item owner
3282 * @param array $contact Target of the communication
3283 * @param string $envelope The message that is to be transmitted
3284 * @param bool $public_batch Is it a public post?
3285 * @param bool $queue_run Is the transmission called from the queue?
3286 * @param string $guid message guid
3288 * @return int Result of the transmission
3290 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3294 $enabled = intval(Config::get("system", "diaspora_enabled"));
3299 $logid = random_string(4);
3301 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3303 // We always try to use the data from the fcontact table.
3304 // This is important for transmitting data to Friendica servers.
3305 if (!empty($contact['addr'])) {
3306 $fcontact = self::personByHandle($contact['addr']);
3307 if (!empty($fcontact)) {
3308 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3313 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3317 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3319 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3322 if (!intval(Config::get("system", "diaspora_test"))) {
3323 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3325 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3326 $return_code = $a->get_curl_code();
3328 logger("test_mode");
3333 logger("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3335 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3336 if (!$no_queue && ($contact['contact-type'] != ACCOUNT_TYPE_RELAY)) {
3337 logger("queue message");
3338 // queue message for redelivery
3339 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3342 // The message could not be delivered. We mark the contact as "dead"
3343 Contact::markForArchival($contact);
3344 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3345 // We successfully delivered a message, the contact is alive
3346 Contact::unmarkForArchival($contact);
3349 return $return_code ? $return_code : -1;
3354 * @brief Build the post xml
3356 * @param string $type The message type
3357 * @param array $message The message data
3359 * @return string The post XML
3361 public static function buildPostXml($type, $message)
3363 $data = [$type => $message];
3365 return XML::fromArray($data, $xml);
3369 * @brief Builds and transmit messages
3371 * @param array $owner the array of the item owner
3372 * @param array $contact Target of the communication
3373 * @param string $type The message type
3374 * @param array $message The message data
3375 * @param bool $public_batch Is it a public post?
3376 * @param string $guid message guid
3377 * @param bool $spool Should the transmission be spooled or transmitted?
3379 * @return int Result of the transmission
3381 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3383 $msg = self::buildPostXml($type, $message);
3385 logger('message: '.$msg, LOGGER_DATA);
3386 logger('send guid '.$guid, LOGGER_DEBUG);
3388 // Fallback if the private key wasn't transmitted in the expected field
3389 if ($owner['uprvkey'] == "") {
3390 $owner['uprvkey'] = $owner['prvkey'];
3393 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3396 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3399 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3402 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3404 return $return_code;
3408 * @brief sends a participation (Used to get all further updates)
3410 * @param array $contact Target of the communication
3411 * @param array $item Item array
3413 * @return int The result of the transmission
3415 private static function sendParticipation($contact, $item)
3417 // Don't send notifications for private postings
3418 if ($item['private']) {
3422 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3424 $result = Cache::get($cachekey);
3425 if (!is_null($result)) {
3429 // Fetch some user id to have a valid handle to transmit the participation.
3430 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3431 // If the item belongs to a user, we take this user id.
3432 if ($item['uid'] == 0) {
3433 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3434 $first_user = dba::selectFirst('user', ['uid'], $condition);
3435 $owner = User::getOwnerDataById($first_user['uid']);
3437 $owner = User::getOwnerDataById($item['uid']);
3440 $author = self::myHandle($owner);
3442 $message = ["author" => $author,
3443 "guid" => get_guid(32),
3444 "parent_type" => "Post",
3445 "parent_guid" => $item["guid"]];
3447 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3449 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3450 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3452 return self::buildAndTransmit($owner, $contact, "participation", $message);
3456 * @brief sends an account migration
3458 * @param array $owner the array of the item owner
3459 * @param array $contact Target of the communication
3460 * @param int $uid User ID
3462 * @return int The result of the transmission
3464 public static function sendAccountMigration($owner, $contact, $uid)
3466 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3467 $profile = self::createProfileData($uid);
3469 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3470 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3472 $message = ["author" => $old_handle,
3473 "profile" => $profile,
3474 "signature" => $signature];
3476 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3478 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3482 * @brief Sends a "share" message
3484 * @param array $owner the array of the item owner
3485 * @param array $contact Target of the communication
3487 * @return int The result of the transmission
3489 public static function sendShare($owner, $contact)
3492 * @todo support the different possible combinations of "following" and "sharing"
3493 * Currently, Diaspora only interprets the "sharing" field
3495 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3499 switch ($contact["rel"]) {
3500 case CONTACT_IS_FRIEND:
3503 case CONTACT_IS_SHARING:
3506 case CONTACT_IS_FOLLOWER:
3512 $message = ["author" => self::myHandle($owner),
3513 "recipient" => $contact["addr"],
3514 "following" => "true",
3515 "sharing" => "true"];
3517 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3519 return self::buildAndTransmit($owner, $contact, "contact", $message);
3523 * @brief sends an "unshare"
3525 * @param array $owner the array of the item owner
3526 * @param array $contact Target of the communication
3528 * @return int The result of the transmission
3530 public static function sendUnshare($owner, $contact)
3532 $message = ["author" => self::myHandle($owner),
3533 "recipient" => $contact["addr"],
3534 "following" => "false",
3535 "sharing" => "false"];
3537 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3539 return self::buildAndTransmit($owner, $contact, "contact", $message);
3543 * @brief Checks a message body if it is a reshare
3545 * @param string $body The message body that is to be check
3546 * @param bool $complete Should it be a complete check or a simple check?
3548 * @return array|bool Reshare details or "false" if no reshare
3550 public static function isReshare($body, $complete = true)
3552 $body = trim($body);
3554 // Skip if it isn't a pure repeated messages
3555 // Does it start with a share?
3556 if ((strpos($body, "[share") > 0) && $complete) {
3560 // Does it end with a share?
3561 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3565 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3566 // Skip if there is no shared message in there
3567 if ($body == $attributes) {
3571 // If we don't do the complete check we quit here
3574 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3575 if ($matches[1] != "") {
3576 $guid = $matches[1];
3579 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3580 if ($matches[1] != "") {
3581 $guid = $matches[1];
3584 if (($guid != "") && $complete) {
3585 $condition = ['guid' => $guid, 'network' => [NETWORK_DFRN, NETWORK_DIASPORA]];
3586 $item = dba::selectFirst('item', ['contact-id'], $condition);
3587 if (DBM::is_result($item)) {
3589 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3590 $ret["root_guid"] = $guid;
3596 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3597 if ($matches[1] != "") {
3598 $profile = $matches[1];
3601 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3602 if ($matches[1] != "") {
3603 $profile = $matches[1];
3608 if ($profile != "") {
3609 if (Contact::getIdForURL($profile)) {
3610 $author = Contact::getDetailsByURL($profile);
3611 $ret["root_handle"] = $author['addr'];
3615 if (!empty($guid)) {
3616 $ret["root_guid"] = $guid;
3619 if (empty($ret) && !$complete) {
3627 * @brief Create an event array
3629 * @param integer $event_id The id of the event
3631 * @return array with event data
3633 private static function buildEvent($event_id)
3635 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3636 if (!DBM::is_result($r)) {
3644 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3645 if (!DBM::is_result($r)) {
3651 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3652 if (!DBM::is_result($r)) {
3658 $eventdata['author'] = self::myHandle($owner);
3660 if ($event['guid']) {
3661 $eventdata['guid'] = $event['guid'];
3664 $mask = DateTimeFormat::ATOM;
3666 /// @todo - establish "all day" events in Friendica
3667 $eventdata["all_day"] = "false";
3669 if (!$event['adjust']) {
3670 $eventdata['timezone'] = $user['timezone'];
3672 if ($eventdata['timezone'] == "") {
3673 $eventdata['timezone'] = 'UTC';
3677 if ($event['start']) {
3678 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3680 if ($event['finish'] && !$event['nofinish']) {
3681 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3683 if ($event['summary']) {
3684 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3686 if ($event['desc']) {
3687 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3689 if ($event['location']) {
3690 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3691 $coord = Map::getCoordinates($event['location']);
3694 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3695 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3696 $location["lat"] = $coord['lat'];
3697 $location["lng"] = $coord['lon'];
3699 $location["lat"] = 0;
3700 $location["lng"] = 0;
3702 $eventdata['location'] = $location;
3709 * @brief Create a post (status message or reshare)
3711 * @param array $item The item that will be exported
3712 * @param array $owner the array of the item owner
3715 * 'type' -> Message type ("status_message" or "reshare")
3716 * 'message' -> Array of XML elements of the status
3718 public static function buildStatus($item, $owner)
3720 $cachekey = "diaspora:buildStatus:".$item['guid'];
3722 $result = Cache::get($cachekey);
3723 if (!is_null($result)) {
3727 $myaddr = self::myHandle($owner);
3729 $public = (($item["private"]) ? "false" : "true");
3731 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3733 // Detect a share element and do a reshare
3734 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3735 $message = ["author" => $myaddr,
3736 "guid" => $item["guid"],
3737 "created_at" => $created,
3738 "root_author" => $ret["root_handle"],
3739 "root_guid" => $ret["root_guid"],
3740 "provider_display_name" => $item["app"],
3741 "public" => $public];
3745 $title = $item["title"];
3746 $body = $item["body"];
3748 if ($item['author-link'] != $item['owner-link']) {
3749 require_once 'mod/share.php';
3750 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3751 "", $item['created'], $item['plink']) . $body . '[/share]';
3754 // convert to markdown
3755 $body = html_entity_decode(BBCode::toMarkdown($body));
3758 if (strlen($title)) {
3759 $body = "## ".html_entity_decode($title)."\n\n".$body;
3762 if ($item["attach"]) {
3763 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3765 $body .= "\n".L10n::t("Attachments:")."\n";
3766 foreach ($matches as $mtch) {
3767 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3774 if ($item["location"] != "")
3775 $location["address"] = $item["location"];
3777 if ($item["coord"] != "") {
3778 $coord = explode(" ", $item["coord"]);
3779 $location["lat"] = $coord[0];
3780 $location["lng"] = $coord[1];
3783 $message = ["author" => $myaddr,
3784 "guid" => $item["guid"],
3785 "created_at" => $created,
3786 "public" => $public,
3788 "provider_display_name" => $item["app"],
3789 "location" => $location];
3791 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3792 if (!isset($location["lat"]) || !isset($location["lng"])) {
3793 unset($message["location"]);
3796 if ($item['event-id'] > 0) {
3797 $event = self::buildEvent($item['event-id']);
3798 if (count($event)) {
3799 $message['event'] = $event;
3801 if (!empty($event['location']['address']) &&
3802 !empty($event['location']['lat']) &&
3803 !empty($event['location']['lng'])) {
3804 $message['location'] = $event['location'];
3807 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3808 // $message['text'] = '';
3812 $type = "status_message";
3815 $msg = ["type" => $type, "message" => $message];
3817 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3823 * @brief Sends a post
3825 * @param array $item The item that will be exported
3826 * @param array $owner the array of the item owner
3827 * @param array $contact Target of the communication
3828 * @param bool $public_batch Is it a public post?
3830 * @return int The result of the transmission
3832 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3834 $status = self::buildStatus($item, $owner);
3836 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3840 * @brief Creates a "like" object
3842 * @param array $item The item that will be exported
3843 * @param array $owner the array of the item owner
3845 * @return array The data for a "like"
3847 private static function constructLike($item, $owner)
3850 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3851 dbesc($item["thr-parent"])
3853 if (!DBM::is_result($p)) {
3859 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3861 if ($item['verb'] === ACTIVITY_LIKE) {
3863 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3864 $positive = "false";
3867 return(["author" => self::myHandle($owner),
3868 "guid" => $item["guid"],
3869 "parent_guid" => $parent["guid"],
3870 "parent_type" => $target_type,
3871 "positive" => $positive,
3872 "author_signature" => ""]);
3876 * @brief Creates an "EventParticipation" object
3878 * @param array $item The item that will be exported
3879 * @param array $owner the array of the item owner
3881 * @return array The data for an "EventParticipation"
3883 private static function constructAttend($item, $owner)
3886 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3887 dbesc($item["thr-parent"])
3889 if (!DBM::is_result($p)) {
3895 switch ($item['verb']) {
3896 case ACTIVITY_ATTEND:
3897 $attend_answer = 'accepted';
3899 case ACTIVITY_ATTENDNO:
3900 $attend_answer = 'declined';
3902 case ACTIVITY_ATTENDMAYBE:
3903 $attend_answer = 'tentative';
3906 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3910 return(["author" => self::myHandle($owner),
3911 "guid" => $item["guid"],
3912 "parent_guid" => $parent["guid"],
3913 "status" => $attend_answer,
3914 "author_signature" => ""]);
3918 * @brief Creates the object for a comment
3920 * @param array $item The item that will be exported
3921 * @param array $owner the array of the item owner
3923 * @return array The data for a comment
3925 private static function constructComment($item, $owner)
3927 $cachekey = "diaspora:constructComment:".$item['guid'];
3929 $result = Cache::get($cachekey);
3930 if (!is_null($result)) {
3935 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3936 intval($item["parent"]),
3937 intval($item["parent"])
3940 if (!DBM::is_result($p)) {
3946 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3947 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3949 $comment = ["author" => self::myHandle($owner),
3950 "guid" => $item["guid"],
3951 "created_at" => $created,
3952 "parent_guid" => $parent["guid"],
3954 "author_signature" => ""];
3956 // Send the thread parent guid only if it is a threaded comment
3957 if ($item['thr-parent'] != $item['parent-uri']) {
3958 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3961 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3967 * @brief Send a like or a comment
3969 * @param array $item The item that will be exported
3970 * @param array $owner the array of the item owner
3971 * @param array $contact Target of the communication
3972 * @param bool $public_batch Is it a public post?
3974 * @return int The result of the transmission
3976 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3978 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3979 $message = self::constructAttend($item, $owner);
3980 $type = "event_participation";
3981 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3982 $message = self::constructLike($item, $owner);
3985 $message = self::constructComment($item, $owner);
3993 $message["author_signature"] = self::signature($owner, $message);
3995 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3999 * @brief Creates a message from a signature record entry
4001 * @param array $item The item that will be exported
4002 * @param array $signature The entry of the "sign" record
4004 * @return string The message
4006 private static function messageFromSignature($item, $signature)
4008 // Split the signed text
4009 $signed_parts = explode(";", $signature['signed_text']);
4011 if ($item["deleted"]) {
4012 $message = ["author" => $signature['signer'],
4013 "target_guid" => $signed_parts[0],
4014 "target_type" => $signed_parts[1]];
4015 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4016 $message = ["author" => $signed_parts[4],
4017 "guid" => $signed_parts[1],
4018 "parent_guid" => $signed_parts[3],
4019 "parent_type" => $signed_parts[2],
4020 "positive" => $signed_parts[0],
4021 "author_signature" => $signature['signature'],
4022 "parent_author_signature" => ""];
4024 // Remove the comment guid
4025 $guid = array_shift($signed_parts);
4027 // Remove the parent guid
4028 $parent_guid = array_shift($signed_parts);
4030 // Remove the handle
4031 $handle = array_pop($signed_parts);
4033 // Glue the parts together
4034 $text = implode(";", $signed_parts);
4036 $message = ["author" => $handle,
4038 "parent_guid" => $parent_guid,
4039 "text" => implode(";", $signed_parts),
4040 "author_signature" => $signature['signature'],
4041 "parent_author_signature" => ""];
4047 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
4049 * @param array $item The item that will be exported
4050 * @param array $owner the array of the item owner
4051 * @param array $contact Target of the communication
4052 * @param bool $public_batch Is it a public post?
4054 * @return int The result of the transmission
4056 public static function sendRelay($item, $owner, $contact, $public_batch = false)
4058 if ($item["deleted"]) {
4059 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
4060 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4066 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4068 // fetch the original signature
4071 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
4076 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4082 // Old way - is used by the internal Friendica functions
4083 /// @todo Change all signatur storing functions to the new format
4084 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
4085 $message = self::messageFromSignature($item, $signature);
4087 $msg = json_decode($signature['signed_text'], true);
4090 if (is_array($msg)) {
4091 foreach ($msg as $field => $data) {
4092 if (!$item["deleted"]) {
4093 if ($field == "diaspora_handle") {
4096 if ($field == "target_type") {
4097 $field = "parent_type";
4101 $message[$field] = $data;
4104 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4108 $message["parent_author_signature"] = self::signature($owner, $message);
4110 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4112 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4116 * @brief Sends a retraction (deletion) of a message, like or comment
4118 * @param array $item The item that will be exported
4119 * @param array $owner the array of the item owner
4120 * @param array $contact Target of the communication
4121 * @param bool $public_batch Is it a public post?
4122 * @param bool $relay Is the retraction transmitted from a relay?
4124 * @return int The result of the transmission
4126 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4128 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4130 $msg_type = "retraction";
4132 if ($item['id'] == $item['parent']) {
4133 $target_type = "Post";
4134 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4135 $target_type = "Like";
4137 $target_type = "Comment";
4140 $message = ["author" => $itemaddr,
4141 "target_guid" => $item['guid'],
4142 "target_type" => $target_type];
4144 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4146 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4150 * @brief Sends a mail
4152 * @param array $item The item that will be exported
4153 * @param array $owner The owner
4154 * @param array $contact Target of the communication
4156 * @return int The result of the transmission
4158 public static function sendMail($item, $owner, $contact)
4160 $myaddr = self::myHandle($owner);
4163 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4164 intval($item["convid"]),
4165 intval($item["uid"])
4168 if (!DBM::is_result($r)) {
4169 logger("conversation not found.");
4175 "author" => $cnv["creator"],
4176 "guid" => $cnv["guid"],
4177 "subject" => $cnv["subject"],
4178 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4179 "participants" => $cnv["recips"]
4182 $body = BBCode::toMarkdown($item["body"]);
4183 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4186 "author" => $myaddr,
4187 "guid" => $item["guid"],
4188 "conversation_guid" => $cnv["guid"],
4190 "created_at" => $created,
4193 if ($item["reply"]) {
4198 "author" => $cnv["creator"],
4199 "guid" => $cnv["guid"],
4200 "subject" => $cnv["subject"],
4201 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4202 "participants" => $cnv["recips"],
4205 $type = "conversation";
4208 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4212 * @brief Split a name into first name and last name
4214 * @param string $name The name
4216 * @return array The array with "first" and "last"
4218 public static function splitName($name) {
4219 $name = trim($name);
4221 // Is the name longer than 64 characters? Then cut the rest of it.
4222 if (strlen($name) > 64) {
4223 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4224 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4226 $name = substr($name, 0, 64);
4230 // Take the first word as first name
4231 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4232 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4233 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4234 return ['first' => $first, 'last' => $last];
4237 // Take the last word as last name
4238 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4239 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4241 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4242 return ['first' => $first, 'last' => $last];
4245 // Take the first 32 characters if there is no space in the first 32 characters
4246 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4247 $first = substr($name, 0, 32);
4248 $last = substr($name, 32);
4249 return ['first' => $first, 'last' => $last];
4252 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4253 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4255 // Check if the last name is longer than 32 characters
4256 if (strlen($last) > 32) {
4257 if (strpos($last, ' ') <= 32) {
4258 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4260 $last = substr($last, 0, 32);
4264 return ['first' => $first, 'last' => $last];
4268 * @brief Create profile data
4270 * @param int $uid The user id
4272 * @return array The profile data
4274 private static function createProfileData($uid)
4277 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4279 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4280 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4281 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4290 $handle = $profile["addr"];
4292 $split_name = self::splitName($profile['name']);
4293 $first = $split_name['first'];
4294 $last = $split_name['last'];
4296 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4297 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4298 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4299 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4305 if ($searchable === 'true') {
4308 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4309 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4313 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4316 $about = $profile['about'];
4317 $about = strip_tags(BBCode::convert($about));
4319 $location = Profile::formatLocation($profile);
4321 if ($profile['pub_keywords']) {
4322 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4323 $kw = str_replace(' ', ' ', $kw);
4324 $arr = explode(' ', $profile['pub_keywords']);
4326 for ($x = 0; $x < 5; $x ++) {
4327 if (trim($arr[$x])) {
4328 $tags .= '#'. trim($arr[$x]) .' ';
4333 $tags = trim($tags);
4336 return ["author" => $handle,
4337 "first_name" => $first,
4338 "last_name" => $last,
4339 "image_url" => $large,
4340 "image_url_medium" => $medium,
4341 "image_url_small" => $small,
4343 "gender" => $profile['gender'],
4345 "location" => $location,
4346 "searchable" => $searchable,
4348 "tag_string" => $tags];
4352 * @brief Sends profile data
4354 * @param int $uid The user id
4355 * @param bool $recips optional, default false
4358 public static function sendProfile($uid, $recips = false)
4364 $owner = User::getOwnerDataById($uid);
4371 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4372 AND `uid` = %d AND `rel` != %d",
4373 dbesc(NETWORK_DIASPORA),
4375 intval(CONTACT_IS_SHARING)
4383 $message = self::createProfileData($uid);
4385 foreach ($recips as $recip) {
4386 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4387 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4392 * @brief Stores the signature for likes that are created on our system
4394 * @param array $contact The contact array of the "like"
4395 * @param int $post_id The post id of the "like"
4397 * @return bool Success
4399 public static function storeLikeSignature($contact, $post_id)
4401 // Is the contact the owner? Then fetch the private key
4402 if (!$contact['self'] || ($contact['uid'] == 0)) {
4403 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4407 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4408 if (!DBM::is_result($r)) {
4412 $contact["uprvkey"] = $r[0]['prvkey'];
4414 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4415 if (!DBM::is_result($r)) {
4419 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4423 $message = self::constructLike($r[0], $contact);
4424 if ($message === false) {
4428 $message["author_signature"] = self::signature($contact, $message);
4431 * Now store the signature more flexible to dynamically support new fields.
4432 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4434 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4436 logger('Stored diaspora like signature');
4441 * @brief Stores the signature for comments that are created on our system
4443 * @param array $item The item array of the comment
4444 * @param array $contact The contact array of the item owner
4445 * @param string $uprvkey The private key of the sender
4446 * @param int $message_id The message id of the comment
4448 * @return bool Success
4450 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4452 if ($uprvkey == "") {
4453 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4457 $contact["uprvkey"] = $uprvkey;
4459 $message = self::constructComment($item, $contact);
4460 if ($message === false) {
4464 $message["author_signature"] = self::signature($contact, $message);
4467 * Now store the signature more flexible to dynamically support new fields.
4468 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4470 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4472 logger('Stored diaspora comment signature');