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 $batch = $server_url . '/receive/public';
139 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
141 // Fetch the relay contact
142 $condition = ['uid' => 0, 'network' => NETWORK_DIASPORA, 'batch' => $batch,
143 'contact-type' => ACCOUNT_TYPE_RELAY];
144 $contact = dba::selectFirst('contact', $fields, $condition);
146 // If there is nothing found, we check if there is some unmarked relay
147 // This code segment can be removed before the release 2018-05
148 if (!DBM::is_result($contact)) {
149 $condition = ['uid' => 0, 'network' => NETWORK_DIASPORA, 'batch' => $batch,
150 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url];
151 $contact = dba::selectFirst('contact', $fields, $condition);
153 if (DBM::is_result($contact)) {
154 // Mark the relay account as a relay account
155 $fields = ['contact-type' => ACCOUNT_TYPE_RELAY];
156 dba::update('contact', $fields, ['id' => $contact['id']]);
159 if (DBM::is_result($contact)) {
160 if ($contact['archive'] || $contact['blocked']) {
165 $fields = ['uid' => 0, 'created' => DateTimeFormat::utcNow(),
166 'name' => 'relay', 'nick' => 'relay',
167 'url' => $server_url, 'nurl' => normalise_link($server_url),
168 'batch' => $batch, 'network' => NETWORK_DIASPORA,
169 'rel' => CONTACT_IS_FOLLOWER, 'blocked' => false,
170 'contact-type' => ACCOUNT_TYPE_RELAY,
171 'pending' => false, 'writable' => true];
172 dba::insert('contact', $fields);
174 $fields = ['batch', 'id', 'name', 'network'];
175 $contact = dba::selectFirst('contact', $fields, $condition);
176 if (DBM::is_result($contact)) {
182 // It should never happen that we arrive here
187 * @brief Return a list of participating contacts for a thread
189 * This is used for the participation feature.
190 * One of the parameters is a contact array.
191 * This is done to avoid duplicates.
193 * @param integer $thread The id of the thread
194 * @param array $contacts The previously fetched contacts
196 * @return array of relay servers
198 public static function participantsForThread($thread, $contacts)
200 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
201 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
202 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
203 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
204 WHERE `participation`.`iid` = ?", $thread);
206 while ($contact = dba::fetch($r)) {
207 if (!empty($contact['fnetwork'])) {
208 $contact['network'] = $contact['fnetwork'];
210 unset($contact['fnetwork']);
212 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
213 $contact['batch'] = $contact['fbatch'];
215 unset($contact['fbatch']);
218 foreach ($contacts as $entry) {
219 if ($entry['batch'] == $contact['batch']) {
225 $contacts[] = $contact;
234 * @brief repairs a signature that was double encoded
236 * The function is unused at the moment. It was copied from the old implementation.
238 * @param string $signature The signature
239 * @param string $handle The handle of the signature owner
240 * @param integer $level This value is only set inside this function to avoid endless loops
242 * @return string the repaired signature
244 private static function repairSignature($signature, $handle = "", $level = 1)
246 if ($signature == "") {
250 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
251 $signature = base64_decode($signature);
252 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
254 // Do a recursive call to be able to fix even multiple levels
256 $signature = self::repairSignature($signature, $handle, ++$level);
264 * @brief verify the envelope and return the verified data
266 * @param string $envelope The magic envelope
268 * @return string verified data
270 private static function verifyMagicEnvelope($envelope)
272 $basedom = XML::parseString($envelope);
274 if (!is_object($basedom)) {
275 logger("Envelope is no XML file");
279 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
281 if (sizeof($children) == 0) {
282 logger("XML has no children");
288 $data = base64url_decode($children->data);
289 $type = $children->data->attributes()->type[0];
291 $encoding = $children->encoding;
293 $alg = $children->alg;
295 $sig = base64url_decode($children->sig);
296 $key_id = $children->sig->attributes()->key_id[0];
298 $handle = base64url_decode($key_id);
301 $b64url_data = base64url_encode($data);
302 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
304 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
307 logger('No author could be decoded. Discarding. Message: ' . $envelope);
311 $key = self::key($handle);
313 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
317 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
319 logger('Message from ' . $handle . ' did not verify. Discarding.');
327 * @brief encrypts data via AES
329 * @param string $key The AES key
330 * @param string $iv The IV (is used for CBC encoding)
331 * @param string $data The data that is to be encrypted
333 * @return string encrypted data
335 private static function aesEncrypt($key, $iv, $data)
337 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
341 * @brief decrypts data via AES
343 * @param string $key The AES key
344 * @param string $iv The IV (is used for CBC encoding)
345 * @param string $encrypted The encrypted data
347 * @return string decrypted data
349 private static function aesDecrypt($key, $iv, $encrypted)
351 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
355 * @brief: Decodes incoming Diaspora message in the new format
357 * @param array $importer Array of the importer user
358 * @param string $raw raw post message
361 * 'message' -> decoded Diaspora XML message
362 * 'author' -> author diaspora handle
363 * 'key' -> author public key (converted to pkcs#8)
365 public static function decodeRaw($importer, $raw)
367 $data = json_decode($raw);
369 // Is it a private post? Then decrypt the outer Salmon
370 if (is_object($data)) {
371 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
372 $ciphertext = base64_decode($data->encrypted_magic_envelope);
374 $outer_key_bundle = '';
375 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
376 $j_outer_key_bundle = json_decode($outer_key_bundle);
378 if (!is_object($j_outer_key_bundle)) {
379 logger('Outer Salmon did not verify. Discarding.');
380 System::httpExit(400);
383 $outer_iv = base64_decode($j_outer_key_bundle->iv);
384 $outer_key = base64_decode($j_outer_key_bundle->key);
386 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
391 $basedom = XML::parseString($xml);
393 if (!is_object($basedom)) {
394 logger('Received data does not seem to be an XML. Discarding. '.$xml);
395 System::httpExit(400);
398 $base = $basedom->children(NAMESPACE_SALMON_ME);
400 // Not sure if this cleaning is needed
401 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
403 // Build the signed data
404 $type = $base->data[0]->attributes()->type[0];
405 $encoding = $base->encoding;
407 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
409 // This is the signature
410 $signature = base64url_decode($base->sig);
412 // Get the senders' public key
413 $key_id = $base->sig[0]->attributes()->key_id[0];
414 $author_addr = base64_decode($key_id);
415 if ($author_addr == '') {
416 logger('No author could be decoded. Discarding. Message: ' . $xml);
417 System::httpExit(400);
420 $key = self::key($author_addr);
422 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
423 System::httpExit(400);
426 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
428 logger('Message did not verify. Discarding.');
429 System::httpExit(400);
432 return ['message' => (string)base64url_decode($base->data),
433 'author' => unxmlify($author_addr),
434 'key' => (string)$key];
438 * @brief: Decodes incoming Diaspora message in the deprecated format
440 * @param array $importer Array of the importer user
441 * @param string $xml urldecoded Diaspora salmon
444 * 'message' -> decoded Diaspora XML message
445 * 'author' -> author diaspora handle
446 * 'key' -> author public key (converted to pkcs#8)
448 public static function decode($importer, $xml)
451 $basedom = XML::parseString($xml);
453 if (!is_object($basedom)) {
454 logger("XML is not parseable.");
457 $children = $basedom->children('https://joindiaspora.com/protocol');
459 $inner_aes_key = null;
462 if ($children->header) {
464 $author_link = str_replace('acct:', '', $children->header->author_id);
466 // This happens with posts from a relais
468 logger("This is no private post in the old format", LOGGER_DEBUG);
472 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
474 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
475 $ciphertext = base64_decode($encrypted_header->ciphertext);
477 $outer_key_bundle = '';
478 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
480 $j_outer_key_bundle = json_decode($outer_key_bundle);
482 $outer_iv = base64_decode($j_outer_key_bundle->iv);
483 $outer_key = base64_decode($j_outer_key_bundle->key);
485 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
487 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
488 $idom = XML::parseString($decrypted);
490 $inner_iv = base64_decode($idom->iv);
491 $inner_aes_key = base64_decode($idom->aes_key);
493 $author_link = str_replace('acct:', '', $idom->author_id);
496 $dom = $basedom->children(NAMESPACE_SALMON_ME);
498 // figure out where in the DOM tree our data is hiding
501 if ($dom->provenance->data) {
502 $base = $dom->provenance;
503 } elseif ($dom->env->data) {
505 } elseif ($dom->data) {
510 logger('unable to locate salmon data in xml');
511 System::httpExit(400);
515 // Stash the signature away for now. We have to find their key or it won't be good for anything.
516 $signature = base64url_decode($base->sig);
520 // strip whitespace so our data element will return to one big base64 blob
521 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
524 // stash away some other stuff for later
526 $type = $base->data[0]->attributes()->type[0];
527 $keyhash = $base->sig[0]->attributes()->keyhash[0];
528 $encoding = $base->encoding;
532 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
536 $data = base64url_decode($data);
540 $inner_decrypted = $data;
542 // Decode the encrypted blob
543 $inner_encrypted = base64_decode($data);
544 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
548 logger('Could not retrieve author URI.');
549 System::httpExit(400);
551 // Once we have the author URI, go to the web and try to find their public key
552 // (first this will look it up locally if it is in the fcontact cache)
553 // This will also convert diaspora public key from pkcs#1 to pkcs#8
555 logger('Fetching key for '.$author_link);
556 $key = self::key($author_link);
559 logger('Could not retrieve author key.');
560 System::httpExit(400);
563 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
566 logger('Message did not verify. Discarding.');
567 System::httpExit(400);
570 logger('Message verified.');
572 return ['message' => (string)$inner_decrypted,
573 'author' => unxmlify($author_link),
574 'key' => (string)$key];
579 * @brief Dispatches public messages and find the fitting receivers
581 * @param array $msg The post that will be dispatched
583 * @return int The message id of the generated message, "true" or "false" if there was an error
585 public static function dispatchPublic($msg)
587 $enabled = intval(Config::get("system", "diaspora_enabled"));
589 logger("diaspora is disabled");
593 if (!($postdata = self::validPosting($msg))) {
594 logger("Invalid posting");
598 $fields = $postdata['fields'];
600 // Is it a an action (comment, like, ...) for our own post?
601 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
602 $guid = notags(unxmlify($fields->parent_guid));
603 $importer = self::importerForGuid($guid);
604 if (is_array($importer)) {
605 logger("delivering to origin: ".$importer["name"]);
606 $message_id = self::dispatch($importer, $msg, $fields);
611 // Process item retractions. This has to be done separated from the other stuff,
612 // since retractions for comments could come even from non followers.
613 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
614 $target = notags(unxmlify($fields->target_type));
615 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
616 logger('processing retraction for '.$target, LOGGER_DEBUG);
617 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
618 $message_id = self::dispatch($importer, $msg, $fields);
623 // Now distribute it to the followers
625 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
626 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
627 AND NOT `account_expired` AND NOT `account_removed`",
628 dbesc(NETWORK_DIASPORA),
629 dbesc($msg["author"])
632 if (DBM::is_result($r)) {
633 foreach ($r as $rr) {
634 logger("delivering to: ".$rr["username"]);
635 self::dispatch($rr, $msg, $fields);
637 } elseif (!Config::get('system', 'relay_subscribe', false)) {
638 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
640 // Use a dummy importer to import the data for the public copy
641 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
642 $message_id = self::dispatch($importer, $msg, $fields);
649 * @brief Dispatches the different message types to the different functions
651 * @param array $importer Array of the importer user
652 * @param array $msg The post that will be dispatched
653 * @param object $fields SimpleXML object that contains the message
655 * @return int The message id of the generated message, "true" or "false" if there was an error
657 public static function dispatch($importer, $msg, $fields = null)
659 // The sender is the handle of the contact that sent the message.
660 // This will often be different with relayed messages (for example "like" and "comment")
661 $sender = $msg["author"];
663 // This is only needed for private postings since this is already done for public ones before
664 if (is_null($fields)) {
665 if (!($postdata = self::validPosting($msg))) {
666 logger("Invalid posting");
669 $fields = $postdata['fields'];
672 $type = $fields->getName();
674 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
677 case "account_migration":
678 return self::receiveAccountMigration($importer, $fields);
680 case "account_deletion":
681 return self::receiveAccountDeletion($importer, $fields);
684 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
687 return self::receiveContactRequest($importer, $fields);
690 return self::receiveConversation($importer, $msg, $fields);
693 return self::receiveLike($importer, $sender, $fields);
696 return self::receiveMessage($importer, $fields);
698 case "participation":
699 return self::receiveParticipation($importer, $fields);
701 case "photo": // Not implemented
702 return self::receivePhoto($importer, $fields);
704 case "poll_participation": // Not implemented
705 return self::receivePollParticipation($importer, $fields);
708 return self::receiveProfile($importer, $fields);
711 return self::receiveReshare($importer, $fields, $msg["message"]);
714 return self::receiveRetraction($importer, $sender, $fields);
716 case "status_message":
717 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
720 logger("Unknown message type ".$type);
728 * @brief Checks if a posting is valid and fetches the data fields.
730 * This function does not only check the signature.
731 * It also does the conversion between the old and the new diaspora format.
733 * @param array $msg Array with the XML, the sender handle and the sender signature
735 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
737 private static function validPosting($msg)
739 $data = XML::parseString($msg["message"]);
741 if (!is_object($data)) {
742 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
746 // Is this the new or the old version?
747 if ($data->getName() == "XML") {
749 foreach ($data->post->children() as $child) {
757 $type = $element->getName();
760 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
762 // All retractions are handled identically from now on.
763 // In the new version there will only be "retraction".
764 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
765 $type = "retraction";
767 if ($type == "request") {
771 $fields = new SimpleXMLElement("<".$type."/>");
774 $author_signature = null;
775 $parent_author_signature = null;
777 foreach ($element->children() as $fieldname => $entry) {
779 // Translation for the old XML structure
780 if ($fieldname == "diaspora_handle") {
781 $fieldname = "author";
783 if ($fieldname == "participant_handles") {
784 $fieldname = "participants";
786 if (in_array($type, ["like", "participation"])) {
787 if ($fieldname == "target_type") {
788 $fieldname = "parent_type";
791 if ($fieldname == "sender_handle") {
792 $fieldname = "author";
794 if ($fieldname == "recipient_handle") {
795 $fieldname = "recipient";
797 if ($fieldname == "root_diaspora_id") {
798 $fieldname = "root_author";
800 if ($type == "status_message") {
801 if ($fieldname == "raw_message") {
805 if ($type == "retraction") {
806 if ($fieldname == "post_guid") {
807 $fieldname = "target_guid";
809 if ($fieldname == "type") {
810 $fieldname = "target_type";
815 if (($fieldname == "author_signature") && ($entry != "")) {
816 $author_signature = base64_decode($entry);
817 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
818 $parent_author_signature = base64_decode($entry);
819 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
820 if ($signed_data != "") {
824 $signed_data .= $entry;
826 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
827 || ($orig_type == "relayable_retraction")
829 XML::copy($entry, $fields, $fieldname);
833 // This is something that shouldn't happen at all.
834 if (in_array($type, ["status_message", "reshare", "profile"])) {
835 if ($msg["author"] != $fields->author) {
836 logger("Message handle is not the same as envelope sender. Quitting this message.");
841 // Only some message types have signatures. So we quit here for the other types.
842 if (!in_array($type, ["comment", "like"])) {
843 return ["fields" => $fields, "relayed" => false];
845 // No author_signature? This is a must, so we quit.
846 if (!isset($author_signature)) {
847 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
851 if (isset($parent_author_signature)) {
854 $key = self::key($msg["author"]);
856 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
857 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);
864 $key = self::key($fields->author);
866 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
867 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
870 return ["fields" => $fields, "relayed" => $relayed];
875 * @brief Fetches the public key for a given handle
877 * @param string $handle The handle
879 * @return string The public key
881 private static function key($handle)
883 $handle = strval($handle);
885 logger("Fetching diaspora key for: ".$handle);
887 $r = self::personByHandle($handle);
896 * @brief Fetches data for a given handle
898 * @param string $handle The handle
900 * @return array the queried data
902 public static function personByHandle($handle)
906 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
907 if (DBM::is_result($person)) {
908 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
910 // update record occasionally so it doesn't get stale
911 $d = strtotime($person["updated"]." +00:00");
912 if ($d < strtotime("now - 14 days")) {
916 if ($person["guid"] == "") {
921 if (!DBM::is_result($person) || $update) {
922 logger("create or refresh", LOGGER_DEBUG);
923 $r = Probe::uri($handle, NETWORK_DIASPORA);
925 // Note that Friendica contacts will return a "Diaspora person"
926 // if Diaspora connectivity is enabled on their server
927 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
928 self::addFContact($r, $update);
930 // Fetch the updated or added contact
931 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
932 if (!DBM::is_result($person)) {
942 * @brief Updates the fcontact table
944 * @param array $arr The fcontact data
945 * @param bool $update Update or insert?
947 * @return string The id of the fcontact entry
949 private static function addFContact($arr, $update = false)
953 "UPDATE `fcontact` SET
967 WHERE `url` = '%s' AND `network` = '%s'",
969 dbesc($arr["photo"]),
970 dbesc($arr["request"]),
972 dbesc(strtolower($arr["addr"])),
974 dbesc($arr["batch"]),
975 dbesc($arr["notify"]),
977 dbesc($arr["confirm"]),
978 dbesc($arr["alias"]),
979 dbesc($arr["pubkey"]),
980 dbesc(DateTimeFormat::utcNow()),
982 dbesc($arr["network"])
986 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
987 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
988 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
991 dbesc($arr["photo"]),
992 dbesc($arr["request"]),
996 dbesc($arr["batch"]),
997 dbesc($arr["notify"]),
999 dbesc($arr["confirm"]),
1000 dbesc($arr["network"]),
1001 dbesc($arr["alias"]),
1002 dbesc($arr["pubkey"]),
1003 dbesc(DateTimeFormat::utcNow())
1011 * @brief get a handle (user@domain.tld) from a given contact id
1013 * @param int $contact_id The id in the contact table
1014 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1016 * @return string the handle
1018 private static function handleFromContact($contact_id, $pcontact_id = 0)
1022 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
1024 if ($pcontact_id != 0) {
1026 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
1027 intval($pcontact_id)
1030 if (DBM::is_result($r)) {
1031 return strtolower($r[0]["addr"]);
1036 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1040 if (DBM::is_result($r)) {
1043 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
1045 if ($contact['addr'] != "") {
1046 $handle = $contact['addr'];
1048 $baseurl_start = strpos($contact['url'], '://') + 3;
1049 // allows installations in a subdirectory--not sure how Diaspora will handle
1050 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1051 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1052 $handle = $contact['nick'].'@'.$baseurl;
1056 return strtolower($handle);
1060 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1063 * @param mixed $fcontact_guid Hexadecimal string guid
1065 * @return string the contact url or null
1067 public static function urlFromContactGuid($fcontact_guid)
1069 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
1072 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1073 dbesc(NETWORK_DIASPORA),
1074 dbesc($fcontact_guid)
1077 if (DBM::is_result($r)) {
1078 return $r[0]['url'];
1085 * @brief Get a contact id for a given handle
1087 * @todo Move to Friendica\Model\Contact
1089 * @param int $uid The user id
1090 * @param string $handle The handle in the format user@domain.tld
1092 * @return int Contact id
1094 private static function contactByHandle($uid, $handle)
1096 // First do a direct search on the contact table
1098 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1103 if (DBM::is_result($r)) {
1107 * We haven't found it?
1108 * We use another function for it that will possibly create a contact entry.
1110 $cid = Contact::getIdForURL($handle, $uid);
1113 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1114 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1116 if (DBM::is_result($r)) {
1122 $handle_parts = explode("@", $handle);
1123 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1125 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1126 dbesc(NETWORK_DFRN),
1130 if (DBM::is_result($r)) {
1134 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1139 * @brief Check if posting is allowed for this contact
1141 * @param array $importer Array of the importer user
1142 * @param array $contact The contact that is checked
1143 * @param bool $is_comment Is the check for a comment?
1145 * @return bool is the contact allowed to post?
1147 private static function postAllow($importer, $contact, $is_comment = false)
1150 * Perhaps we were already sharing with this person. Now they're sharing with us.
1151 * That makes us friends.
1152 * Normally this should have handled by getting a request - but this could get lost
1154 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1155 // It is not removed by now. Possibly the code is needed?
1156 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1159 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1160 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1163 // $contact["rel"] = CONTACT_IS_FRIEND;
1164 // logger("defining user ".$contact["nick"]." as friend");
1167 // We don't seem to like that person
1168 if ($contact["blocked"] || $contact["readonly"]) {
1169 // Maybe blocked, don't accept.
1171 // We are following this person?
1172 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1173 // Yes, then it is fine.
1175 // Is it a post to a community?
1176 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && in_array($importer["page-flags"], [PAGE_COMMUNITY, PAGE_PRVGROUP])) {
1179 // Is the message a global user or a comment?
1180 } elseif (($importer["uid"] == 0) || $is_comment) {
1181 // Messages for the global users and comments are always accepted
1189 * @brief Fetches the contact id for a handle and checks if posting is allowed
1191 * @param array $importer Array of the importer user
1192 * @param string $handle The checked handle in the format user@domain.tld
1193 * @param bool $is_comment Is the check for a comment?
1195 * @return array The contact data
1197 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1199 $contact = self::contactByHandle($importer["uid"], $handle);
1201 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1202 // If a contact isn't found, we accept it anyway if it is a comment
1210 if (!self::postAllow($importer, $contact, $is_comment)) {
1211 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1218 * @brief Does the message already exists on the system?
1220 * @param int $uid The user id
1221 * @param string $guid The guid of the message
1223 * @return int|bool message id if the message already was stored into the system - or false.
1225 private static function messageExists($uid, $guid)
1228 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1233 if (DBM::is_result($r)) {
1234 logger("message ".$guid." already exists for user ".$uid);
1242 * @brief Checks for links to posts in a message
1244 * @param array $item The item array
1247 private static function fetchGuid($item)
1249 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1250 preg_replace_callback(
1252 function ($match) use ($item) {
1253 self::fetchGuidSub($match, $item);
1258 preg_replace_callback(
1259 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1260 function ($match) use ($item) {
1261 self::fetchGuidSub($match, $item);
1268 * @brief Checks for relative /people/* links in an item body to match local
1269 * contacts or prepends the remote host taken from the author link.
1271 * @param string $body The item body to replace links from
1272 * @param string $author_link The author link for missing local contact fallback
1274 * @return string the replaced string
1276 public static function replacePeopleGuid($body, $author_link)
1278 $return = preg_replace_callback(
1279 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1280 function ($match) use ($author_link) {
1282 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1283 // 1 => '0123456789abcdef'
1285 $handle = self::urlFromContactGuid($match[1]);
1288 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1290 // No local match, restoring absolute remote URL from author scheme and host
1291 $author_url = parse_url($author_link);
1292 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1304 * @brief sub function of "fetchGuid" which checks for links in messages
1306 * @param array $match array containing a link that has to be checked for a message link
1307 * @param array $item The item array
1310 private static function fetchGuidSub($match, $item)
1312 if (!self::storeByGuid($match[1], $item["author-link"])) {
1313 self::storeByGuid($match[1], $item["owner-link"]);
1318 * @brief Fetches an item with a given guid from a given server
1320 * @param string $guid the message guid
1321 * @param string $server The server address
1322 * @param int $uid The user id of the user
1324 * @return int the message id of the stored message or false
1326 private static function storeByGuid($guid, $server, $uid = 0)
1328 $serverparts = parse_url($server);
1329 $server = $serverparts["scheme"]."://".$serverparts["host"];
1331 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1333 $msg = self::message($guid, $server);
1339 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1341 // Now call the dispatcher
1342 return self::dispatchPublic($msg);
1346 * @brief Fetches a message from a server
1348 * @param string $guid message guid
1349 * @param string $server The url of the server
1350 * @param int $level Endless loop prevention
1353 * 'message' => The message XML
1354 * 'author' => The author handle
1355 * 'key' => The public key of the author
1357 private static function message($guid, $server, $level = 0)
1363 // This will work for new Diaspora servers and Friendica servers from 3.5
1364 $source_url = $server."/fetch/post/".urlencode($guid);
1366 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1368 $envelope = Network::fetchUrl($source_url);
1370 logger("Envelope was fetched.", LOGGER_DEBUG);
1371 $x = self::verifyMagicEnvelope($envelope);
1373 logger("Envelope could not be verified.", LOGGER_DEBUG);
1375 logger("Envelope was verified.", LOGGER_DEBUG);
1381 // This will work for older Diaspora and Friendica servers
1383 $source_url = $server."/p/".urlencode($guid).".xml";
1384 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1386 $x = Network::fetchUrl($source_url);
1392 $source_xml = XML::parseString($x);
1394 if (!is_object($source_xml)) {
1398 if ($source_xml->post->reshare) {
1399 // Reshare of a reshare - old Diaspora version
1400 logger("Message is a reshare", LOGGER_DEBUG);
1401 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1402 } elseif ($source_xml->getName() == "reshare") {
1403 // Reshare of a reshare - new Diaspora version
1404 logger("Message is a new reshare", LOGGER_DEBUG);
1405 return self::message($source_xml->root_guid, $server, ++$level);
1410 // Fetch the author - for the old and the new Diaspora version
1411 if ($source_xml->post->status_message->diaspora_handle) {
1412 $author = (string)$source_xml->post->status_message->diaspora_handle;
1413 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1414 $author = (string)$source_xml->author;
1417 // If this isn't a "status_message" then quit
1419 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1423 $msg = ["message" => $x, "author" => $author];
1425 $msg["key"] = self::key($msg["author"]);
1431 * @brief Fetches the item record of a given guid
1433 * @param int $uid The user id
1434 * @param string $guid message guid
1435 * @param string $author The handle of the item
1436 * @param array $contact The contact of the item owner
1438 * @return array the item record
1440 private static function parentItem($uid, $guid, $author, $contact)
1443 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1444 `author-name`, `author-link`, `author-avatar`,
1445 `owner-name`, `owner-link`, `owner-avatar`
1446 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1452 $result = self::storeByGuid($guid, $contact["url"], $uid);
1455 $person = self::personByHandle($author);
1456 $result = self::storeByGuid($guid, $person["url"], $uid);
1460 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1463 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1464 `author-name`, `author-link`, `author-avatar`,
1465 `owner-name`, `owner-link`, `owner-avatar`
1466 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1474 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1477 logger("parent item found: parent: ".$guid." - user: ".$uid);
1483 * @brief returns contact details
1485 * @param array $def_contact The default contact if the person isn't found
1486 * @param array $person The record of the person
1487 * @param int $uid The user id
1490 * 'cid' => contact id
1491 * 'network' => network type
1493 private static function authorContactByUrl($def_contact, $person, $uid)
1495 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1496 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1497 if (DBM::is_result($contact)) {
1498 $cid = $contact["id"];
1499 $network = $contact["network"];
1501 $cid = $def_contact["id"];
1502 $network = NETWORK_DIASPORA;
1505 return ["cid" => $cid, "network" => $network];
1509 * @brief Is the profile a hubzilla profile?
1511 * @param string $url The profile link
1513 * @return bool is it a hubzilla server?
1515 public static function isRedmatrix($url)
1517 return(strstr($url, "/channel/"));
1521 * @brief Generate a post link with a given handle and message guid
1523 * @param string $addr The user handle
1524 * @param string $guid message guid
1525 * @param string $parent_guid optional parent guid
1527 * @return string the post link
1529 private static function plink($addr, $guid, $parent_guid = '')
1531 $contact = Contact::getDetailsByAddr($addr);
1535 if ($parent_guid != '') {
1536 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1538 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1542 if ($contact["network"] == NETWORK_DFRN) {
1543 return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1546 if (self::isRedmatrix($contact["url"])) {
1547 return $contact["url"] . "/?f=&mid=" . $guid;
1550 if ($parent_guid != '') {
1551 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1553 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1558 * @brief Receives account migration
1560 * @param array $importer Array of the importer user
1561 * @param object $data The message object
1563 * @return bool Success
1565 private static function receiveAccountMigration($importer, $data)
1567 $old_handle = notags(unxmlify($data->author));
1568 $new_handle = notags(unxmlify($data->profile->author));
1569 $signature = notags(unxmlify($data->signature));
1571 $contact = self::contactByHandle($importer["uid"], $old_handle);
1573 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1577 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1580 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1581 $key = self::key($old_handle);
1582 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1583 logger('No valid signature for migration.');
1587 // Update the profile
1588 self::receiveProfile($importer, $data->profile);
1590 // change the technical stuff in contact and gcontact
1591 $data = Probe::uri($new_handle);
1592 if ($data['network'] == NETWORK_PHANTOM) {
1593 logger('Account for '.$new_handle." couldn't be probed.");
1597 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1598 'name' => $data['name'], 'nick' => $data['nick'],
1599 'addr' => $data['addr'], 'batch' => $data['batch'],
1600 'notify' => $data['notify'], 'poll' => $data['poll'],
1601 'network' => $data['network']];
1603 dba::update('contact', $fields, ['addr' => $old_handle]);
1605 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1606 'name' => $data['name'], 'nick' => $data['nick'],
1607 'addr' => $data['addr'], 'connect' => $data['addr'],
1608 'notify' => $data['notify'], 'photo' => $data['photo'],
1609 'server_url' => $data['baseurl'], 'network' => $data['network']];
1611 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1613 logger('Contacts are updated.');
1616 /// @todo This is an extreme performance killer
1618 'owner-link' => [$contact["url"], $data["url"]],
1619 'author-link' => [$contact["url"], $data["url"]],
1621 foreach ($fields as $n => $f) {
1623 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1626 intval($importer["uid"])
1629 if (DBM::is_result($r)) {
1631 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1636 intval($importer["uid"])
1645 logger('Items are updated.');
1651 * @brief Processes an account deletion
1653 * @param array $importer Array of the importer user
1654 * @param object $data The message object
1656 * @return bool Success
1658 private static function receiveAccountDeletion($importer, $data)
1660 /// @todo Account deletion should remove the contact from the global contacts as well
1662 $author = notags(unxmlify($data->author));
1664 $contact = self::contactByHandle($importer["uid"], $author);
1666 logger("cannot find contact for author: ".$author);
1670 // We now remove the contact
1671 Contact::remove($contact["id"]);
1676 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1678 * @param string $author Author handle
1679 * @param string $guid Message guid
1680 * @param boolean $onlyfound Only return uri when found in the database
1682 * @return string The constructed uri or the one from our database
1684 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1686 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1687 if (DBM::is_result($r)) {
1688 return $r[0]["uri"];
1689 } elseif (!$onlyfound) {
1690 return $author.":".$guid;
1697 * @brief Fetch the guid from our database with a given uri
1699 * @param string $uri Message uri
1700 * @param string $uid Author handle
1702 * @return string The post guid
1704 private static function getGuidFromUri($uri, $uid)
1706 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1707 if (DBM::is_result($r)) {
1708 return $r[0]["guid"];
1715 * @brief Find the best importer for a comment, like, ...
1717 * @param string $guid The guid of the item
1719 * @return array|boolean the origin owner of that post - or false
1721 private static function importerForGuid($guid)
1723 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1725 if (DBM::is_result($item)) {
1726 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1727 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1728 if (DBM::is_result($contact)) {
1736 * @brief Processes an incoming comment
1738 * @param array $importer Array of the importer user
1739 * @param string $sender The sender of the message
1740 * @param object $data The message object
1741 * @param string $xml The original XML of the message
1743 * @return int The message id of the generated comment or "false" if there was an error
1745 private static function receiveComment($importer, $sender, $data, $xml)
1747 $author = notags(unxmlify($data->author));
1748 $guid = notags(unxmlify($data->guid));
1749 $parent_guid = notags(unxmlify($data->parent_guid));
1750 $text = unxmlify($data->text);
1752 if (isset($data->created_at)) {
1753 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1755 $created_at = DateTimeFormat::utcNow();
1758 if (isset($data->thread_parent_guid)) {
1759 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1760 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1765 $contact = self::allowedContactByHandle($importer, $sender, true);
1770 $message_id = self::messageExists($importer["uid"], $guid);
1775 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1776 if (!$parent_item) {
1780 $person = self::personByHandle($author);
1781 if (!is_array($person)) {
1782 logger("unable to find author details");
1786 // Fetch the contact id - if we know this contact
1787 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1791 $datarray["uid"] = $importer["uid"];
1792 $datarray["contact-id"] = $author_contact["cid"];
1793 $datarray["network"] = $author_contact["network"];
1795 $datarray["author-name"] = $person["name"];
1796 $datarray["author-link"] = $person["url"];
1797 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1799 $datarray["owner-name"] = $contact["name"];
1800 $datarray["owner-link"] = $contact["url"];
1801 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1803 $datarray["guid"] = $guid;
1804 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1806 $datarray["type"] = "remote-comment";
1807 $datarray["verb"] = ACTIVITY_POST;
1808 $datarray["gravity"] = GRAVITY_COMMENT;
1810 if ($thr_uri != "") {
1811 $datarray["parent-uri"] = $thr_uri;
1813 $datarray["parent-uri"] = $parent_item["uri"];
1816 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1818 $datarray["protocol"] = PROTOCOL_DIASPORA;
1819 $datarray["source"] = $xml;
1821 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1823 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1825 $body = Markdown::toBBCode($text);
1827 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1829 self::fetchGuid($datarray);
1831 $message_id = Item::insert($datarray);
1833 if ($message_id <= 0) {
1838 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1841 // If we are the origin of the parent we store the original data and notify our followers
1842 if ($message_id && $parent_item["origin"]) {
1843 // Formerly we stored the signed text, the signature and the author in different fields.
1844 // We now store the raw data so that we are more flexible.
1845 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1848 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1855 * @brief processes and stores private messages
1857 * @param array $importer Array of the importer user
1858 * @param array $contact The contact of the message
1859 * @param object $data The message object
1860 * @param array $msg Array of the processed message, author handle and key
1861 * @param object $mesg The private message
1862 * @param array $conversation The conversation record to which this message belongs
1864 * @return bool "true" if it was successful
1866 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1868 $author = notags(unxmlify($data->author));
1869 $guid = notags(unxmlify($data->guid));
1870 $subject = notags(unxmlify($data->subject));
1872 // "diaspora_handle" is the element name from the old version
1873 // "author" is the element name from the new version
1874 if ($mesg->author) {
1875 $msg_author = notags(unxmlify($mesg->author));
1876 } elseif ($mesg->diaspora_handle) {
1877 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1882 $msg_guid = notags(unxmlify($mesg->guid));
1883 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1884 $msg_text = unxmlify($mesg->text);
1885 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1887 if ($msg_conversation_guid != $guid) {
1888 logger("message conversation guid does not belong to the current conversation.");
1892 $body = Markdown::toBBCode($msg_text);
1893 $message_uri = $msg_author.":".$msg_guid;
1895 $person = self::personByHandle($msg_author);
1900 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1902 intval($importer["uid"])
1904 if (DBM::is_result($r)) {
1905 logger("duplicate message already delivered.", LOGGER_DEBUG);
1910 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1911 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1912 intval($importer["uid"]),
1914 intval($conversation["id"]),
1915 dbesc($person["name"]),
1916 dbesc($person["photo"]),
1917 dbesc($person["url"]),
1918 intval($contact["id"]),
1923 dbesc($message_uri),
1924 dbesc($author.":".$guid),
1925 dbesc($msg_created_at)
1930 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1934 "type" => NOTIFY_MAIL,
1935 "notify_flags" => $importer["notify-flags"],
1936 "language" => $importer["language"],
1937 "to_name" => $importer["username"],
1938 "to_email" => $importer["email"],
1939 "uid" =>$importer["uid"],
1940 "item" => ["subject" => $subject, "body" => $body],
1941 "source_name" => $person["name"],
1942 "source_link" => $person["url"],
1943 "source_photo" => $person["thumb"],
1944 "verb" => ACTIVITY_POST,
1951 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1953 * @param array $importer Array of the importer user
1954 * @param array $msg Array of the processed message, author handle and key
1955 * @param object $data The message object
1957 * @return bool Success
1959 private static function receiveConversation($importer, $msg, $data)
1961 $author = notags(unxmlify($data->author));
1962 $guid = notags(unxmlify($data->guid));
1963 $subject = notags(unxmlify($data->subject));
1964 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1965 $participants = notags(unxmlify($data->participants));
1967 $messages = $data->message;
1969 if (!count($messages)) {
1970 logger("empty conversation");
1974 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1979 $conversation = null;
1982 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1983 intval($importer["uid"]),
1987 $conversation = $c[0];
1990 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1991 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1992 intval($importer["uid"]),
1996 dbesc(DateTimeFormat::utcNow()),
1998 dbesc($participants)
2002 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2003 intval($importer["uid"]),
2009 $conversation = $c[0];
2012 if (!$conversation) {
2013 logger("unable to create conversation.");
2017 foreach ($messages as $mesg) {
2018 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2025 * @brief Creates the body for a "like" message
2027 * @param array $contact The contact that send us the "like"
2028 * @param array $parent_item The item array of the parent item
2029 * @param string $guid message guid
2031 * @return string the body
2033 private static function constructLikeBody($contact, $parent_item, $guid)
2035 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
2037 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2038 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
2039 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
2041 return sprintf($bodyverb, $ulink, $alink, $plink);
2045 * @brief Creates a XML object for a "like"
2047 * @param array $importer Array of the importer user
2048 * @param array $parent_item The item array of the parent item
2050 * @return string The XML
2052 private static function constructLikeObject($importer, $parent_item)
2054 $objtype = ACTIVITY_OBJ_NOTE;
2055 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
2056 $parent_body = $parent_item["body"];
2058 $xmldata = ["object" => ["type" => $objtype,
2060 "id" => $parent_item["uri"],
2063 "content" => $parent_body]];
2065 return XML::fromArray($xmldata, $xml, true);
2069 * @brief Processes "like" messages
2071 * @param array $importer Array of the importer user
2072 * @param string $sender The sender of the message
2073 * @param object $data The message object
2075 * @return int The message id of the generated like or "false" if there was an error
2077 private static function receiveLike($importer, $sender, $data)
2079 $author = notags(unxmlify($data->author));
2080 $guid = notags(unxmlify($data->guid));
2081 $parent_guid = notags(unxmlify($data->parent_guid));
2082 $parent_type = notags(unxmlify($data->parent_type));
2083 $positive = notags(unxmlify($data->positive));
2085 // likes on comments aren't supported by Diaspora - only on posts
2086 // But maybe this will be supported in the future, so we will accept it.
2087 if (!in_array($parent_type, ["Post", "Comment"])) {
2091 $contact = self::allowedContactByHandle($importer, $sender, true);
2096 $message_id = self::messageExists($importer["uid"], $guid);
2101 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2102 if (!$parent_item) {
2106 $person = self::personByHandle($author);
2107 if (!is_array($person)) {
2108 logger("unable to find author details");
2112 // Fetch the contact id - if we know this contact
2113 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2115 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2116 // We would accept this anyhow.
2117 if ($positive == "true") {
2118 $verb = ACTIVITY_LIKE;
2120 $verb = ACTIVITY_DISLIKE;
2125 $datarray["protocol"] = PROTOCOL_DIASPORA;
2127 $datarray["uid"] = $importer["uid"];
2128 $datarray["contact-id"] = $author_contact["cid"];
2129 $datarray["network"] = $author_contact["network"];
2131 $datarray["author-name"] = $person["name"];
2132 $datarray["author-link"] = $person["url"];
2133 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2135 $datarray["owner-name"] = $contact["name"];
2136 $datarray["owner-link"] = $contact["url"];
2137 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2139 $datarray["guid"] = $guid;
2140 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2142 $datarray["type"] = "activity";
2143 $datarray["verb"] = $verb;
2144 $datarray["gravity"] = GRAVITY_LIKE;
2145 $datarray["parent-uri"] = $parent_item["uri"];
2147 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2148 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2150 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2152 $message_id = Item::insert($datarray);
2154 if ($message_id <= 0) {
2159 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2162 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2163 if ($parent_item["id"] != $parent_item["parent"]) {
2164 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2165 $origin = $toplevel["origin"];
2167 $origin = $parent_item["origin"];
2170 // If we are the origin of the parent we store the original data and notify our followers
2171 if ($message_id && $origin) {
2172 // Formerly we stored the signed text, the signature and the author in different fields.
2173 // We now store the raw data so that we are more flexible.
2174 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2177 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2184 * @brief Processes private messages
2186 * @param array $importer Array of the importer user
2187 * @param object $data The message object
2189 * @return bool Success?
2191 private static function receiveMessage($importer, $data)
2193 $author = notags(unxmlify($data->author));
2194 $guid = notags(unxmlify($data->guid));
2195 $conversation_guid = notags(unxmlify($data->conversation_guid));
2196 $text = unxmlify($data->text);
2197 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2199 $contact = self::allowedContactByHandle($importer, $author, true);
2204 $conversation = null;
2207 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2208 intval($importer["uid"]),
2209 dbesc($conversation_guid)
2212 $conversation = $c[0];
2214 logger("conversation not available.");
2218 $message_uri = $author.":".$guid;
2220 $person = self::personByHandle($author);
2222 logger("unable to find author details");
2226 $body = Markdown::toBBCode($text);
2228 $body = self::replacePeopleGuid($body, $person["url"]);
2233 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2235 intval($importer["uid"])
2237 if (DBM::is_result($r)) {
2238 logger("duplicate message already delivered.", LOGGER_DEBUG);
2243 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2244 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2245 intval($importer["uid"]),
2247 intval($conversation["id"]),
2248 dbesc($person["name"]),
2249 dbesc($person["photo"]),
2250 dbesc($person["url"]),
2251 intval($contact["id"]),
2252 dbesc($conversation["subject"]),
2256 dbesc($message_uri),
2257 dbesc($author.":".$conversation["guid"]),
2263 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2268 * @brief Processes participations - unsupported by now
2270 * @param array $importer Array of the importer user
2271 * @param object $data The message object
2273 * @return bool always true
2275 private static function receiveParticipation($importer, $data)
2277 $author = strtolower(notags(unxmlify($data->author)));
2278 $parent_guid = notags(unxmlify($data->parent_guid));
2280 $contact_id = Contact::getIdForURL($author);
2282 logger('Contact not found: '.$author);
2286 $person = self::personByHandle($author);
2287 if (!is_array($person)) {
2288 logger("Person not found: ".$author);
2292 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2293 if (!DBM::is_result($item)) {
2294 logger('Item not found, no origin or private: '.$parent_guid);
2298 $author_parts = explode('@', $author);
2299 if (isset($author_parts[1])) {
2300 $server = $author_parts[1];
2302 // Should never happen
2306 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2308 if (!dba::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2309 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2312 // Send all existing comments and likes to the requesting server
2313 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2315 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2316 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2317 while ($comment = dba::fetch($comments)) {
2318 if ($comment['verb'] == ACTIVITY_POST) {
2319 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2321 $cmd = $comment['self'] ? 'like' : 'comment-import';
2323 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2324 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2326 dba::close($comments);
2332 * @brief Processes photos - unneeded
2334 * @param array $importer Array of the importer user
2335 * @param object $data The message object
2337 * @return bool always true
2339 private static function receivePhoto($importer, $data)
2341 // There doesn't seem to be a reason for this function,
2342 // since the photo data is transmitted in the status message as well
2347 * @brief Processes poll participations - unssupported
2349 * @param array $importer Array of the importer user
2350 * @param object $data The message object
2352 * @return bool always true
2354 private static function receivePollParticipation($importer, $data)
2356 // We don't support polls by now
2361 * @brief Processes incoming profile updates
2363 * @param array $importer Array of the importer user
2364 * @param object $data The message object
2366 * @return bool Success
2368 private static function receiveProfile($importer, $data)
2370 $author = strtolower(notags(unxmlify($data->author)));
2372 $contact = self::contactByHandle($importer["uid"], $author);
2377 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2378 $image_url = unxmlify($data->image_url);
2379 $birthday = unxmlify($data->birthday);
2380 $gender = unxmlify($data->gender);
2381 $about = Markdown::toBBCode(unxmlify($data->bio));
2382 $location = Markdown::toBBCode(unxmlify($data->location));
2383 $searchable = (unxmlify($data->searchable) == "true");
2384 $nsfw = (unxmlify($data->nsfw) == "true");
2385 $tags = unxmlify($data->tag_string);
2387 $tags = explode("#", $tags);
2390 foreach ($tags as $tag) {
2391 $tag = trim(strtolower($tag));
2397 $keywords = implode(", ", $keywords);
2399 $handle_parts = explode("@", $author);
2400 $nick = $handle_parts[0];
2403 $name = $handle_parts[0];
2406 if (preg_match("|^https?://|", $image_url) === 0) {
2407 $image_url = "http://".$handle_parts[1].$image_url;
2410 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2412 // Generic birthday. We don't know the timezone. The year is irrelevant.
2414 $birthday = str_replace("1000", "1901", $birthday);
2416 if ($birthday != "") {
2417 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2420 // this is to prevent multiple birthday notifications in a single year
2421 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2423 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2424 $birthday = $contact["bd"];
2428 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2429 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2433 dbesc(DateTimeFormat::utcNow()),
2439 intval($contact["id"]),
2440 intval($importer["uid"])
2443 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2444 "photo" => $image_url, "name" => $name, "location" => $location,
2445 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2446 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2447 "hide" => !$searchable, "nsfw" => $nsfw];
2449 $gcid = GContact::update($gcontact);
2451 GContact::link($gcid, $importer["uid"], $contact["id"]);
2453 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2459 * @brief Processes incoming friend requests
2461 * @param array $importer Array of the importer user
2462 * @param array $contact The contact that send the request
2465 private static function receiveRequestMakeFriend($importer, $contact)
2469 if ($contact["rel"] == CONTACT_IS_SHARING) {
2472 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2473 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2476 // send notification
2479 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2480 intval($importer["uid"])
2483 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2485 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2486 intval($importer["uid"])
2489 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2491 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2493 $arr["protocol"] = PROTOCOL_DIASPORA;
2494 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2495 $arr["uid"] = $importer["uid"];
2496 $arr["contact-id"] = $self[0]["id"];
2498 $arr["type"] = 'wall';
2499 $arr["gravity"] = 0;
2501 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2502 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2503 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2504 $arr["verb"] = ACTIVITY_FRIEND;
2505 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2507 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2508 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2509 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2510 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2512 $arr["object"] = self::constructNewFriendObject($contact);
2514 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2516 $arr["allow_cid"] = $user["allow_cid"];
2517 $arr["allow_gid"] = $user["allow_gid"];
2518 $arr["deny_cid"] = $user["deny_cid"];
2519 $arr["deny_gid"] = $user["deny_gid"];
2521 $i = Item::insert($arr);
2523 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2530 * @brief Creates a XML object for a "new friend" message
2532 * @param array $contact Array of the contact
2534 * @return string The XML
2536 private static function constructNewFriendObject($contact)
2538 $objtype = ACTIVITY_OBJ_PERSON;
2539 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2540 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2542 $xmldata = ["object" => ["type" => $objtype,
2543 "title" => $contact["name"],
2544 "id" => $contact["url"]."/".$contact["name"],
2547 return XML::fromArray($xmldata, $xml, true);
2551 * @brief Processes incoming sharing notification
2553 * @param array $importer Array of the importer user
2554 * @param object $data The message object
2556 * @return bool Success
2558 private static function receiveContactRequest($importer, $data)
2560 $author = unxmlify($data->author);
2561 $recipient = unxmlify($data->recipient);
2563 if (!$author || !$recipient) {
2567 // the current protocol version doesn't know these fields
2568 // That means that we will assume their existance
2569 if (isset($data->following)) {
2570 $following = (unxmlify($data->following) == "true");
2575 if (isset($data->sharing)) {
2576 $sharing = (unxmlify($data->sharing) == "true");
2581 $contact = self::contactByHandle($importer["uid"], $author);
2583 // perhaps we were already sharing with this person. Now they're sharing with us.
2584 // That makes us friends.
2587 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2588 self::receiveRequestMakeFriend($importer, $contact);
2590 // refetch the contact array
2591 $contact = self::contactByHandle($importer["uid"], $author);
2593 // If we are now friends, we are sending a share message.
2594 // Normally we needn't to do so, but the first message could have been vanished.
2595 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2596 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2598 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2599 $ret = self::sendShare($u[0], $contact);
2604 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2605 Contact::removeFollower($importer, $contact);
2610 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2611 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2613 } elseif (!$following && !$sharing) {
2614 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2616 } elseif (!$following && $sharing) {
2617 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2618 } elseif ($following && $sharing) {
2619 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2620 } elseif ($following && !$sharing) {
2621 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2624 $ret = self::personByHandle($author);
2626 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2627 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2631 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2634 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2635 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2636 intval($importer["uid"]),
2637 dbesc($ret["network"]),
2638 dbesc($ret["addr"]),
2639 DateTimeFormat::utcNow(),
2641 dbesc(normalise_link($ret["url"])),
2643 dbesc($ret["name"]),
2644 dbesc($ret["nick"]),
2645 dbesc($ret["photo"]),
2646 dbesc($ret["pubkey"]),
2647 dbesc($ret["notify"]),
2648 dbesc($ret["poll"]),
2653 // find the contact record we just created
2655 $contact_record = self::contactByHandle($importer["uid"], $author);
2657 if (!$contact_record) {
2658 logger("unable to locate newly created contact record.");
2662 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2664 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2666 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2668 if (in_array($importer["page-flags"], [PAGE_NORMAL, PAGE_PRVGROUP])) {
2669 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2671 $hash = random_string().(string)time(); // Generate a confirm_key
2674 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2675 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2676 intval($importer["uid"]),
2677 intval($contact_record["id"]),
2680 dbesc(L10n::t("Sharing notification from Diaspora network")),
2682 dbesc(DateTimeFormat::utcNow())
2685 // automatic friend approval
2687 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2689 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2691 // technically they are sharing with us (CONTACT_IS_SHARING),
2692 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2693 // we are going to change the relationship and make them a follower.
2695 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2696 $new_relation = CONTACT_IS_FRIEND;
2697 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2698 $new_relation = CONTACT_IS_SHARING;
2700 $new_relation = CONTACT_IS_FOLLOWER;
2704 "UPDATE `contact` SET `rel` = %d,
2712 intval($new_relation),
2713 dbesc(DateTimeFormat::utcNow()),
2714 dbesc(DateTimeFormat::utcNow()),
2715 intval($contact_record["id"])
2718 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2720 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2721 $ret = self::sendShare($u[0], $contact_record);
2723 // Send the profile data, maybe it weren't transmitted before
2724 self::sendProfile($importer["uid"], [$contact_record]);
2732 * @brief Fetches a message with a given guid
2734 * @param string $guid message guid
2735 * @param string $orig_author handle of the original post
2736 * @param string $author handle of the sharer
2738 * @return array The fetched item
2740 public static function originalItem($guid, $orig_author)
2742 // Do we already have this item?
2743 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2744 'author-name', 'author-link', 'author-avatar'];
2745 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false];
2746 $item = dba::selectfirst('item', $fields, $condition);
2748 if (DBM::is_result($item)) {
2749 logger("reshared message ".$guid." already exists on system.");
2751 // Maybe it is already a reshared item?
2752 // Then refetch the content, if it is a reshare from a reshare.
2753 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2754 if (self::isReshare($item["body"], true)) {
2756 } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2757 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2759 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2761 // Add OEmbed and other information to the body
2762 $item["body"] = add_page_info_to_body($item["body"], false, true);
2770 if (!DBM::is_result($r)) {
2771 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2772 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2773 $item_id = self::storeByGuid($guid, $server);
2776 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2777 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2778 $item_id = self::storeByGuid($guid, $server);
2782 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2783 'author-name', 'author-link', 'author-avatar'];
2784 $condition = ['id' => $item_id, 'visible' => true, 'deleted' => false];
2785 $item = dba::selectfirst('item', $fields, $condition);
2787 if (DBM::is_result($item)) {
2788 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2789 if (self::isReshare($item["body"], false)) {
2790 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2791 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2802 * @brief Processes a reshare message
2804 * @param array $importer Array of the importer user
2805 * @param object $data The message object
2806 * @param string $xml The original XML of the message
2808 * @return int the message id
2810 private static function receiveReshare($importer, $data, $xml)
2812 $author = notags(unxmlify($data->author));
2813 $guid = notags(unxmlify($data->guid));
2814 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2815 $root_author = notags(unxmlify($data->root_author));
2816 $root_guid = notags(unxmlify($data->root_guid));
2817 /// @todo handle unprocessed property "provider_display_name"
2818 $public = notags(unxmlify($data->public));
2820 $contact = self::allowedContactByHandle($importer, $author, false);
2825 $message_id = self::messageExists($importer["uid"], $guid);
2830 $original_item = self::originalItem($root_guid, $root_author);
2831 if (!$original_item) {
2835 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2839 $datarray["uid"] = $importer["uid"];
2840 $datarray["contact-id"] = $contact["id"];
2841 $datarray["network"] = NETWORK_DIASPORA;
2843 $datarray["author-name"] = $contact["name"];
2844 $datarray["author-link"] = $contact["url"];
2845 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2847 $datarray["owner-name"] = $datarray["author-name"];
2848 $datarray["owner-link"] = $datarray["author-link"];
2849 $datarray["owner-avatar"] = $datarray["author-avatar"];
2851 $datarray["guid"] = $guid;
2852 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2854 $datarray["verb"] = ACTIVITY_POST;
2855 $datarray["gravity"] = GRAVITY_PARENT;
2857 $datarray["protocol"] = PROTOCOL_DIASPORA;
2858 $datarray["source"] = $xml;
2860 $prefix = share_header(
2861 $original_item["author-name"],
2862 $original_item["author-link"],
2863 $original_item["author-avatar"],
2864 $original_item["guid"],
2865 $original_item["created"],
2868 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2870 $datarray["tag"] = $original_item["tag"];
2871 $datarray["app"] = $original_item["app"];
2873 $datarray["plink"] = self::plink($author, $guid);
2874 $datarray["private"] = (($public == "false") ? 1 : 0);
2875 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2877 $datarray["object-type"] = $original_item["object-type"];
2879 self::fetchGuid($datarray);
2880 $message_id = Item::insert($datarray);
2882 self::sendParticipation($contact, $datarray);
2885 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2893 * @brief Processes retractions
2895 * @param array $importer Array of the importer user
2896 * @param array $contact The contact of the item owner
2897 * @param object $data The message object
2899 * @return bool success
2901 private static function itemRetraction($importer, $contact, $data)
2903 $author = notags(unxmlify($data->author));
2904 $target_guid = notags(unxmlify($data->target_guid));
2905 $target_type = notags(unxmlify($data->target_type));
2907 $person = self::personByHandle($author);
2908 if (!is_array($person)) {
2909 logger("unable to find author detail for ".$author);
2913 if (empty($contact["url"])) {
2914 $contact["url"] = $person["url"];
2917 // Fetch items that are about to be deleted
2918 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2920 // When we receive a public retraction, we delete every item that we find.
2921 if ($importer['uid'] == 0) {
2922 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2924 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2926 $r = dba::select('item', $fields, $condition);
2927 if (!DBM::is_result($r)) {
2928 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2932 while ($item = dba::fetch($r)) {
2933 // Fetch the parent item
2934 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2936 // Only delete it if the parent author really fits
2937 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2938 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2942 Item::deleteById($item["id"]);
2944 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2946 // Now check if the retraction needs to be relayed by us
2947 if ($parent["origin"]) {
2949 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2957 * @brief Receives retraction messages
2959 * @param array $importer Array of the importer user
2960 * @param string $sender The sender of the message
2961 * @param object $data The message object
2963 * @return bool Success
2965 private static function receiveRetraction($importer, $sender, $data)
2967 $target_type = notags(unxmlify($data->target_type));
2969 $contact = self::contactByHandle($importer["uid"], $sender);
2970 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2971 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2975 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2977 switch ($target_type) {
2982 case "StatusMessage":
2983 return self::itemRetraction($importer, $contact, $data);
2987 /// @todo What should we do with an "unshare"?
2988 // Removing the contact isn't correct since we still can read the public items
2989 Contact::remove($contact["id"]);
2993 logger("Unknown target type ".$target_type);
3000 * @brief Receives status messages
3002 * @param array $importer Array of the importer user
3003 * @param object $data The message object
3004 * @param string $xml The original XML of the message
3006 * @return int The message id of the newly created item
3008 private static function receiveStatusMessage($importer, $data, $xml)
3010 $author = notags(unxmlify($data->author));
3011 $guid = notags(unxmlify($data->guid));
3012 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
3013 $public = notags(unxmlify($data->public));
3014 $text = unxmlify($data->text);
3015 $provider_display_name = notags(unxmlify($data->provider_display_name));
3017 $contact = self::allowedContactByHandle($importer, $author, false);
3022 $message_id = self::messageExists($importer["uid"], $guid);
3028 if ($data->location) {
3029 foreach ($data->location->children() as $fieldname => $data) {
3030 $address[$fieldname] = notags(unxmlify($data));
3034 $body = Markdown::toBBCode($text);
3038 // Attach embedded pictures to the body
3040 foreach ($data->photo as $photo) {
3041 $body = "[img]".unxmlify($photo->remote_photo_path).
3042 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
3045 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
3047 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
3049 // Add OEmbed and other information to the body
3050 if (!self::isRedmatrix($contact["url"])) {
3051 $body = add_page_info_to_body($body, false, true);
3055 /// @todo enable support for polls
3056 //if ($data->poll) {
3057 // foreach ($data->poll AS $poll)
3062 /// @todo enable support for events
3064 $datarray["uid"] = $importer["uid"];
3065 $datarray["contact-id"] = $contact["id"];
3066 $datarray["network"] = NETWORK_DIASPORA;
3068 $datarray["author-name"] = $contact["name"];
3069 $datarray["author-link"] = $contact["url"];
3070 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
3072 $datarray["owner-name"] = $datarray["author-name"];
3073 $datarray["owner-link"] = $datarray["author-link"];
3074 $datarray["owner-avatar"] = $datarray["author-avatar"];
3076 $datarray["guid"] = $guid;
3077 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3079 $datarray["verb"] = ACTIVITY_POST;
3080 $datarray["gravity"] = GRAVITY_PARENT;
3082 $datarray["protocol"] = PROTOCOL_DIASPORA;
3083 $datarray["source"] = $xml;
3085 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3087 if ($provider_display_name != "") {
3088 $datarray["app"] = $provider_display_name;
3091 $datarray["plink"] = self::plink($author, $guid);
3092 $datarray["private"] = (($public == "false") ? 1 : 0);
3093 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3095 if (isset($address["address"])) {
3096 $datarray["location"] = $address["address"];
3099 if (isset($address["lat"]) && isset($address["lng"])) {
3100 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3103 self::fetchGuid($datarray);
3104 $message_id = Item::insert($datarray);
3106 self::sendParticipation($contact, $datarray);
3109 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3116 /* ************************************************************************************** *
3117 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3118 * ************************************************************************************** */
3121 * @brief returnes the handle of a contact
3123 * @param array $contact contact array
3125 * @return string the handle in the format user@domain.tld
3127 private static function myHandle($contact)
3129 if ($contact["addr"] != "") {
3130 return $contact["addr"];
3133 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3134 // So - just in case - we build the the address here.
3135 if ($contact["nickname"] != "") {
3136 $nick = $contact["nickname"];
3138 $nick = $contact["nick"];
3141 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3146 * @brief Creates the data for a private message in the new format
3148 * @param string $msg The message that is to be transmitted
3149 * @param array $user The record of the sender
3150 * @param array $contact Target of the communication
3151 * @param string $prvkey The private key of the sender
3152 * @param string $pubkey The public key of the receiver
3154 * @return string The encrypted data
3156 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3158 logger("Message: ".$msg, LOGGER_DATA);
3160 // without a public key nothing will work
3162 logger("pubkey missing: contact id: ".$contact["id"]);
3166 $aes_key = openssl_random_pseudo_bytes(32);
3167 $b_aes_key = base64_encode($aes_key);
3168 $iv = openssl_random_pseudo_bytes(16);
3169 $b_iv = base64_encode($iv);
3171 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3173 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3175 $encrypted_key_bundle = "";
3176 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3178 $json_object = json_encode(
3179 ["aes_key" => base64_encode($encrypted_key_bundle),
3180 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3183 return $json_object;
3187 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3189 * @param string $msg The message that is to be transmitted
3190 * @param array $user The record of the sender
3192 * @return string The envelope
3194 public static function buildMagicEnvelope($msg, $user)
3196 $b64url_data = base64url_encode($msg);
3197 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3199 $key_id = base64url_encode(self::myHandle($user));
3200 $type = "application/xml";
3201 $encoding = "base64url";
3202 $alg = "RSA-SHA256";
3203 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3205 // Fallback if the private key wasn't transmitted in the expected field
3206 if ($user['uprvkey'] == "") {
3207 $user['uprvkey'] = $user['prvkey'];
3210 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3211 $sig = base64url_encode($signature);
3213 $xmldata = ["me:env" => ["me:data" => $data,
3214 "@attributes" => ["type" => $type],
3215 "me:encoding" => $encoding,
3218 "@attributes2" => ["key_id" => $key_id]]];
3220 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3222 return XML::fromArray($xmldata, $xml, false, $namespaces);
3226 * @brief Create the envelope for a message
3228 * @param string $msg The message that is to be transmitted
3229 * @param array $user The record of the sender
3230 * @param array $contact Target of the communication
3231 * @param string $prvkey The private key of the sender
3232 * @param string $pubkey The public key of the receiver
3233 * @param bool $public Is the message public?
3235 * @return string The message that will be transmitted to other servers
3237 public static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3239 // The message is put into an envelope with the sender's signature
3240 $envelope = self::buildMagicEnvelope($msg, $user);
3242 // Private messages are put into a second envelope, encrypted with the receivers public key
3244 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3251 * @brief Creates a signature for a message
3253 * @param array $owner the array of the owner of the message
3254 * @param array $message The message that is to be signed
3256 * @return string The signature
3258 private static function signature($owner, $message)
3261 unset($sigmsg["author_signature"]);
3262 unset($sigmsg["parent_author_signature"]);
3264 $signed_text = implode(";", $sigmsg);
3266 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3270 * @brief Transmit a message to a target server
3272 * @param array $owner the array of the item owner
3273 * @param array $contact Target of the communication
3274 * @param string $envelope The message that is to be transmitted
3275 * @param bool $public_batch Is it a public post?
3276 * @param bool $queue_run Is the transmission called from the queue?
3277 * @param string $guid message guid
3279 * @return int Result of the transmission
3281 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3285 $enabled = intval(Config::get("system", "diaspora_enabled"));
3290 $logid = random_string(4);
3292 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3294 // We always try to use the data from the fcontact table.
3295 // This is important for transmitting data to Friendica servers.
3296 if (!empty($contact['addr'])) {
3297 $fcontact = self::personByHandle($contact['addr']);
3298 if (!empty($fcontact)) {
3299 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3304 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3308 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3310 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3313 if (!intval(Config::get("system", "diaspora_test"))) {
3314 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3316 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3317 $return_code = $a->get_curl_code();
3319 logger("test_mode");
3324 logger("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3326 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3327 if (!$no_queue && ($contact['contact-type'] != ACCOUNT_TYPE_RELAY)) {
3328 logger("queue message");
3329 // queue message for redelivery
3330 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3333 // The message could not be delivered. We mark the contact as "dead"
3334 Contact::markForArchival($contact);
3335 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3336 // We successfully delivered a message, the contact is alive
3337 Contact::unmarkForArchival($contact);
3340 return $return_code ? $return_code : -1;
3345 * @brief Build the post xml
3347 * @param string $type The message type
3348 * @param array $message The message data
3350 * @return string The post XML
3352 public static function buildPostXml($type, $message)
3354 $data = [$type => $message];
3356 return XML::fromArray($data, $xml);
3360 * @brief Builds and transmit messages
3362 * @param array $owner the array of the item owner
3363 * @param array $contact Target of the communication
3364 * @param string $type The message type
3365 * @param array $message The message data
3366 * @param bool $public_batch Is it a public post?
3367 * @param string $guid message guid
3368 * @param bool $spool Should the transmission be spooled or transmitted?
3370 * @return int Result of the transmission
3372 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3374 $msg = self::buildPostXml($type, $message);
3376 logger('message: '.$msg, LOGGER_DATA);
3377 logger('send guid '.$guid, LOGGER_DEBUG);
3379 // Fallback if the private key wasn't transmitted in the expected field
3380 if ($owner['uprvkey'] == "") {
3381 $owner['uprvkey'] = $owner['prvkey'];
3384 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3387 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3390 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3393 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3395 return $return_code;
3399 * @brief sends a participation (Used to get all further updates)
3401 * @param array $contact Target of the communication
3402 * @param array $item Item array
3404 * @return int The result of the transmission
3406 private static function sendParticipation($contact, $item)
3408 // Don't send notifications for private postings
3409 if ($item['private']) {
3413 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3415 $result = Cache::get($cachekey);
3416 if (!is_null($result)) {
3420 // Fetch some user id to have a valid handle to transmit the participation.
3421 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3422 // If the item belongs to a user, we take this user id.
3423 if ($item['uid'] == 0) {
3424 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3425 $first_user = dba::selectFirst('user', ['uid'], $condition);
3426 $owner = User::getOwnerDataById($first_user['uid']);
3428 $owner = User::getOwnerDataById($item['uid']);
3431 $author = self::myHandle($owner);
3433 $message = ["author" => $author,
3434 "guid" => get_guid(32),
3435 "parent_type" => "Post",
3436 "parent_guid" => $item["guid"]];
3438 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3440 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3441 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3443 return self::buildAndTransmit($owner, $contact, "participation", $message);
3447 * @brief sends an account migration
3449 * @param array $owner the array of the item owner
3450 * @param array $contact Target of the communication
3451 * @param int $uid User ID
3453 * @return int The result of the transmission
3455 public static function sendAccountMigration($owner, $contact, $uid)
3457 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3458 $profile = self::createProfileData($uid);
3460 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3461 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3463 $message = ["author" => $old_handle,
3464 "profile" => $profile,
3465 "signature" => $signature];
3467 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3469 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3473 * @brief Sends a "share" message
3475 * @param array $owner the array of the item owner
3476 * @param array $contact Target of the communication
3478 * @return int The result of the transmission
3480 public static function sendShare($owner, $contact)
3483 * @todo support the different possible combinations of "following" and "sharing"
3484 * Currently, Diaspora only interprets the "sharing" field
3486 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3490 switch ($contact["rel"]) {
3491 case CONTACT_IS_FRIEND:
3494 case CONTACT_IS_SHARING:
3497 case CONTACT_IS_FOLLOWER:
3503 $message = ["author" => self::myHandle($owner),
3504 "recipient" => $contact["addr"],
3505 "following" => "true",
3506 "sharing" => "true"];
3508 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3510 return self::buildAndTransmit($owner, $contact, "contact", $message);
3514 * @brief sends an "unshare"
3516 * @param array $owner the array of the item owner
3517 * @param array $contact Target of the communication
3519 * @return int The result of the transmission
3521 public static function sendUnshare($owner, $contact)
3523 $message = ["author" => self::myHandle($owner),
3524 "recipient" => $contact["addr"],
3525 "following" => "false",
3526 "sharing" => "false"];
3528 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3530 return self::buildAndTransmit($owner, $contact, "contact", $message);
3534 * @brief Checks a message body if it is a reshare
3536 * @param string $body The message body that is to be check
3537 * @param bool $complete Should it be a complete check or a simple check?
3539 * @return array|bool Reshare details or "false" if no reshare
3541 public static function isReshare($body, $complete = true)
3543 $body = trim($body);
3545 // Skip if it isn't a pure repeated messages
3546 // Does it start with a share?
3547 if ((strpos($body, "[share") > 0) && $complete) {
3551 // Does it end with a share?
3552 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3556 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3557 // Skip if there is no shared message in there
3558 if ($body == $attributes) {
3562 // If we don't do the complete check we quit here
3565 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3566 if ($matches[1] != "") {
3567 $guid = $matches[1];
3570 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3571 if ($matches[1] != "") {
3572 $guid = $matches[1];
3575 if (($guid != "") && $complete) {
3576 $condition = ['guid' => $guid, 'network' => [NETWORK_DFRN, NETWORK_DIASPORA]];
3577 $item = dba::selectFirst('item', ['contact-id'], $condition);
3578 if (DBM::is_result($item)) {
3580 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3581 $ret["root_guid"] = $guid;
3587 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3588 if ($matches[1] != "") {
3589 $profile = $matches[1];
3592 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3593 if ($matches[1] != "") {
3594 $profile = $matches[1];
3599 if ($profile != "") {
3600 if (Contact::getIdForURL($profile)) {
3601 $author = Contact::getDetailsByURL($profile);
3602 $ret["root_handle"] = $author['addr'];
3606 if (!empty($guid)) {
3607 $ret["root_guid"] = $guid;
3610 if (empty($ret) && !$complete) {
3618 * @brief Create an event array
3620 * @param integer $event_id The id of the event
3622 * @return array with event data
3624 private static function buildEvent($event_id)
3626 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3627 if (!DBM::is_result($r)) {
3635 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3636 if (!DBM::is_result($r)) {
3642 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3643 if (!DBM::is_result($r)) {
3649 $eventdata['author'] = self::myHandle($owner);
3651 if ($event['guid']) {
3652 $eventdata['guid'] = $event['guid'];
3655 $mask = DateTimeFormat::ATOM;
3657 /// @todo - establish "all day" events in Friendica
3658 $eventdata["all_day"] = "false";
3660 if (!$event['adjust']) {
3661 $eventdata['timezone'] = $user['timezone'];
3663 if ($eventdata['timezone'] == "") {
3664 $eventdata['timezone'] = 'UTC';
3668 if ($event['start']) {
3669 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3671 if ($event['finish'] && !$event['nofinish']) {
3672 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3674 if ($event['summary']) {
3675 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3677 if ($event['desc']) {
3678 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3680 if ($event['location']) {
3681 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3682 $coord = Map::getCoordinates($event['location']);
3685 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3686 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3687 $location["lat"] = $coord['lat'];
3688 $location["lng"] = $coord['lon'];
3690 $location["lat"] = 0;
3691 $location["lng"] = 0;
3693 $eventdata['location'] = $location;
3700 * @brief Create a post (status message or reshare)
3702 * @param array $item The item that will be exported
3703 * @param array $owner the array of the item owner
3706 * 'type' -> Message type ("status_message" or "reshare")
3707 * 'message' -> Array of XML elements of the status
3709 public static function buildStatus($item, $owner)
3711 $cachekey = "diaspora:buildStatus:".$item['guid'];
3713 $result = Cache::get($cachekey);
3714 if (!is_null($result)) {
3718 $myaddr = self::myHandle($owner);
3720 $public = (($item["private"]) ? "false" : "true");
3722 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3724 // Detect a share element and do a reshare
3725 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3726 $message = ["author" => $myaddr,
3727 "guid" => $item["guid"],
3728 "created_at" => $created,
3729 "root_author" => $ret["root_handle"],
3730 "root_guid" => $ret["root_guid"],
3731 "provider_display_name" => $item["app"],
3732 "public" => $public];
3736 $title = $item["title"];
3737 $body = $item["body"];
3739 if ($item['author-link'] != $item['owner-link']) {
3740 require_once 'mod/share.php';
3741 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3742 "", $item['created'], $item['plink']) . $body . '[/share]';
3745 // convert to markdown
3746 $body = html_entity_decode(BBCode::toMarkdown($body));
3749 if (strlen($title)) {
3750 $body = "## ".html_entity_decode($title)."\n\n".$body;
3753 if ($item["attach"]) {
3754 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3756 $body .= "\n".L10n::t("Attachments:")."\n";
3757 foreach ($matches as $mtch) {
3758 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3765 if ($item["location"] != "")
3766 $location["address"] = $item["location"];
3768 if ($item["coord"] != "") {
3769 $coord = explode(" ", $item["coord"]);
3770 $location["lat"] = $coord[0];
3771 $location["lng"] = $coord[1];
3774 $message = ["author" => $myaddr,
3775 "guid" => $item["guid"],
3776 "created_at" => $created,
3777 "public" => $public,
3779 "provider_display_name" => $item["app"],
3780 "location" => $location];
3782 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3783 if (!isset($location["lat"]) || !isset($location["lng"])) {
3784 unset($message["location"]);
3787 if ($item['event-id'] > 0) {
3788 $event = self::buildEvent($item['event-id']);
3789 if (count($event)) {
3790 $message['event'] = $event;
3792 if (!empty($event['location']['address']) &&
3793 !empty($event['location']['lat']) &&
3794 !empty($event['location']['lng'])) {
3795 $message['location'] = $event['location'];
3798 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3799 // $message['text'] = '';
3803 $type = "status_message";
3806 $msg = ["type" => $type, "message" => $message];
3808 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3814 * @brief Sends a post
3816 * @param array $item The item that will be exported
3817 * @param array $owner the array of the item owner
3818 * @param array $contact Target of the communication
3819 * @param bool $public_batch Is it a public post?
3821 * @return int The result of the transmission
3823 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3825 $status = self::buildStatus($item, $owner);
3827 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3831 * @brief Creates a "like" object
3833 * @param array $item The item that will be exported
3834 * @param array $owner the array of the item owner
3836 * @return array The data for a "like"
3838 private static function constructLike($item, $owner)
3841 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3842 dbesc($item["thr-parent"])
3844 if (!DBM::is_result($p)) {
3850 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3852 if ($item['verb'] === ACTIVITY_LIKE) {
3854 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3855 $positive = "false";
3858 return(["author" => self::myHandle($owner),
3859 "guid" => $item["guid"],
3860 "parent_guid" => $parent["guid"],
3861 "parent_type" => $target_type,
3862 "positive" => $positive,
3863 "author_signature" => ""]);
3867 * @brief Creates an "EventParticipation" object
3869 * @param array $item The item that will be exported
3870 * @param array $owner the array of the item owner
3872 * @return array The data for an "EventParticipation"
3874 private static function constructAttend($item, $owner)
3877 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3878 dbesc($item["thr-parent"])
3880 if (!DBM::is_result($p)) {
3886 switch ($item['verb']) {
3887 case ACTIVITY_ATTEND:
3888 $attend_answer = 'accepted';
3890 case ACTIVITY_ATTENDNO:
3891 $attend_answer = 'declined';
3893 case ACTIVITY_ATTENDMAYBE:
3894 $attend_answer = 'tentative';
3897 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3901 return(["author" => self::myHandle($owner),
3902 "guid" => $item["guid"],
3903 "parent_guid" => $parent["guid"],
3904 "status" => $attend_answer,
3905 "author_signature" => ""]);
3909 * @brief Creates the object for a comment
3911 * @param array $item The item that will be exported
3912 * @param array $owner the array of the item owner
3914 * @return array The data for a comment
3916 private static function constructComment($item, $owner)
3918 $cachekey = "diaspora:constructComment:".$item['guid'];
3920 $result = Cache::get($cachekey);
3921 if (!is_null($result)) {
3926 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3927 intval($item["parent"]),
3928 intval($item["parent"])
3931 if (!DBM::is_result($p)) {
3937 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3938 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3940 $comment = ["author" => self::myHandle($owner),
3941 "guid" => $item["guid"],
3942 "created_at" => $created,
3943 "parent_guid" => $parent["guid"],
3945 "author_signature" => ""];
3947 // Send the thread parent guid only if it is a threaded comment
3948 if ($item['thr-parent'] != $item['parent-uri']) {
3949 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3952 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3958 * @brief Send a like or a comment
3960 * @param array $item The item that will be exported
3961 * @param array $owner the array of the item owner
3962 * @param array $contact Target of the communication
3963 * @param bool $public_batch Is it a public post?
3965 * @return int The result of the transmission
3967 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3969 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3970 $message = self::constructAttend($item, $owner);
3971 $type = "event_participation";
3972 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3973 $message = self::constructLike($item, $owner);
3976 $message = self::constructComment($item, $owner);
3984 $message["author_signature"] = self::signature($owner, $message);
3986 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3990 * @brief Creates a message from a signature record entry
3992 * @param array $item The item that will be exported
3993 * @param array $signature The entry of the "sign" record
3995 * @return string The message
3997 private static function messageFromSignature($item, $signature)
3999 // Split the signed text
4000 $signed_parts = explode(";", $signature['signed_text']);
4002 if ($item["deleted"]) {
4003 $message = ["author" => $signature['signer'],
4004 "target_guid" => $signed_parts[0],
4005 "target_type" => $signed_parts[1]];
4006 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4007 $message = ["author" => $signed_parts[4],
4008 "guid" => $signed_parts[1],
4009 "parent_guid" => $signed_parts[3],
4010 "parent_type" => $signed_parts[2],
4011 "positive" => $signed_parts[0],
4012 "author_signature" => $signature['signature'],
4013 "parent_author_signature" => ""];
4015 // Remove the comment guid
4016 $guid = array_shift($signed_parts);
4018 // Remove the parent guid
4019 $parent_guid = array_shift($signed_parts);
4021 // Remove the handle
4022 $handle = array_pop($signed_parts);
4024 // Glue the parts together
4025 $text = implode(";", $signed_parts);
4027 $message = ["author" => $handle,
4029 "parent_guid" => $parent_guid,
4030 "text" => implode(";", $signed_parts),
4031 "author_signature" => $signature['signature'],
4032 "parent_author_signature" => ""];
4038 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
4040 * @param array $item The item that will be exported
4041 * @param array $owner the array of the item owner
4042 * @param array $contact Target of the communication
4043 * @param bool $public_batch Is it a public post?
4045 * @return int The result of the transmission
4047 public static function sendRelay($item, $owner, $contact, $public_batch = false)
4049 if ($item["deleted"]) {
4050 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
4051 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4057 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4059 // fetch the original signature
4062 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
4067 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4073 // Old way - is used by the internal Friendica functions
4074 /// @todo Change all signatur storing functions to the new format
4075 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
4076 $message = self::messageFromSignature($item, $signature);
4078 $msg = json_decode($signature['signed_text'], true);
4081 if (is_array($msg)) {
4082 foreach ($msg as $field => $data) {
4083 if (!$item["deleted"]) {
4084 if ($field == "diaspora_handle") {
4087 if ($field == "target_type") {
4088 $field = "parent_type";
4092 $message[$field] = $data;
4095 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4099 $message["parent_author_signature"] = self::signature($owner, $message);
4101 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4103 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4107 * @brief Sends a retraction (deletion) of a message, like or comment
4109 * @param array $item The item that will be exported
4110 * @param array $owner the array of the item owner
4111 * @param array $contact Target of the communication
4112 * @param bool $public_batch Is it a public post?
4113 * @param bool $relay Is the retraction transmitted from a relay?
4115 * @return int The result of the transmission
4117 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4119 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4121 $msg_type = "retraction";
4123 if ($item['id'] == $item['parent']) {
4124 $target_type = "Post";
4125 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4126 $target_type = "Like";
4128 $target_type = "Comment";
4131 $message = ["author" => $itemaddr,
4132 "target_guid" => $item['guid'],
4133 "target_type" => $target_type];
4135 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4137 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4141 * @brief Sends a mail
4143 * @param array $item The item that will be exported
4144 * @param array $owner The owner
4145 * @param array $contact Target of the communication
4147 * @return int The result of the transmission
4149 public static function sendMail($item, $owner, $contact)
4151 $myaddr = self::myHandle($owner);
4154 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4155 intval($item["convid"]),
4156 intval($item["uid"])
4159 if (!DBM::is_result($r)) {
4160 logger("conversation not found.");
4166 "author" => $cnv["creator"],
4167 "guid" => $cnv["guid"],
4168 "subject" => $cnv["subject"],
4169 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4170 "participants" => $cnv["recips"]
4173 $body = BBCode::toMarkdown($item["body"]);
4174 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4177 "author" => $myaddr,
4178 "guid" => $item["guid"],
4179 "conversation_guid" => $cnv["guid"],
4181 "created_at" => $created,
4184 if ($item["reply"]) {
4189 "author" => $cnv["creator"],
4190 "guid" => $cnv["guid"],
4191 "subject" => $cnv["subject"],
4192 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4193 "participants" => $cnv["recips"],
4196 $type = "conversation";
4199 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4203 * @brief Split a name into first name and last name
4205 * @param string $name The name
4207 * @return array The array with "first" and "last"
4209 public static function splitName($name) {
4210 $name = trim($name);
4212 // Is the name longer than 64 characters? Then cut the rest of it.
4213 if (strlen($name) > 64) {
4214 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4215 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4217 $name = substr($name, 0, 64);
4221 // Take the first word as first name
4222 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4223 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4224 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4225 return ['first' => $first, 'last' => $last];
4228 // Take the last word as last name
4229 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4230 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4232 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4233 return ['first' => $first, 'last' => $last];
4236 // Take the first 32 characters if there is no space in the first 32 characters
4237 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4238 $first = substr($name, 0, 32);
4239 $last = substr($name, 32);
4240 return ['first' => $first, 'last' => $last];
4243 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4244 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4246 // Check if the last name is longer than 32 characters
4247 if (strlen($last) > 32) {
4248 if (strpos($last, ' ') <= 32) {
4249 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4251 $last = substr($last, 0, 32);
4255 return ['first' => $first, 'last' => $last];
4259 * @brief Create profile data
4261 * @param int $uid The user id
4263 * @return array The profile data
4265 private static function createProfileData($uid)
4268 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4270 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4271 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4272 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4281 $handle = $profile["addr"];
4283 $split_name = self::splitName($profile['name']);
4284 $first = $split_name['first'];
4285 $last = $split_name['last'];
4287 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4288 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4289 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4290 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4296 if ($searchable === 'true') {
4299 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4300 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4304 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4307 $about = $profile['about'];
4308 $about = strip_tags(BBCode::convert($about));
4310 $location = Profile::formatLocation($profile);
4312 if ($profile['pub_keywords']) {
4313 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4314 $kw = str_replace(' ', ' ', $kw);
4315 $arr = explode(' ', $profile['pub_keywords']);
4317 for ($x = 0; $x < 5; $x ++) {
4318 if (trim($arr[$x])) {
4319 $tags .= '#'. trim($arr[$x]) .' ';
4324 $tags = trim($tags);
4327 return ["author" => $handle,
4328 "first_name" => $first,
4329 "last_name" => $last,
4330 "image_url" => $large,
4331 "image_url_medium" => $medium,
4332 "image_url_small" => $small,
4334 "gender" => $profile['gender'],
4336 "location" => $location,
4337 "searchable" => $searchable,
4339 "tag_string" => $tags];
4343 * @brief Sends profile data
4345 * @param int $uid The user id
4346 * @param bool $recips optional, default false
4349 public static function sendProfile($uid, $recips = false)
4355 $owner = User::getOwnerDataById($uid);
4362 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4363 AND `uid` = %d AND `rel` != %d",
4364 dbesc(NETWORK_DIASPORA),
4366 intval(CONTACT_IS_SHARING)
4374 $message = self::createProfileData($uid);
4376 foreach ($recips as $recip) {
4377 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4378 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4383 * @brief Stores the signature for likes that are created on our system
4385 * @param array $contact The contact array of the "like"
4386 * @param int $post_id The post id of the "like"
4388 * @return bool Success
4390 public static function storeLikeSignature($contact, $post_id)
4392 // Is the contact the owner? Then fetch the private key
4393 if (!$contact['self'] || ($contact['uid'] == 0)) {
4394 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4398 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4399 if (!DBM::is_result($r)) {
4403 $contact["uprvkey"] = $r[0]['prvkey'];
4405 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4406 if (!DBM::is_result($r)) {
4410 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4414 $message = self::constructLike($r[0], $contact);
4415 if ($message === false) {
4419 $message["author_signature"] = self::signature($contact, $message);
4422 * Now store the signature more flexible to dynamically support new fields.
4423 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4425 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4427 logger('Stored diaspora like signature');
4432 * @brief Stores the signature for comments that are created on our system
4434 * @param array $item The item array of the comment
4435 * @param array $contact The contact array of the item owner
4436 * @param string $uprvkey The private key of the sender
4437 * @param int $message_id The message id of the comment
4439 * @return bool Success
4441 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4443 if ($uprvkey == "") {
4444 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4448 $contact["uprvkey"] = $uprvkey;
4450 $message = self::constructComment($item, $contact);
4451 if ($message === false) {
4455 $message["author_signature"] = self::signature($contact, $message);
4458 * Now store the signature more flexible to dynamically support new fields.
4459 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4461 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4463 logger('Stored diaspora comment signature');