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.
10 namespace Friendica\Protocol;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Core\Cache;
14 use Friendica\Core\Config;
15 use Friendica\Core\L10n;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\System;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Model\Contact;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Item;
24 use Friendica\Model\Profile;
25 use Friendica\Model\Queue;
26 use Friendica\Model\User;
27 use Friendica\Network\Probe;
28 use Friendica\Util\Crypto;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Network;
31 use Friendica\Util\XML;
35 require_once 'include/dba.php';
36 require_once 'include/items.php';
37 require_once 'include/bb2diaspora.php';
40 * @brief This class contain functions to create and send Diaspora XML files
46 * @brief Return a list of relay servers
48 * This is an experimental Diaspora feature.
50 * @return array of relay servers
52 public static function relayList()
54 $serverdata = Config::get("system", "relay_server");
55 if ($serverdata == "") {
61 $servers = explode(",", $serverdata);
63 foreach ($servers as $server) {
64 $server = trim($server);
65 $addr = "relay@".str_replace("http://", "", normalise_link($server));
66 $batch = $server."/receive/public";
69 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
72 dbesc(normalise_link($server))
77 "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
78 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
79 DateTimeFormat::utcNow(),
83 dbesc(normalise_link($server)),
85 dbesc(NETWORK_DIASPORA),
86 intval(CONTACT_IS_FOLLOWER),
87 dbesc(DateTimeFormat::utcNow()),
88 dbesc(DateTimeFormat::utcNow()),
89 dbesc(DateTimeFormat::utcNow())
92 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
94 $relay[] = $relais[0];
97 $relay[] = $relais[0];
105 * @brief Return a list of participating contacts for a thread
107 * This is used for the participation feature.
108 * One of the parameters is a contact array.
109 * This is done to avoid duplicates.
111 * @param integer $thread The id of the thread
112 * @param array $contacts The previously fetched contacts
114 * @return array of relay servers
116 public static function participantsForThread($thread, $contacts)
118 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
119 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
120 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
121 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
122 WHERE `participation`.`iid` = ?", $thread);
124 while ($contact = dba::fetch($r)) {
125 if (!empty($contact['fnetwork'])) {
126 $contact['network'] = $contact['fnetwork'];
128 unset($contact['fnetwork']);
130 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
131 $contact['batch'] = $contact['fbatch'];
133 unset($contact['fbatch']);
136 foreach ($contacts as $entry) {
137 if ($entry['batch'] == $contact['batch']) {
143 $contacts[] = $contact;
152 * @brief repairs a signature that was double encoded
154 * The function is unused at the moment. It was copied from the old implementation.
156 * @param string $signature The signature
157 * @param string $handle The handle of the signature owner
158 * @param integer $level This value is only set inside this function to avoid endless loops
160 * @return string the repaired signature
162 private static function repairSignature($signature, $handle = "", $level = 1)
164 if ($signature == "") {
168 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
169 $signature = base64_decode($signature);
170 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
172 // Do a recursive call to be able to fix even multiple levels
174 $signature = self::repairSignature($signature, $handle, ++$level);
182 * @brief verify the envelope and return the verified data
184 * @param string $envelope The magic envelope
186 * @return string verified data
188 private static function verifyMagicEnvelope($envelope)
190 $basedom = XML::parseString($envelope);
192 if (!is_object($basedom)) {
193 logger("Envelope is no XML file");
197 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
199 if (sizeof($children) == 0) {
200 logger("XML has no children");
206 $data = base64url_decode($children->data);
207 $type = $children->data->attributes()->type[0];
209 $encoding = $children->encoding;
211 $alg = $children->alg;
213 $sig = base64url_decode($children->sig);
214 $key_id = $children->sig->attributes()->key_id[0];
216 $handle = base64url_decode($key_id);
219 $b64url_data = base64url_encode($data);
220 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
222 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
224 $key = self::key($handle);
226 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
228 logger('Message did not verify. Discarding.');
236 * @brief encrypts data via AES
238 * @param string $key The AES key
239 * @param string $iv The IV (is used for CBC encoding)
240 * @param string $data The data that is to be encrypted
242 * @return string encrypted data
244 private static function aesEncrypt($key, $iv, $data)
246 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
250 * @brief decrypts data via AES
252 * @param string $key The AES key
253 * @param string $iv The IV (is used for CBC encoding)
254 * @param string $encrypted The encrypted data
256 * @return string decrypted data
258 private static function aesDecrypt($key, $iv, $encrypted)
260 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
264 * @brief: Decodes incoming Diaspora message in the new format
266 * @param array $importer Array of the importer user
267 * @param string $raw raw post message
270 * 'message' -> decoded Diaspora XML message
271 * 'author' -> author diaspora handle
272 * 'key' -> author public key (converted to pkcs#8)
274 public static function decodeRaw($importer, $raw)
276 $data = json_decode($raw);
278 // Is it a private post? Then decrypt the outer Salmon
279 if (is_object($data)) {
280 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
281 $ciphertext = base64_decode($data->encrypted_magic_envelope);
283 $outer_key_bundle = '';
284 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
285 $j_outer_key_bundle = json_decode($outer_key_bundle);
287 if (!is_object($j_outer_key_bundle)) {
288 logger('Outer Salmon did not verify. Discarding.');
289 System::httpExit(400);
292 $outer_iv = base64_decode($j_outer_key_bundle->iv);
293 $outer_key = base64_decode($j_outer_key_bundle->key);
295 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
300 $basedom = XML::parseString($xml);
302 if (!is_object($basedom)) {
303 logger('Received data does not seem to be an XML. Discarding. '.$xml);
304 System::httpExit(400);
307 $base = $basedom->children(NAMESPACE_SALMON_ME);
309 // Not sure if this cleaning is needed
310 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
312 // Build the signed data
313 $type = $base->data[0]->attributes()->type[0];
314 $encoding = $base->encoding;
316 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
318 // This is the signature
319 $signature = base64url_decode($base->sig);
321 // Get the senders' public key
322 $key_id = $base->sig[0]->attributes()->key_id[0];
323 $author_addr = base64_decode($key_id);
324 $key = self::key($author_addr);
326 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
328 logger('Message did not verify. Discarding.');
329 System::httpExit(400);
332 return ['message' => (string)base64url_decode($base->data),
333 'author' => unxmlify($author_addr),
334 'key' => (string)$key];
338 * @brief: Decodes incoming Diaspora message in the deprecated format
340 * @param array $importer Array of the importer user
341 * @param string $xml urldecoded Diaspora salmon
344 * 'message' -> decoded Diaspora XML message
345 * 'author' -> author diaspora handle
346 * 'key' -> author public key (converted to pkcs#8)
348 public static function decode($importer, $xml)
351 $basedom = XML::parseString($xml);
353 if (!is_object($basedom)) {
354 logger("XML is not parseable.");
357 $children = $basedom->children('https://joindiaspora.com/protocol');
359 $inner_aes_key = null;
362 if ($children->header) {
364 $author_link = str_replace('acct:', '', $children->header->author_id);
366 // This happens with posts from a relais
368 logger("This is no private post in the old format", LOGGER_DEBUG);
372 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
374 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
375 $ciphertext = base64_decode($encrypted_header->ciphertext);
377 $outer_key_bundle = '';
378 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
380 $j_outer_key_bundle = json_decode($outer_key_bundle);
382 $outer_iv = base64_decode($j_outer_key_bundle->iv);
383 $outer_key = base64_decode($j_outer_key_bundle->key);
385 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
387 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
388 $idom = XML::parseString($decrypted);
390 $inner_iv = base64_decode($idom->iv);
391 $inner_aes_key = base64_decode($idom->aes_key);
393 $author_link = str_replace('acct:', '', $idom->author_id);
396 $dom = $basedom->children(NAMESPACE_SALMON_ME);
398 // figure out where in the DOM tree our data is hiding
401 if ($dom->provenance->data) {
402 $base = $dom->provenance;
403 } elseif ($dom->env->data) {
405 } elseif ($dom->data) {
410 logger('unable to locate salmon data in xml');
411 System::httpExit(400);
415 // Stash the signature away for now. We have to find their key or it won't be good for anything.
416 $signature = base64url_decode($base->sig);
420 // strip whitespace so our data element will return to one big base64 blob
421 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
424 // stash away some other stuff for later
426 $type = $base->data[0]->attributes()->type[0];
427 $keyhash = $base->sig[0]->attributes()->keyhash[0];
428 $encoding = $base->encoding;
432 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
436 $data = base64url_decode($data);
440 $inner_decrypted = $data;
442 // Decode the encrypted blob
443 $inner_encrypted = base64_decode($data);
444 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
448 logger('Could not retrieve author URI.');
449 System::httpExit(400);
451 // Once we have the author URI, go to the web and try to find their public key
452 // (first this will look it up locally if it is in the fcontact cache)
453 // This will also convert diaspora public key from pkcs#1 to pkcs#8
455 logger('Fetching key for '.$author_link);
456 $key = self::key($author_link);
459 logger('Could not retrieve author key.');
460 System::httpExit(400);
463 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
466 logger('Message did not verify. Discarding.');
467 System::httpExit(400);
470 logger('Message verified.');
472 return ['message' => (string)$inner_decrypted,
473 'author' => unxmlify($author_link),
474 'key' => (string)$key];
479 * @brief Dispatches public messages and find the fitting receivers
481 * @param array $msg The post that will be dispatched
483 * @return int The message id of the generated message, "true" or "false" if there was an error
485 public static function dispatchPublic($msg)
487 $enabled = intval(Config::get("system", "diaspora_enabled"));
489 logger("diaspora is disabled");
493 if (!($postdata = self::validPosting($msg))) {
494 logger("Invalid posting");
498 $fields = $postdata['fields'];
500 // Is it a an action (comment, like, ...) for our own post?
501 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
502 $guid = notags(unxmlify($fields->parent_guid));
503 $importer = self::importerForGuid($guid);
504 if (is_array($importer)) {
505 logger("delivering to origin: ".$importer["name"]);
506 $message_id = self::dispatch($importer, $msg, $fields);
511 // Process item retractions. This has to be done separated from the other stuff,
512 // since retractions for comments could come even from non followers.
513 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
514 $target = notags(unxmlify($fields->target_type));
515 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
516 logger('processing retraction for '.$target, LOGGER_DEBUG);
517 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
518 $message_id = self::dispatch($importer, $msg, $fields);
523 // Now distribute it to the followers
525 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
526 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
527 AND NOT `account_expired` AND NOT `account_removed`",
528 dbesc(NETWORK_DIASPORA),
529 dbesc($msg["author"])
532 if (DBM::is_result($r)) {
533 foreach ($r as $rr) {
534 logger("delivering to: ".$rr["username"]);
535 self::dispatch($rr, $msg, $fields);
537 } elseif (!Config::get('system', 'relay_subscribe', false)) {
538 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
540 // Use a dummy importer to import the data for the public copy
541 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
542 $message_id = self::dispatch($importer, $msg, $fields);
549 * @brief Dispatches the different message types to the different functions
551 * @param array $importer Array of the importer user
552 * @param array $msg The post that will be dispatched
553 * @param object $fields SimpleXML object that contains the message
555 * @return int The message id of the generated message, "true" or "false" if there was an error
557 public static function dispatch($importer, $msg, $fields = null)
559 // The sender is the handle of the contact that sent the message.
560 // This will often be different with relayed messages (for example "like" and "comment")
561 $sender = $msg["author"];
563 // This is only needed for private postings since this is already done for public ones before
564 if (is_null($fields)) {
565 if (!($postdata = self::validPosting($msg))) {
566 logger("Invalid posting");
569 $fields = $postdata['fields'];
572 $type = $fields->getName();
574 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
577 case "account_migration":
578 return self::receiveAccountMigration($importer, $fields);
580 case "account_deletion":
581 return self::receiveAccountDeletion($importer, $fields);
584 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
587 return self::receiveContactRequest($importer, $fields);
590 return self::receiveConversation($importer, $msg, $fields);
593 return self::receiveLike($importer, $sender, $fields);
596 return self::receiveMessage($importer, $fields);
598 case "participation":
599 return self::receiveParticipation($importer, $fields);
601 case "photo": // Not implemented
602 return self::receivePhoto($importer, $fields);
604 case "poll_participation": // Not implemented
605 return self::receivePollParticipation($importer, $fields);
608 return self::receiveProfile($importer, $fields);
611 return self::receiveReshare($importer, $fields, $msg["message"]);
614 return self::receiveRetraction($importer, $sender, $fields);
616 case "status_message":
617 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
620 logger("Unknown message type ".$type);
628 * @brief Checks if a posting is valid and fetches the data fields.
630 * This function does not only check the signature.
631 * It also does the conversion between the old and the new diaspora format.
633 * @param array $msg Array with the XML, the sender handle and the sender signature
635 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
637 private static function validPosting($msg)
639 $data = XML::parseString($msg["message"]);
641 if (!is_object($data)) {
642 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
646 // Is this the new or the old version?
647 if ($data->getName() == "XML") {
649 foreach ($data->post->children() as $child) {
657 $type = $element->getName();
660 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
662 // All retractions are handled identically from now on.
663 // In the new version there will only be "retraction".
664 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
665 $type = "retraction";
667 if ($type == "request") {
671 $fields = new SimpleXMLElement("<".$type."/>");
674 $author_signature = null;
675 $parent_author_signature = null;
677 foreach ($element->children() as $fieldname => $entry) {
679 // Translation for the old XML structure
680 if ($fieldname == "diaspora_handle") {
681 $fieldname = "author";
683 if ($fieldname == "participant_handles") {
684 $fieldname = "participants";
686 if (in_array($type, ["like", "participation"])) {
687 if ($fieldname == "target_type") {
688 $fieldname = "parent_type";
691 if ($fieldname == "sender_handle") {
692 $fieldname = "author";
694 if ($fieldname == "recipient_handle") {
695 $fieldname = "recipient";
697 if ($fieldname == "root_diaspora_id") {
698 $fieldname = "root_author";
700 if ($type == "status_message") {
701 if ($fieldname == "raw_message") {
705 if ($type == "retraction") {
706 if ($fieldname == "post_guid") {
707 $fieldname = "target_guid";
709 if ($fieldname == "type") {
710 $fieldname = "target_type";
715 if (($fieldname == "author_signature") && ($entry != "")) {
716 $author_signature = base64_decode($entry);
717 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
718 $parent_author_signature = base64_decode($entry);
719 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
720 if ($signed_data != "") {
724 $signed_data .= $entry;
726 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
727 || ($orig_type == "relayable_retraction")
729 XML::copy($entry, $fields, $fieldname);
733 // This is something that shouldn't happen at all.
734 if (in_array($type, ["status_message", "reshare", "profile"])) {
735 if ($msg["author"] != $fields->author) {
736 logger("Message handle is not the same as envelope sender. Quitting this message.");
741 // Only some message types have signatures. So we quit here for the other types.
742 if (!in_array($type, ["comment", "like"])) {
743 return ["fields" => $fields, "relayed" => false];
745 // No author_signature? This is a must, so we quit.
746 if (!isset($author_signature)) {
747 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
751 if (isset($parent_author_signature)) {
754 $key = self::key($msg["author"]);
756 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
757 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);
764 $key = self::key($fields->author);
766 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
767 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
770 return ["fields" => $fields, "relayed" => $relayed];
775 * @brief Fetches the public key for a given handle
777 * @param string $handle The handle
779 * @return string The public key
781 private static function key($handle)
783 $handle = strval($handle);
785 logger("Fetching diaspora key for: ".$handle);
787 $r = self::personByHandle($handle);
796 * @brief Fetches data for a given handle
798 * @param string $handle The handle
800 * @return array the queried data
802 public static function personByHandle($handle)
806 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
807 if (DBM::is_result($person)) {
808 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
810 // update record occasionally so it doesn't get stale
811 $d = strtotime($person["updated"]." +00:00");
812 if ($d < strtotime("now - 14 days")) {
816 if ($person["guid"] == "") {
821 if (!DBM::is_result($person) || $update) {
822 logger("create or refresh", LOGGER_DEBUG);
823 $r = Probe::uri($handle, NETWORK_DIASPORA);
825 // Note that Friendica contacts will return a "Diaspora person"
826 // if Diaspora connectivity is enabled on their server
827 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
828 self::addFContact($r, $update);
830 // Fetch the updated or added contact
831 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
832 if (!DBM::is_result($person)) {
842 * @brief Updates the fcontact table
844 * @param array $arr The fcontact data
845 * @param bool $update Update or insert?
847 * @return string The id of the fcontact entry
849 private static function addFContact($arr, $update = false)
853 "UPDATE `fcontact` SET
867 WHERE `url` = '%s' AND `network` = '%s'",
869 dbesc($arr["photo"]),
870 dbesc($arr["request"]),
872 dbesc(strtolower($arr["addr"])),
874 dbesc($arr["batch"]),
875 dbesc($arr["notify"]),
877 dbesc($arr["confirm"]),
878 dbesc($arr["alias"]),
879 dbesc($arr["pubkey"]),
880 dbesc(DateTimeFormat::utcNow()),
882 dbesc($arr["network"])
886 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
887 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
888 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
891 dbesc($arr["photo"]),
892 dbesc($arr["request"]),
896 dbesc($arr["batch"]),
897 dbesc($arr["notify"]),
899 dbesc($arr["confirm"]),
900 dbesc($arr["network"]),
901 dbesc($arr["alias"]),
902 dbesc($arr["pubkey"]),
903 dbesc(DateTimeFormat::utcNow())
911 * @brief get a handle (user@domain.tld) from a given contact id
913 * @param int $contact_id The id in the contact table
914 * @param int $pcontact_id The id in the contact table (Used for the public contact)
916 * @return string the handle
918 private static function handleFromContact($contact_id, $pcontact_id = 0)
922 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
924 if ($pcontact_id != 0) {
926 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
930 if (DBM::is_result($r)) {
931 return strtolower($r[0]["addr"]);
936 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
940 if (DBM::is_result($r)) {
943 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
945 if ($contact['addr'] != "") {
946 $handle = $contact['addr'];
948 $baseurl_start = strpos($contact['url'], '://') + 3;
949 // allows installations in a subdirectory--not sure how Diaspora will handle
950 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
951 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
952 $handle = $contact['nick'].'@'.$baseurl;
956 return strtolower($handle);
960 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
963 * @param mixed $fcontact_guid Hexadecimal string guid
965 * @return string the contact url or null
967 public static function urlFromContactGuid($fcontact_guid)
969 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
972 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
973 dbesc(NETWORK_DIASPORA),
974 dbesc($fcontact_guid)
977 if (DBM::is_result($r)) {
985 * @brief Get a contact id for a given handle
987 * @todo Move to Friendica\Model\Contact
989 * @param int $uid The user id
990 * @param string $handle The handle in the format user@domain.tld
992 * @return int Contact id
994 private static function contactByHandle($uid, $handle)
996 // First do a direct search on the contact table
998 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1003 if (DBM::is_result($r)) {
1007 * We haven't found it?
1008 * We use another function for it that will possibly create a contact entry.
1010 $cid = Contact::getIdForURL($handle, $uid);
1013 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1014 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1016 if (DBM::is_result($r)) {
1022 $handle_parts = explode("@", $handle);
1023 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1025 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1026 dbesc(NETWORK_DFRN),
1030 if (DBM::is_result($r)) {
1034 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1039 * @brief Check if posting is allowed for this contact
1041 * @param array $importer Array of the importer user
1042 * @param array $contact The contact that is checked
1043 * @param bool $is_comment Is the check for a comment?
1045 * @return bool is the contact allowed to post?
1047 private static function postAllow($importer, $contact, $is_comment = false)
1050 * Perhaps we were already sharing with this person. Now they're sharing with us.
1051 * That makes us friends.
1052 * Normally this should have handled by getting a request - but this could get lost
1054 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1055 // It is not removed by now. Possibly the code is needed?
1056 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1059 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1060 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1063 // $contact["rel"] = CONTACT_IS_FRIEND;
1064 // logger("defining user ".$contact["nick"]." as friend");
1067 // We don't seem to like that person
1068 if ($contact["blocked"] || $contact["readonly"]) {
1069 // Maybe blocked, don't accept.
1071 // We are following this person?
1072 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1073 // Yes, then it is fine.
1075 // Is it a post to a community?
1076 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1079 // Is the message a global user or a comment?
1080 } elseif (($importer["uid"] == 0) || $is_comment) {
1081 // Messages for the global users and comments are always accepted
1089 * @brief Fetches the contact id for a handle and checks if posting is allowed
1091 * @param array $importer Array of the importer user
1092 * @param string $handle The checked handle in the format user@domain.tld
1093 * @param bool $is_comment Is the check for a comment?
1095 * @return array The contact data
1097 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1099 $contact = self::contactByHandle($importer["uid"], $handle);
1101 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1102 // If a contact isn't found, we accept it anyway if it is a comment
1110 if (!self::postAllow($importer, $contact, $is_comment)) {
1111 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1118 * @brief Does the message already exists on the system?
1120 * @param int $uid The user id
1121 * @param string $guid The guid of the message
1123 * @return int|bool message id if the message already was stored into the system - or false.
1125 private static function messageExists($uid, $guid)
1128 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1133 if (DBM::is_result($r)) {
1134 logger("message ".$guid." already exists for user ".$uid);
1142 * @brief Checks for links to posts in a message
1144 * @param array $item The item array
1147 private static function fetchGuid($item)
1149 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1150 preg_replace_callback(
1152 function ($match) use ($item) {
1153 self::fetchGuidSub($match, $item);
1158 preg_replace_callback(
1159 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1160 function ($match) use ($item) {
1161 self::fetchGuidSub($match, $item);
1168 * @brief Checks for relative /people/* links in an item body to match local
1169 * contacts or prepends the remote host taken from the author link.
1171 * @param string $body The item body to replace links from
1172 * @param string $author_link The author link for missing local contact fallback
1174 * @return string the replaced string
1176 public static function replacePeopleGuid($body, $author_link)
1178 $return = preg_replace_callback(
1179 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1180 function ($match) use ($author_link) {
1182 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1183 // 1 => '0123456789abcdef'
1185 $handle = self::urlFromContactGuid($match[1]);
1188 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1190 // No local match, restoring absolute remote URL from author scheme and host
1191 $author_url = parse_url($author_link);
1192 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1204 * @brief sub function of "fetchGuid" which checks for links in messages
1206 * @param array $match array containing a link that has to be checked for a message link
1207 * @param array $item The item array
1210 private static function fetchGuidSub($match, $item)
1212 if (!self::storeByGuid($match[1], $item["author-link"])) {
1213 self::storeByGuid($match[1], $item["owner-link"]);
1218 * @brief Fetches an item with a given guid from a given server
1220 * @param string $guid the message guid
1221 * @param string $server The server address
1222 * @param int $uid The user id of the user
1224 * @return int the message id of the stored message or false
1226 private static function storeByGuid($guid, $server, $uid = 0)
1228 $serverparts = parse_url($server);
1229 $server = $serverparts["scheme"]."://".$serverparts["host"];
1231 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1233 $msg = self::message($guid, $server);
1239 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1241 // Now call the dispatcher
1242 return self::dispatchPublic($msg);
1246 * @brief Fetches a message from a server
1248 * @param string $guid message guid
1249 * @param string $server The url of the server
1250 * @param int $level Endless loop prevention
1253 * 'message' => The message XML
1254 * 'author' => The author handle
1255 * 'key' => The public key of the author
1257 private static function message($guid, $server, $level = 0)
1263 // This will work for new Diaspora servers and Friendica servers from 3.5
1264 $source_url = $server."/fetch/post/".urlencode($guid);
1266 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1268 $envelope = Network::fetchUrl($source_url);
1270 logger("Envelope was fetched.", LOGGER_DEBUG);
1271 $x = self::verifyMagicEnvelope($envelope);
1273 logger("Envelope could not be verified.", LOGGER_DEBUG);
1275 logger("Envelope was verified.", LOGGER_DEBUG);
1281 // This will work for older Diaspora and Friendica servers
1283 $source_url = $server."/p/".urlencode($guid).".xml";
1284 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1286 $x = Network::fetchUrl($source_url);
1292 $source_xml = XML::parseString($x);
1294 if (!is_object($source_xml)) {
1298 if ($source_xml->post->reshare) {
1299 // Reshare of a reshare - old Diaspora version
1300 logger("Message is a reshare", LOGGER_DEBUG);
1301 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1302 } elseif ($source_xml->getName() == "reshare") {
1303 // Reshare of a reshare - new Diaspora version
1304 logger("Message is a new reshare", LOGGER_DEBUG);
1305 return self::message($source_xml->root_guid, $server, ++$level);
1310 // Fetch the author - for the old and the new Diaspora version
1311 if ($source_xml->post->status_message->diaspora_handle) {
1312 $author = (string)$source_xml->post->status_message->diaspora_handle;
1313 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1314 $author = (string)$source_xml->author;
1317 // If this isn't a "status_message" then quit
1319 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1323 $msg = ["message" => $x, "author" => $author];
1325 $msg["key"] = self::key($msg["author"]);
1331 * @brief Fetches the item record of a given guid
1333 * @param int $uid The user id
1334 * @param string $guid message guid
1335 * @param string $author The handle of the item
1336 * @param array $contact The contact of the item owner
1338 * @return array the item record
1340 private static function parentItem($uid, $guid, $author, $contact)
1343 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1344 `author-name`, `author-link`, `author-avatar`,
1345 `owner-name`, `owner-link`, `owner-avatar`
1346 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1352 $result = self::storeByGuid($guid, $contact["url"], $uid);
1355 $person = self::personByHandle($author);
1356 $result = self::storeByGuid($guid, $person["url"], $uid);
1360 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1363 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1364 `author-name`, `author-link`, `author-avatar`,
1365 `owner-name`, `owner-link`, `owner-avatar`
1366 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1374 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1377 logger("parent item found: parent: ".$guid." - user: ".$uid);
1383 * @brief returns contact details
1385 * @param array $def_contact The default contact if the person isn't found
1386 * @param array $person The record of the person
1387 * @param int $uid The user id
1390 * 'cid' => contact id
1391 * 'network' => network type
1393 private static function authorContactByUrl($def_contact, $person, $uid)
1395 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1396 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1397 if (DBM::is_result($contact)) {
1398 $cid = $contact["id"];
1399 $network = $contact["network"];
1401 $cid = $def_contact["id"];
1402 $network = NETWORK_DIASPORA;
1405 return ["cid" => $cid, "network" => $network];
1409 * @brief Is the profile a hubzilla profile?
1411 * @param string $url The profile link
1413 * @return bool is it a hubzilla server?
1415 public static function isRedmatrix($url)
1417 return(strstr($url, "/channel/"));
1421 * @brief Generate a post link with a given handle and message guid
1423 * @param string $addr The user handle
1424 * @param string $guid message guid
1425 * @param string $parent_guid optional parent guid
1427 * @return string the post link
1429 private static function plink($addr, $guid, $parent_guid = '')
1431 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1434 if (!DBM::is_result($r)) {
1435 if ($parent_guid != '') {
1436 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1438 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1442 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1443 // So we try another way as well.
1444 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1445 if (DBM::is_result($s)) {
1446 $r[0]["network"] = $s[0]["network"];
1449 if ($r[0]["network"] == NETWORK_DFRN) {
1450 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1453 if (self::isRedmatrix($r[0]["url"])) {
1454 return $r[0]["url"]."/?f=&mid=".$guid;
1457 if ($parent_guid != '') {
1458 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1460 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1465 * @brief Receives account migration
1467 * @param array $importer Array of the importer user
1468 * @param object $data The message object
1470 * @return bool Success
1472 private static function receiveAccountMigration($importer, $data)
1474 $old_handle = notags(unxmlify($data->author));
1475 $new_handle = notags(unxmlify($data->profile->author));
1476 $signature = notags(unxmlify($data->signature));
1478 $contact = self::contactByHandle($importer["uid"], $old_handle);
1480 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1484 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1487 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1488 $key = self::key($old_handle);
1489 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1490 logger('No valid signature for migration.');
1494 // Update the profile
1495 self::receiveProfile($importer, $data->profile);
1497 // change the technical stuff in contact and gcontact
1498 $data = Probe::uri($new_handle);
1499 if ($data['network'] == NETWORK_PHANTOM) {
1500 logger('Account for '.$new_handle." couldn't be probed.");
1504 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1505 'name' => $data['name'], 'nick' => $data['nick'],
1506 'addr' => $data['addr'], 'batch' => $data['batch'],
1507 'notify' => $data['notify'], 'poll' => $data['poll'],
1508 'network' => $data['network']];
1510 dba::update('contact', $fields, ['addr' => $old_handle]);
1512 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1513 'name' => $data['name'], 'nick' => $data['nick'],
1514 'addr' => $data['addr'], 'connect' => $data['addr'],
1515 'notify' => $data['notify'], 'photo' => $data['photo'],
1516 'server_url' => $data['baseurl'], 'network' => $data['network']];
1518 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1520 logger('Contacts are updated.');
1523 /// @todo This is an extreme performance killer
1525 'owner-link' => [$contact["url"], $data["url"]],
1526 'author-link' => [$contact["url"], $data["url"]],
1528 foreach ($fields as $n => $f) {
1530 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1533 intval($importer["uid"])
1536 if (DBM::is_result($r)) {
1538 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1543 intval($importer["uid"])
1552 logger('Items are updated.');
1558 * @brief Processes an account deletion
1560 * @param array $importer Array of the importer user
1561 * @param object $data The message object
1563 * @return bool Success
1565 private static function receiveAccountDeletion($importer, $data)
1567 /// @todo Account deletion should remove the contact from the global contacts as well
1569 $author = notags(unxmlify($data->author));
1571 $contact = self::contactByHandle($importer["uid"], $author);
1573 logger("cannot find contact for author: ".$author);
1577 // We now remove the contact
1578 Contact::remove($contact["id"]);
1583 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1585 * @param string $author Author handle
1586 * @param string $guid Message guid
1587 * @param boolean $onlyfound Only return uri when found in the database
1589 * @return string The constructed uri or the one from our database
1591 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1593 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1594 if (DBM::is_result($r)) {
1595 return $r[0]["uri"];
1596 } elseif (!$onlyfound) {
1597 return $author.":".$guid;
1604 * @brief Fetch the guid from our database with a given uri
1606 * @param string $uri Message uri
1607 * @param string $uid Author handle
1609 * @return string The post guid
1611 private static function getGuidFromUri($uri, $uid)
1613 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1614 if (DBM::is_result($r)) {
1615 return $r[0]["guid"];
1622 * @brief Find the best importer for a comment, like, ...
1624 * @param string $guid The guid of the item
1626 * @return array|boolean the origin owner of that post - or false
1628 private static function importerForGuid($guid)
1630 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1632 if (DBM::is_result($item)) {
1633 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1634 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1635 if (DBM::is_result($contact)) {
1643 * @brief Processes an incoming comment
1645 * @param array $importer Array of the importer user
1646 * @param string $sender The sender of the message
1647 * @param object $data The message object
1648 * @param string $xml The original XML of the message
1650 * @return int The message id of the generated comment or "false" if there was an error
1652 private static function receiveComment($importer, $sender, $data, $xml)
1654 $author = notags(unxmlify($data->author));
1655 $guid = notags(unxmlify($data->guid));
1656 $parent_guid = notags(unxmlify($data->parent_guid));
1657 $text = unxmlify($data->text);
1659 if (isset($data->created_at)) {
1660 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1662 $created_at = DateTimeFormat::utcNow();
1665 if (isset($data->thread_parent_guid)) {
1666 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1667 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1672 $contact = self::allowedContactByHandle($importer, $sender, true);
1677 $message_id = self::messageExists($importer["uid"], $guid);
1682 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1683 if (!$parent_item) {
1687 $person = self::personByHandle($author);
1688 if (!is_array($person)) {
1689 logger("unable to find author details");
1693 // Fetch the contact id - if we know this contact
1694 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1698 $datarray["uid"] = $importer["uid"];
1699 $datarray["contact-id"] = $author_contact["cid"];
1700 $datarray["network"] = $author_contact["network"];
1702 $datarray["author-name"] = $person["name"];
1703 $datarray["author-link"] = $person["url"];
1704 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1706 $datarray["owner-name"] = $contact["name"];
1707 $datarray["owner-link"] = $contact["url"];
1708 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1710 $datarray["guid"] = $guid;
1711 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1713 $datarray["type"] = "remote-comment";
1714 $datarray["verb"] = ACTIVITY_POST;
1715 $datarray["gravity"] = GRAVITY_COMMENT;
1717 if ($thr_uri != "") {
1718 $datarray["parent-uri"] = $thr_uri;
1720 $datarray["parent-uri"] = $parent_item["uri"];
1723 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1725 $datarray["protocol"] = PROTOCOL_DIASPORA;
1726 $datarray["source"] = $xml;
1728 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1730 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1732 $body = diaspora2bb($text);
1734 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1736 self::fetchGuid($datarray);
1738 $message_id = Item::insert($datarray);
1740 if ($message_id <= 0) {
1745 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1748 // If we are the origin of the parent we store the original data and notify our followers
1749 if ($message_id && $parent_item["origin"]) {
1750 // Formerly we stored the signed text, the signature and the author in different fields.
1751 // We now store the raw data so that we are more flexible.
1752 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1755 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1762 * @brief processes and stores private messages
1764 * @param array $importer Array of the importer user
1765 * @param array $contact The contact of the message
1766 * @param object $data The message object
1767 * @param array $msg Array of the processed message, author handle and key
1768 * @param object $mesg The private message
1769 * @param array $conversation The conversation record to which this message belongs
1771 * @return bool "true" if it was successful
1773 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1775 $author = notags(unxmlify($data->author));
1776 $guid = notags(unxmlify($data->guid));
1777 $subject = notags(unxmlify($data->subject));
1779 // "diaspora_handle" is the element name from the old version
1780 // "author" is the element name from the new version
1781 if ($mesg->author) {
1782 $msg_author = notags(unxmlify($mesg->author));
1783 } elseif ($mesg->diaspora_handle) {
1784 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1789 $msg_guid = notags(unxmlify($mesg->guid));
1790 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1791 $msg_text = unxmlify($mesg->text);
1792 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1794 if ($msg_conversation_guid != $guid) {
1795 logger("message conversation guid does not belong to the current conversation.");
1799 $body = diaspora2bb($msg_text);
1800 $message_uri = $msg_author.":".$msg_guid;
1802 $person = self::personByHandle($msg_author);
1807 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1809 intval($importer["uid"])
1811 if (DBM::is_result($r)) {
1812 logger("duplicate message already delivered.", LOGGER_DEBUG);
1817 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1818 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1819 intval($importer["uid"]),
1821 intval($conversation["id"]),
1822 dbesc($person["name"]),
1823 dbesc($person["photo"]),
1824 dbesc($person["url"]),
1825 intval($contact["id"]),
1830 dbesc($message_uri),
1831 dbesc($author.":".$guid),
1832 dbesc($msg_created_at)
1837 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1841 "type" => NOTIFY_MAIL,
1842 "notify_flags" => $importer["notify-flags"],
1843 "language" => $importer["language"],
1844 "to_name" => $importer["username"],
1845 "to_email" => $importer["email"],
1846 "uid" =>$importer["uid"],
1847 "item" => ["subject" => $subject, "body" => $body],
1848 "source_name" => $person["name"],
1849 "source_link" => $person["url"],
1850 "source_photo" => $person["thumb"],
1851 "verb" => ACTIVITY_POST,
1858 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1860 * @param array $importer Array of the importer user
1861 * @param array $msg Array of the processed message, author handle and key
1862 * @param object $data The message object
1864 * @return bool Success
1866 private static function receiveConversation($importer, $msg, $data)
1868 $author = notags(unxmlify($data->author));
1869 $guid = notags(unxmlify($data->guid));
1870 $subject = notags(unxmlify($data->subject));
1871 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1872 $participants = notags(unxmlify($data->participants));
1874 $messages = $data->message;
1876 if (!count($messages)) {
1877 logger("empty conversation");
1881 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1886 $conversation = null;
1889 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1890 intval($importer["uid"]),
1894 $conversation = $c[0];
1897 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1898 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1899 intval($importer["uid"]),
1903 dbesc(DateTimeFormat::utcNow()),
1905 dbesc($participants)
1909 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1910 intval($importer["uid"]),
1916 $conversation = $c[0];
1919 if (!$conversation) {
1920 logger("unable to create conversation.");
1924 foreach ($messages as $mesg) {
1925 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1932 * @brief Creates the body for a "like" message
1934 * @param array $contact The contact that send us the "like"
1935 * @param array $parent_item The item array of the parent item
1936 * @param string $guid message guid
1938 * @return string the body
1940 private static function constructLikeBody($contact, $parent_item, $guid)
1942 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1944 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1945 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1946 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
1948 return sprintf($bodyverb, $ulink, $alink, $plink);
1952 * @brief Creates a XML object for a "like"
1954 * @param array $importer Array of the importer user
1955 * @param array $parent_item The item array of the parent item
1957 * @return string The XML
1959 private static function constructLikeObject($importer, $parent_item)
1961 $objtype = ACTIVITY_OBJ_NOTE;
1962 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1963 $parent_body = $parent_item["body"];
1965 $xmldata = ["object" => ["type" => $objtype,
1967 "id" => $parent_item["uri"],
1970 "content" => $parent_body]];
1972 return XML::fromArray($xmldata, $xml, true);
1976 * @brief Processes "like" messages
1978 * @param array $importer Array of the importer user
1979 * @param string $sender The sender of the message
1980 * @param object $data The message object
1982 * @return int The message id of the generated like or "false" if there was an error
1984 private static function receiveLike($importer, $sender, $data)
1986 $author = notags(unxmlify($data->author));
1987 $guid = notags(unxmlify($data->guid));
1988 $parent_guid = notags(unxmlify($data->parent_guid));
1989 $parent_type = notags(unxmlify($data->parent_type));
1990 $positive = notags(unxmlify($data->positive));
1992 // likes on comments aren't supported by Diaspora - only on posts
1993 // But maybe this will be supported in the future, so we will accept it.
1994 if (!in_array($parent_type, ["Post", "Comment"])) {
1998 $contact = self::allowedContactByHandle($importer, $sender, true);
2003 $message_id = self::messageExists($importer["uid"], $guid);
2008 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2009 if (!$parent_item) {
2013 $person = self::personByHandle($author);
2014 if (!is_array($person)) {
2015 logger("unable to find author details");
2019 // Fetch the contact id - if we know this contact
2020 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2022 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2023 // We would accept this anyhow.
2024 if ($positive == "true") {
2025 $verb = ACTIVITY_LIKE;
2027 $verb = ACTIVITY_DISLIKE;
2032 $datarray["protocol"] = PROTOCOL_DIASPORA;
2034 $datarray["uid"] = $importer["uid"];
2035 $datarray["contact-id"] = $author_contact["cid"];
2036 $datarray["network"] = $author_contact["network"];
2038 $datarray["author-name"] = $person["name"];
2039 $datarray["author-link"] = $person["url"];
2040 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2042 $datarray["owner-name"] = $contact["name"];
2043 $datarray["owner-link"] = $contact["url"];
2044 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2046 $datarray["guid"] = $guid;
2047 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2049 $datarray["type"] = "activity";
2050 $datarray["verb"] = $verb;
2051 $datarray["gravity"] = GRAVITY_LIKE;
2052 $datarray["parent-uri"] = $parent_item["uri"];
2054 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2055 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2057 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2059 $message_id = Item::insert($datarray);
2061 if ($message_id <= 0) {
2066 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2069 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2070 if ($parent_item["id"] != $parent_item["parent"]) {
2071 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2072 $origin = $toplevel["origin"];
2074 $origin = $parent_item["origin"];
2077 // If we are the origin of the parent we store the original data and notify our followers
2078 if ($message_id && $origin) {
2079 // Formerly we stored the signed text, the signature and the author in different fields.
2080 // We now store the raw data so that we are more flexible.
2081 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2084 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2091 * @brief Processes private messages
2093 * @param array $importer Array of the importer user
2094 * @param object $data The message object
2096 * @return bool Success?
2098 private static function receiveMessage($importer, $data)
2100 $author = notags(unxmlify($data->author));
2101 $guid = notags(unxmlify($data->guid));
2102 $conversation_guid = notags(unxmlify($data->conversation_guid));
2103 $text = unxmlify($data->text);
2104 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2106 $contact = self::allowedContactByHandle($importer, $author, true);
2111 $conversation = null;
2114 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2115 intval($importer["uid"]),
2116 dbesc($conversation_guid)
2119 $conversation = $c[0];
2121 logger("conversation not available.");
2125 $message_uri = $author.":".$guid;
2127 $person = self::personByHandle($author);
2129 logger("unable to find author details");
2133 $body = diaspora2bb($text);
2135 $body = self::replacePeopleGuid($body, $person["url"]);
2140 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2142 intval($importer["uid"])
2144 if (DBM::is_result($r)) {
2145 logger("duplicate message already delivered.", LOGGER_DEBUG);
2150 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2151 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2152 intval($importer["uid"]),
2154 intval($conversation["id"]),
2155 dbesc($person["name"]),
2156 dbesc($person["photo"]),
2157 dbesc($person["url"]),
2158 intval($contact["id"]),
2159 dbesc($conversation["subject"]),
2163 dbesc($message_uri),
2164 dbesc($author.":".$conversation["guid"]),
2170 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2175 * @brief Processes participations - unsupported by now
2177 * @param array $importer Array of the importer user
2178 * @param object $data The message object
2180 * @return bool always true
2182 private static function receiveParticipation($importer, $data)
2184 $author = strtolower(notags(unxmlify($data->author)));
2185 $parent_guid = notags(unxmlify($data->parent_guid));
2187 $contact_id = Contact::getIdForURL($author);
2189 logger('Contact not found: '.$author);
2193 $person = self::personByHandle($author);
2194 if (!is_array($person)) {
2195 logger("Person not found: ".$author);
2199 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2200 if (!DBM::is_result($item)) {
2201 logger('Item not found, no origin or private: '.$parent_guid);
2205 $author_parts = explode('@', $author);
2206 if (isset($author_parts[1])) {
2207 $server = $author_parts[1];
2209 // Should never happen
2213 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2214 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2216 // Send all existing comments and likes to the requesting server
2217 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2219 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2220 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2221 while ($comment = dba::fetch($comments)) {
2222 if ($comment['verb'] == ACTIVITY_POST) {
2223 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2225 $cmd = $comment['self'] ? 'like' : 'comment-import';
2227 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2228 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2230 dba::close($comments);
2236 * @brief Processes photos - unneeded
2238 * @param array $importer Array of the importer user
2239 * @param object $data The message object
2241 * @return bool always true
2243 private static function receivePhoto($importer, $data)
2245 // There doesn't seem to be a reason for this function,
2246 // since the photo data is transmitted in the status message as well
2251 * @brief Processes poll participations - unssupported
2253 * @param array $importer Array of the importer user
2254 * @param object $data The message object
2256 * @return bool always true
2258 private static function receivePollParticipation($importer, $data)
2260 // We don't support polls by now
2265 * @brief Processes incoming profile updates
2267 * @param array $importer Array of the importer user
2268 * @param object $data The message object
2270 * @return bool Success
2272 private static function receiveProfile($importer, $data)
2274 $author = strtolower(notags(unxmlify($data->author)));
2276 $contact = self::contactByHandle($importer["uid"], $author);
2281 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2282 $image_url = unxmlify($data->image_url);
2283 $birthday = unxmlify($data->birthday);
2284 $gender = unxmlify($data->gender);
2285 $about = diaspora2bb(unxmlify($data->bio));
2286 $location = diaspora2bb(unxmlify($data->location));
2287 $searchable = (unxmlify($data->searchable) == "true");
2288 $nsfw = (unxmlify($data->nsfw) == "true");
2289 $tags = unxmlify($data->tag_string);
2291 $tags = explode("#", $tags);
2294 foreach ($tags as $tag) {
2295 $tag = trim(strtolower($tag));
2301 $keywords = implode(", ", $keywords);
2303 $handle_parts = explode("@", $author);
2304 $nick = $handle_parts[0];
2307 $name = $handle_parts[0];
2310 if (preg_match("|^https?://|", $image_url) === 0) {
2311 $image_url = "http://".$handle_parts[1].$image_url;
2314 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2316 // Generic birthday. We don't know the timezone. The year is irrelevant.
2318 $birthday = str_replace("1000", "1901", $birthday);
2320 if ($birthday != "") {
2321 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2324 // this is to prevent multiple birthday notifications in a single year
2325 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2327 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2328 $birthday = $contact["bd"];
2332 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2333 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2337 dbesc(DateTimeFormat::utcNow()),
2343 intval($contact["id"]),
2344 intval($importer["uid"])
2347 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2348 "photo" => $image_url, "name" => $name, "location" => $location,
2349 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2350 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2351 "hide" => !$searchable, "nsfw" => $nsfw];
2353 $gcid = GContact::update($gcontact);
2355 GContact::link($gcid, $importer["uid"], $contact["id"]);
2357 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2363 * @brief Processes incoming friend requests
2365 * @param array $importer Array of the importer user
2366 * @param array $contact The contact that send the request
2369 private static function receiveRequestMakeFriend($importer, $contact)
2373 if ($contact["rel"] == CONTACT_IS_SHARING) {
2376 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2377 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2380 // send notification
2383 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2384 intval($importer["uid"])
2387 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2389 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2390 intval($importer["uid"])
2393 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2395 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2397 $arr["protocol"] = PROTOCOL_DIASPORA;
2398 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2399 $arr["uid"] = $importer["uid"];
2400 $arr["contact-id"] = $self[0]["id"];
2402 $arr["type"] = 'wall';
2403 $arr["gravity"] = 0;
2405 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2406 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2407 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2408 $arr["verb"] = ACTIVITY_FRIEND;
2409 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2411 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2412 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2413 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2414 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2416 $arr["object"] = self::constructNewFriendObject($contact);
2418 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2420 $arr["allow_cid"] = $user["allow_cid"];
2421 $arr["allow_gid"] = $user["allow_gid"];
2422 $arr["deny_cid"] = $user["deny_cid"];
2423 $arr["deny_gid"] = $user["deny_gid"];
2425 $i = Item::insert($arr);
2427 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2434 * @brief Creates a XML object for a "new friend" message
2436 * @param array $contact Array of the contact
2438 * @return string The XML
2440 private static function constructNewFriendObject($contact)
2442 $objtype = ACTIVITY_OBJ_PERSON;
2443 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2444 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2446 $xmldata = ["object" => ["type" => $objtype,
2447 "title" => $contact["name"],
2448 "id" => $contact["url"]."/".$contact["name"],
2451 return XML::fromArray($xmldata, $xml, true);
2455 * @brief Processes incoming sharing notification
2457 * @param array $importer Array of the importer user
2458 * @param object $data The message object
2460 * @return bool Success
2462 private static function receiveContactRequest($importer, $data)
2464 $author = unxmlify($data->author);
2465 $recipient = unxmlify($data->recipient);
2467 if (!$author || !$recipient) {
2471 // the current protocol version doesn't know these fields
2472 // That means that we will assume their existance
2473 if (isset($data->following)) {
2474 $following = (unxmlify($data->following) == "true");
2479 if (isset($data->sharing)) {
2480 $sharing = (unxmlify($data->sharing) == "true");
2485 $contact = self::contactByHandle($importer["uid"], $author);
2487 // perhaps we were already sharing with this person. Now they're sharing with us.
2488 // That makes us friends.
2491 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2492 self::receiveRequestMakeFriend($importer, $contact);
2494 // refetch the contact array
2495 $contact = self::contactByHandle($importer["uid"], $author);
2497 // If we are now friends, we are sending a share message.
2498 // Normally we needn't to do so, but the first message could have been vanished.
2499 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2500 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2502 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2503 $ret = self::sendShare($u[0], $contact);
2508 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2509 Contact::removeFollower($importer, $contact);
2514 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2515 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2517 } elseif (!$following && !$sharing) {
2518 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2520 } elseif (!$following && $sharing) {
2521 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2522 } elseif ($following && $sharing) {
2523 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2524 } elseif ($following && !$sharing) {
2525 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2528 $ret = self::personByHandle($author);
2530 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2531 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2535 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2538 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2539 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2540 intval($importer["uid"]),
2541 dbesc($ret["network"]),
2542 dbesc($ret["addr"]),
2543 DateTimeFormat::utcNow(),
2545 dbesc(normalise_link($ret["url"])),
2547 dbesc($ret["name"]),
2548 dbesc($ret["nick"]),
2549 dbesc($ret["photo"]),
2550 dbesc($ret["pubkey"]),
2551 dbesc($ret["notify"]),
2552 dbesc($ret["poll"]),
2557 // find the contact record we just created
2559 $contact_record = self::contactByHandle($importer["uid"], $author);
2561 if (!$contact_record) {
2562 logger("unable to locate newly created contact record.");
2566 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2568 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2570 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2572 if ($importer["page-flags"] == PAGE_NORMAL) {
2573 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2575 $hash = random_string().(string)time(); // Generate a confirm_key
2578 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2579 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2580 intval($importer["uid"]),
2581 intval($contact_record["id"]),
2584 dbesc(L10n::t("Sharing notification from Diaspora network")),
2586 dbesc(DateTimeFormat::utcNow())
2589 // automatic friend approval
2591 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2593 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2595 // technically they are sharing with us (CONTACT_IS_SHARING),
2596 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2597 // we are going to change the relationship and make them a follower.
2599 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2600 $new_relation = CONTACT_IS_FRIEND;
2601 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2602 $new_relation = CONTACT_IS_SHARING;
2604 $new_relation = CONTACT_IS_FOLLOWER;
2608 "UPDATE `contact` SET `rel` = %d,
2616 intval($new_relation),
2617 dbesc(DateTimeFormat::utcNow()),
2618 dbesc(DateTimeFormat::utcNow()),
2619 intval($contact_record["id"])
2622 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2624 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2625 $ret = self::sendShare($u[0], $contact_record);
2627 // Send the profile data, maybe it weren't transmitted before
2628 self::sendProfile($importer["uid"], [$contact_record]);
2636 * @brief Fetches a message with a given guid
2638 * @param string $guid message guid
2639 * @param string $orig_author handle of the original post
2640 * @param string $author handle of the sharer
2642 * @return array The fetched item
2644 private static function originalItem($guid, $orig_author, $author)
2646 // Do we already have this item?
2648 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2649 `author-name`, `author-link`, `author-avatar`
2650 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2654 if (DBM::is_result($r)) {
2655 logger("reshared message ".$guid." already exists on system.");
2657 // Maybe it is already a reshared item?
2658 // Then refetch the content, if it is a reshare from a reshare.
2659 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2660 if (self::isReshare($r[0]["body"], true)) {
2662 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2663 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2665 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2667 // Add OEmbed and other information to the body
2668 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2676 if (!DBM::is_result($r)) {
2677 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2678 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2679 $item_id = self::storeByGuid($guid, $server);
2682 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2683 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2684 $item_id = self::storeByGuid($guid, $server);
2689 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2690 `author-name`, `author-link`, `author-avatar`
2691 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2695 if (DBM::is_result($r)) {
2696 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2697 if (self::isReshare($r[0]["body"], false)) {
2698 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2699 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2710 * @brief Processes a reshare message
2712 * @param array $importer Array of the importer user
2713 * @param object $data The message object
2714 * @param string $xml The original XML of the message
2716 * @return int the message id
2718 private static function receiveReshare($importer, $data, $xml)
2720 $author = notags(unxmlify($data->author));
2721 $guid = notags(unxmlify($data->guid));
2722 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2723 $root_author = notags(unxmlify($data->root_author));
2724 $root_guid = notags(unxmlify($data->root_guid));
2725 /// @todo handle unprocessed property "provider_display_name"
2726 $public = notags(unxmlify($data->public));
2728 $contact = self::allowedContactByHandle($importer, $author, false);
2733 $message_id = self::messageExists($importer["uid"], $guid);
2738 $original_item = self::originalItem($root_guid, $root_author, $author);
2739 if (!$original_item) {
2743 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2747 $datarray["uid"] = $importer["uid"];
2748 $datarray["contact-id"] = $contact["id"];
2749 $datarray["network"] = NETWORK_DIASPORA;
2751 $datarray["author-name"] = $contact["name"];
2752 $datarray["author-link"] = $contact["url"];
2753 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2755 $datarray["owner-name"] = $datarray["author-name"];
2756 $datarray["owner-link"] = $datarray["author-link"];
2757 $datarray["owner-avatar"] = $datarray["author-avatar"];
2759 $datarray["guid"] = $guid;
2760 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2762 $datarray["verb"] = ACTIVITY_POST;
2763 $datarray["gravity"] = GRAVITY_PARENT;
2765 $datarray["protocol"] = PROTOCOL_DIASPORA;
2766 $datarray["source"] = $xml;
2768 $prefix = share_header(
2769 $original_item["author-name"],
2770 $original_item["author-link"],
2771 $original_item["author-avatar"],
2772 $original_item["guid"],
2773 $original_item["created"],
2776 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2778 $datarray["tag"] = $original_item["tag"];
2779 $datarray["app"] = $original_item["app"];
2781 $datarray["plink"] = self::plink($author, $guid);
2782 $datarray["private"] = (($public == "false") ? 1 : 0);
2783 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2785 $datarray["object-type"] = $original_item["object-type"];
2787 self::fetchGuid($datarray);
2788 $message_id = Item::insert($datarray);
2790 self::sendParticipation($contact, $datarray);
2793 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2801 * @brief Processes retractions
2803 * @param array $importer Array of the importer user
2804 * @param array $contact The contact of the item owner
2805 * @param object $data The message object
2807 * @return bool success
2809 private static function itemRetraction($importer, $contact, $data)
2811 $author = notags(unxmlify($data->author));
2812 $target_guid = notags(unxmlify($data->target_guid));
2813 $target_type = notags(unxmlify($data->target_type));
2815 $person = self::personByHandle($author);
2816 if (!is_array($person)) {
2817 logger("unable to find author detail for ".$author);
2821 if (empty($contact["url"])) {
2822 $contact["url"] = $person["url"];
2825 // Fetch items that are about to be deleted
2826 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2828 // When we receive a public retraction, we delete every item that we find.
2829 if ($importer['uid'] == 0) {
2830 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2832 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2834 $r = dba::select('item', $fields, $condition);
2835 if (!DBM::is_result($r)) {
2836 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2840 while ($item = dba::fetch($r)) {
2841 // Fetch the parent item
2842 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2844 // Only delete it if the parent author really fits
2845 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2846 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2850 Item::deleteById($item["id"]);
2852 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2854 // Now check if the retraction needs to be relayed by us
2855 if ($parent["origin"]) {
2857 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2865 * @brief Receives retraction messages
2867 * @param array $importer Array of the importer user
2868 * @param string $sender The sender of the message
2869 * @param object $data The message object
2871 * @return bool Success
2873 private static function receiveRetraction($importer, $sender, $data)
2875 $target_type = notags(unxmlify($data->target_type));
2877 $contact = self::contactByHandle($importer["uid"], $sender);
2878 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2879 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2883 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2885 switch ($target_type) {
2890 case "StatusMessage":
2891 return self::itemRetraction($importer, $contact, $data);
2895 /// @todo What should we do with an "unshare"?
2896 // Removing the contact isn't correct since we still can read the public items
2897 Contact::remove($contact["id"]);
2901 logger("Unknown target type ".$target_type);
2908 * @brief Receives status messages
2910 * @param array $importer Array of the importer user
2911 * @param object $data The message object
2912 * @param string $xml The original XML of the message
2914 * @return int The message id of the newly created item
2916 private static function receiveStatusMessage($importer, $data, $xml)
2918 $author = notags(unxmlify($data->author));
2919 $guid = notags(unxmlify($data->guid));
2920 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2921 $public = notags(unxmlify($data->public));
2922 $text = unxmlify($data->text);
2923 $provider_display_name = notags(unxmlify($data->provider_display_name));
2925 $contact = self::allowedContactByHandle($importer, $author, false);
2930 $message_id = self::messageExists($importer["uid"], $guid);
2936 if ($data->location) {
2937 foreach ($data->location->children() as $fieldname => $data) {
2938 $address[$fieldname] = notags(unxmlify($data));
2942 $body = diaspora2bb($text);
2946 // Attach embedded pictures to the body
2948 foreach ($data->photo as $photo) {
2949 $body = "[img]".unxmlify($photo->remote_photo_path).
2950 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2953 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2955 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2957 // Add OEmbed and other information to the body
2958 if (!self::isRedmatrix($contact["url"])) {
2959 $body = add_page_info_to_body($body, false, true);
2963 /// @todo enable support for polls
2964 //if ($data->poll) {
2965 // foreach ($data->poll AS $poll)
2970 /// @todo enable support for events
2972 $datarray["uid"] = $importer["uid"];
2973 $datarray["contact-id"] = $contact["id"];
2974 $datarray["network"] = NETWORK_DIASPORA;
2976 $datarray["author-name"] = $contact["name"];
2977 $datarray["author-link"] = $contact["url"];
2978 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2980 $datarray["owner-name"] = $datarray["author-name"];
2981 $datarray["owner-link"] = $datarray["author-link"];
2982 $datarray["owner-avatar"] = $datarray["author-avatar"];
2984 $datarray["guid"] = $guid;
2985 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2987 $datarray["verb"] = ACTIVITY_POST;
2988 $datarray["gravity"] = GRAVITY_PARENT;
2990 $datarray["protocol"] = PROTOCOL_DIASPORA;
2991 $datarray["source"] = $xml;
2993 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2995 if ($provider_display_name != "") {
2996 $datarray["app"] = $provider_display_name;
2999 $datarray["plink"] = self::plink($author, $guid);
3000 $datarray["private"] = (($public == "false") ? 1 : 0);
3001 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3003 if (isset($address["address"])) {
3004 $datarray["location"] = $address["address"];
3007 if (isset($address["lat"]) && isset($address["lng"])) {
3008 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3011 self::fetchGuid($datarray);
3012 $message_id = Item::insert($datarray);
3014 self::sendParticipation($contact, $datarray);
3017 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3024 /* ************************************************************************************** *
3025 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3026 * ************************************************************************************** */
3029 * @brief returnes the handle of a contact
3031 * @param array $contact contact array
3033 * @return string the handle in the format user@domain.tld
3035 private static function myHandle($contact)
3037 if ($contact["addr"] != "") {
3038 return $contact["addr"];
3041 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3042 // So - just in case - we build the the address here.
3043 if ($contact["nickname"] != "") {
3044 $nick = $contact["nickname"];
3046 $nick = $contact["nick"];
3049 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3054 * @brief Creates the data for a private message in the new format
3056 * @param string $msg The message that is to be transmitted
3057 * @param array $user The record of the sender
3058 * @param array $contact Target of the communication
3059 * @param string $prvkey The private key of the sender
3060 * @param string $pubkey The public key of the receiver
3062 * @return string The encrypted data
3064 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3066 logger("Message: ".$msg, LOGGER_DATA);
3068 // without a public key nothing will work
3070 logger("pubkey missing: contact id: ".$contact["id"]);
3074 $aes_key = openssl_random_pseudo_bytes(32);
3075 $b_aes_key = base64_encode($aes_key);
3076 $iv = openssl_random_pseudo_bytes(16);
3077 $b_iv = base64_encode($iv);
3079 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3081 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3083 $encrypted_key_bundle = "";
3084 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3086 $json_object = json_encode(
3087 ["aes_key" => base64_encode($encrypted_key_bundle),
3088 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3091 return $json_object;
3095 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3097 * @param string $msg The message that is to be transmitted
3098 * @param array $user The record of the sender
3100 * @return string The envelope
3102 public static function buildMagicEnvelope($msg, $user)
3104 $b64url_data = base64url_encode($msg);
3105 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3107 $key_id = base64url_encode(self::myHandle($user));
3108 $type = "application/xml";
3109 $encoding = "base64url";
3110 $alg = "RSA-SHA256";
3111 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3113 // Fallback if the private key wasn't transmitted in the expected field
3114 if ($user['uprvkey'] == "") {
3115 $user['uprvkey'] = $user['prvkey'];
3118 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3119 $sig = base64url_encode($signature);
3121 $xmldata = ["me:env" => ["me:data" => $data,
3122 "@attributes" => ["type" => $type],
3123 "me:encoding" => $encoding,
3126 "@attributes2" => ["key_id" => $key_id]]];
3128 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3130 return XML::fromArray($xmldata, $xml, false, $namespaces);
3134 * @brief Create the envelope for a message
3136 * @param string $msg The message that is to be transmitted
3137 * @param array $user The record of the sender
3138 * @param array $contact Target of the communication
3139 * @param string $prvkey The private key of the sender
3140 * @param string $pubkey The public key of the receiver
3141 * @param bool $public Is the message public?
3143 * @return string The message that will be transmitted to other servers
3145 private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3147 // The message is put into an envelope with the sender's signature
3148 $envelope = self::buildMagicEnvelope($msg, $user);
3150 // Private messages are put into a second envelope, encrypted with the receivers public key
3152 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3159 * @brief Creates a signature for a message
3161 * @param array $owner the array of the owner of the message
3162 * @param array $message The message that is to be signed
3164 * @return string The signature
3166 private static function signature($owner, $message)
3169 unset($sigmsg["author_signature"]);
3170 unset($sigmsg["parent_author_signature"]);
3172 $signed_text = implode(";", $sigmsg);
3174 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3178 * @brief Transmit a message to a target server
3180 * @param array $owner the array of the item owner
3181 * @param array $contact Target of the communication
3182 * @param string $envelope The message that is to be transmitted
3183 * @param bool $public_batch Is it a public post?
3184 * @param bool $queue_run Is the transmission called from the queue?
3185 * @param string $guid message guid
3187 * @return int Result of the transmission
3189 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3193 $enabled = intval(Config::get("system", "diaspora_enabled"));
3198 $logid = random_string(4);
3199 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3201 // Fetch the fcontact entry when there is missing data
3202 // Will possibly happen when data is transmitted to a DFRN contact
3203 if (empty($dest_url) && !empty($contact['addr'])) {
3204 $fcontact = self::personByHandle($contact['addr']);
3205 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3209 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3213 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3215 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3218 if (!intval(Config::get("system", "diaspora_test"))) {
3219 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3221 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3222 $return_code = $a->get_curl_code();
3224 logger("test_mode");
3229 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3231 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3233 logger("queue message");
3234 // queue message for redelivery
3235 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3238 // The message could not be delivered. We mark the contact as "dead"
3239 Contact::markForArchival($contact);
3240 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3241 // We successfully delivered a message, the contact is alive
3242 Contact::unmarkForArchival($contact);
3245 return $return_code ? $return_code : -1;
3250 * @brief Build the post xml
3252 * @param string $type The message type
3253 * @param array $message The message data
3255 * @return string The post XML
3257 public static function buildPostXml($type, $message)
3259 $data = [$type => $message];
3261 return XML::fromArray($data, $xml);
3265 * @brief Builds and transmit messages
3267 * @param array $owner the array of the item owner
3268 * @param array $contact Target of the communication
3269 * @param string $type The message type
3270 * @param array $message The message data
3271 * @param bool $public_batch Is it a public post?
3272 * @param string $guid message guid
3273 * @param bool $spool Should the transmission be spooled or transmitted?
3275 * @return int Result of the transmission
3277 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3279 $msg = self::buildPostXml($type, $message);
3281 logger('message: '.$msg, LOGGER_DATA);
3282 logger('send guid '.$guid, LOGGER_DEBUG);
3284 // Fallback if the private key wasn't transmitted in the expected field
3285 if ($owner['uprvkey'] == "") {
3286 $owner['uprvkey'] = $owner['prvkey'];
3289 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3292 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3295 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3298 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3300 return $return_code;
3304 * @brief sends a participation (Used to get all further updates)
3306 * @param array $contact Target of the communication
3307 * @param array $item Item array
3309 * @return int The result of the transmission
3311 private static function sendParticipation($contact, $item)
3313 // Don't send notifications for private postings
3314 if ($item['private']) {
3318 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3320 $result = Cache::get($cachekey);
3321 if (!is_null($result)) {
3325 // Fetch some user id to have a valid handle to transmit the participation.
3326 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3327 // If the item belongs to a user, we take this user id.
3328 if ($item['uid'] == 0) {
3329 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3330 $first_user = dba::selectFirst('user', ['uid'], $condition);
3331 $owner = User::getOwnerDataById($first_user['uid']);
3333 $owner = User::getOwnerDataById($item['uid']);
3336 $author = self::myHandle($owner);
3338 $message = ["author" => $author,
3339 "guid" => get_guid(32),
3340 "parent_type" => "Post",
3341 "parent_guid" => $item["guid"]];
3343 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3345 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3346 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3348 return self::buildAndTransmit($owner, $contact, "participation", $message);
3352 * @brief sends an account migration
3354 * @param array $owner the array of the item owner
3355 * @param array $contact Target of the communication
3356 * @param int $uid User ID
3358 * @return int The result of the transmission
3360 public static function sendAccountMigration($owner, $contact, $uid)
3362 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3363 $profile = self::createProfileData($uid);
3365 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3366 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3368 $message = ["author" => $old_handle,
3369 "profile" => $profile,
3370 "signature" => $signature];
3372 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3374 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3378 * @brief Sends a "share" message
3380 * @param array $owner the array of the item owner
3381 * @param array $contact Target of the communication
3383 * @return int The result of the transmission
3385 public static function sendShare($owner, $contact)
3388 * @todo support the different possible combinations of "following" and "sharing"
3389 * Currently, Diaspora only interprets the "sharing" field
3391 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3395 switch ($contact["rel"]) {
3396 case CONTACT_IS_FRIEND:
3399 case CONTACT_IS_SHARING:
3402 case CONTACT_IS_FOLLOWER:
3408 $message = ["author" => self::myHandle($owner),
3409 "recipient" => $contact["addr"],
3410 "following" => "true",
3411 "sharing" => "true"];
3413 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3415 return self::buildAndTransmit($owner, $contact, "contact", $message);
3419 * @brief sends an "unshare"
3421 * @param array $owner the array of the item owner
3422 * @param array $contact Target of the communication
3424 * @return int The result of the transmission
3426 public static function sendUnshare($owner, $contact)
3428 $message = ["author" => self::myHandle($owner),
3429 "recipient" => $contact["addr"],
3430 "following" => "false",
3431 "sharing" => "false"];
3433 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3435 return self::buildAndTransmit($owner, $contact, "contact", $message);
3439 * @brief Checks a message body if it is a reshare
3441 * @param string $body The message body that is to be check
3442 * @param bool $complete Should it be a complete check or a simple check?
3444 * @return array|bool Reshare details or "false" if no reshare
3446 public static function isReshare($body, $complete = true)
3448 $body = trim($body);
3450 // Skip if it isn't a pure repeated messages
3451 // Does it start with a share?
3452 if ((strpos($body, "[share") > 0) && $complete) {
3456 // Does it end with a share?
3457 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3461 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3462 // Skip if there is no shared message in there
3463 if ($body == $attributes) {
3467 // If we don't do the complete check we quit here
3473 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3474 if ($matches[1] != "") {
3475 $guid = $matches[1];
3478 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3479 if ($matches[1] != "") {
3480 $guid = $matches[1];
3485 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3492 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3493 $ret["root_guid"] = $guid;
3499 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3500 if ($matches[1] != "") {
3501 $profile = $matches[1];
3504 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3505 if ($matches[1] != "") {
3506 $profile = $matches[1];
3511 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3512 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3517 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3518 if ($matches[1] != "") {
3519 $link = $matches[1];
3522 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3523 if ($matches[1] != "") {
3524 $link = $matches[1];
3527 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3528 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3536 * @brief Create an event array
3538 * @param integer $event_id The id of the event
3540 * @return array with event data
3542 private static function buildEvent($event_id)
3544 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3545 if (!DBM::is_result($r)) {
3553 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3554 if (!DBM::is_result($r)) {
3560 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3561 if (!DBM::is_result($r)) {
3567 $eventdata['author'] = self::myHandle($owner);
3569 if ($event['guid']) {
3570 $eventdata['guid'] = $event['guid'];
3573 $mask = DateTimeFormat::ATOM;
3575 /// @todo - establish "all day" events in Friendica
3576 $eventdata["all_day"] = "false";
3578 if (!$event['adjust']) {
3579 $eventdata['timezone'] = $user['timezone'];
3581 if ($eventdata['timezone'] == "") {
3582 $eventdata['timezone'] = 'UTC';
3586 if ($event['start']) {
3587 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3589 if ($event['finish'] && !$event['nofinish']) {
3590 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3592 if ($event['summary']) {
3593 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3595 if ($event['desc']) {
3596 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3598 if ($event['location']) {
3600 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3601 $location["lat"] = 0;
3602 $location["lng"] = 0;
3603 $eventdata['location'] = $location;
3610 * @brief Create a post (status message or reshare)
3612 * @param array $item The item that will be exported
3613 * @param array $owner the array of the item owner
3616 * 'type' -> Message type ("status_message" or "reshare")
3617 * 'message' -> Array of XML elements of the status
3619 public static function buildStatus($item, $owner)
3621 $cachekey = "diaspora:buildStatus:".$item['guid'];
3623 $result = Cache::get($cachekey);
3624 if (!is_null($result)) {
3628 $myaddr = self::myHandle($owner);
3630 $public = (($item["private"]) ? "false" : "true");
3632 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3634 // Detect a share element and do a reshare
3635 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3636 $message = ["author" => $myaddr,
3637 "guid" => $item["guid"],
3638 "created_at" => $created,
3639 "root_author" => $ret["root_handle"],
3640 "root_guid" => $ret["root_guid"],
3641 "provider_display_name" => $item["app"],
3642 "public" => $public];
3646 $title = $item["title"];
3647 $body = $item["body"];
3649 // convert to markdown
3650 $body = html_entity_decode(bb2diaspora($body));
3653 if (strlen($title)) {
3654 $body = "## ".html_entity_decode($title)."\n\n".$body;
3657 if ($item["attach"]) {
3658 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3660 $body .= "\n".L10n::t("Attachments:")."\n";
3661 foreach ($matches as $mtch) {
3662 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3669 if ($item["location"] != "")
3670 $location["address"] = $item["location"];
3672 if ($item["coord"] != "") {
3673 $coord = explode(" ", $item["coord"]);
3674 $location["lat"] = $coord[0];
3675 $location["lng"] = $coord[1];
3678 $message = ["author" => $myaddr,
3679 "guid" => $item["guid"],
3680 "created_at" => $created,
3681 "public" => $public,
3683 "provider_display_name" => $item["app"],
3684 "location" => $location];
3686 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3687 if (!isset($location["lat"]) || !isset($location["lng"])) {
3688 unset($message["location"]);
3691 if ($item['event-id'] > 0) {
3692 $event = self::buildEvent($item['event-id']);
3693 if (count($event)) {
3694 $message['event'] = $event;
3696 /// @todo Once Diaspora supports it, we will remove the body
3697 // $message['text'] = '';
3701 $type = "status_message";
3704 $msg = ["type" => $type, "message" => $message];
3706 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3712 * @brief Sends a post
3714 * @param array $item The item that will be exported
3715 * @param array $owner the array of the item owner
3716 * @param array $contact Target of the communication
3717 * @param bool $public_batch Is it a public post?
3719 * @return int The result of the transmission
3721 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3723 $status = self::buildStatus($item, $owner);
3725 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3729 * @brief Creates a "like" object
3731 * @param array $item The item that will be exported
3732 * @param array $owner the array of the item owner
3734 * @return array The data for a "like"
3736 private static function constructLike($item, $owner)
3739 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3740 dbesc($item["thr-parent"])
3742 if (!DBM::is_result($p)) {
3748 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3750 if ($item['verb'] === ACTIVITY_LIKE) {
3752 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3753 $positive = "false";
3756 return(["author" => self::myHandle($owner),
3757 "guid" => $item["guid"],
3758 "parent_guid" => $parent["guid"],
3759 "parent_type" => $target_type,
3760 "positive" => $positive,
3761 "author_signature" => ""]);
3765 * @brief Creates an "EventParticipation" object
3767 * @param array $item The item that will be exported
3768 * @param array $owner the array of the item owner
3770 * @return array The data for an "EventParticipation"
3772 private static function constructAttend($item, $owner)
3775 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3776 dbesc($item["thr-parent"])
3778 if (!DBM::is_result($p)) {
3784 switch ($item['verb']) {
3785 case ACTIVITY_ATTEND:
3786 $attend_answer = 'accepted';
3788 case ACTIVITY_ATTENDNO:
3789 $attend_answer = 'declined';
3791 case ACTIVITY_ATTENDMAYBE:
3792 $attend_answer = 'tentative';
3795 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3799 return(["author" => self::myHandle($owner),
3800 "guid" => $item["guid"],
3801 "parent_guid" => $parent["guid"],
3802 "status" => $attend_answer,
3803 "author_signature" => ""]);
3807 * @brief Creates the object for a comment
3809 * @param array $item The item that will be exported
3810 * @param array $owner the array of the item owner
3812 * @return array The data for a comment
3814 private static function constructComment($item, $owner)
3816 $cachekey = "diaspora:constructComment:".$item['guid'];
3818 $result = Cache::get($cachekey);
3819 if (!is_null($result)) {
3824 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3825 intval($item["parent"]),
3826 intval($item["parent"])
3829 if (!DBM::is_result($p)) {
3835 $text = html_entity_decode(bb2diaspora($item["body"]));
3836 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3838 $comment = ["author" => self::myHandle($owner),
3839 "guid" => $item["guid"],
3840 "created_at" => $created,
3841 "parent_guid" => $parent["guid"],
3843 "author_signature" => ""];
3845 // Send the thread parent guid only if it is a threaded comment
3846 if ($item['thr-parent'] != $item['parent-uri']) {
3847 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3850 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3856 * @brief Send a like or a comment
3858 * @param array $item The item that will be exported
3859 * @param array $owner the array of the item owner
3860 * @param array $contact Target of the communication
3861 * @param bool $public_batch Is it a public post?
3863 * @return int The result of the transmission
3865 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3867 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3868 $message = self::constructAttend($item, $owner);
3869 $type = "event_participation";
3870 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3871 $message = self::constructLike($item, $owner);
3874 $message = self::constructComment($item, $owner);
3882 $message["author_signature"] = self::signature($owner, $message);
3884 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3888 * @brief Creates a message from a signature record entry
3890 * @param array $item The item that will be exported
3891 * @param array $signature The entry of the "sign" record
3893 * @return string The message
3895 private static function messageFromSignature($item, $signature)
3897 // Split the signed text
3898 $signed_parts = explode(";", $signature['signed_text']);
3900 if ($item["deleted"]) {
3901 $message = ["author" => $signature['signer'],
3902 "target_guid" => $signed_parts[0],
3903 "target_type" => $signed_parts[1]];
3904 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3905 $message = ["author" => $signed_parts[4],
3906 "guid" => $signed_parts[1],
3907 "parent_guid" => $signed_parts[3],
3908 "parent_type" => $signed_parts[2],
3909 "positive" => $signed_parts[0],
3910 "author_signature" => $signature['signature'],
3911 "parent_author_signature" => ""];
3913 // Remove the comment guid
3914 $guid = array_shift($signed_parts);
3916 // Remove the parent guid
3917 $parent_guid = array_shift($signed_parts);
3919 // Remove the handle
3920 $handle = array_pop($signed_parts);
3922 // Glue the parts together
3923 $text = implode(";", $signed_parts);
3925 $message = ["author" => $handle,
3927 "parent_guid" => $parent_guid,
3928 "text" => implode(";", $signed_parts),
3929 "author_signature" => $signature['signature'],
3930 "parent_author_signature" => ""];
3936 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3938 * @param array $item The item that will be exported
3939 * @param array $owner the array of the item owner
3940 * @param array $contact Target of the communication
3941 * @param bool $public_batch Is it a public post?
3943 * @return int The result of the transmission
3945 public static function sendRelay($item, $owner, $contact, $public_batch = false)
3947 if ($item["deleted"]) {
3948 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3949 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3955 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3957 // fetch the original signature
3960 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3965 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3971 // Old way - is used by the internal Friendica functions
3972 /// @todo Change all signatur storing functions to the new format
3973 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3974 $message = self::messageFromSignature($item, $signature);
3976 $msg = json_decode($signature['signed_text'], true);
3979 if (is_array($msg)) {
3980 foreach ($msg as $field => $data) {
3981 if (!$item["deleted"]) {
3982 if ($field == "diaspora_handle") {
3985 if ($field == "target_type") {
3986 $field = "parent_type";
3990 $message[$field] = $data;
3993 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3997 $message["parent_author_signature"] = self::signature($owner, $message);
3999 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4001 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4005 * @brief Sends a retraction (deletion) of a message, like or comment
4007 * @param array $item The item that will be exported
4008 * @param array $owner the array of the item owner
4009 * @param array $contact Target of the communication
4010 * @param bool $public_batch Is it a public post?
4011 * @param bool $relay Is the retraction transmitted from a relay?
4013 * @return int The result of the transmission
4015 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4017 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4019 $msg_type = "retraction";
4021 if ($item['id'] == $item['parent']) {
4022 $target_type = "Post";
4023 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4024 $target_type = "Like";
4026 $target_type = "Comment";
4029 $message = ["author" => $itemaddr,
4030 "target_guid" => $item['guid'],
4031 "target_type" => $target_type];
4033 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4035 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4039 * @brief Sends a mail
4041 * @param array $item The item that will be exported
4042 * @param array $owner The owner
4043 * @param array $contact Target of the communication
4045 * @return int The result of the transmission
4047 public static function sendMail($item, $owner, $contact)
4049 $myaddr = self::myHandle($owner);
4052 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4053 intval($item["convid"]),
4054 intval($item["uid"])
4057 if (!DBM::is_result($r)) {
4058 logger("conversation not found.");
4064 "author" => $cnv["creator"],
4065 "guid" => $cnv["guid"],
4066 "subject" => $cnv["subject"],
4067 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4068 "participants" => $cnv["recips"]
4071 $body = bb2diaspora($item["body"]);
4072 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4075 "author" => $myaddr,
4076 "guid" => $item["guid"],
4077 "conversation_guid" => $cnv["guid"],
4079 "created_at" => $created,
4082 if ($item["reply"]) {
4087 "author" => $cnv["creator"],
4088 "guid" => $cnv["guid"],
4089 "subject" => $cnv["subject"],
4090 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4091 "participants" => $cnv["recips"],
4094 $type = "conversation";
4097 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4101 * @brief Split a name into first name and last name
4103 * @param string $name The name
4105 * @return array The array with "first" and "last"
4107 public static function splitName($name) {
4108 $name = trim($name);
4110 // Is the name longer than 64 characters? Then cut the rest of it.
4111 if (strlen($name) > 64) {
4112 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4113 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4115 $name = substr($name, 0, 64);
4119 // Take the first word as first name
4120 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4121 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4122 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4123 return ['first' => $first, 'last' => $last];
4126 // Take the last word as last name
4127 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4128 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4130 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4131 return ['first' => $first, 'last' => $last];
4134 // Take the first 32 characters if there is no space in the first 32 characters
4135 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4136 $first = substr($name, 0, 32);
4137 $last = substr($name, 32);
4138 return ['first' => $first, 'last' => $last];
4141 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4142 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4144 // Check if the last name is longer than 32 characters
4145 if (strlen($last) > 32) {
4146 if (strpos($last, ' ') <= 32) {
4147 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4149 $last = substr($last, 0, 32);
4153 return ['first' => $first, 'last' => $last];
4157 * @brief Create profile data
4159 * @param int $uid The user id
4161 * @return array The profile data
4163 private static function createProfileData($uid)
4166 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4168 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4169 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4170 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4179 $handle = $profile["addr"];
4181 $split_name = self::splitName($profile['name']);
4182 $first = $split_name['first'];
4183 $last = $split_name['last'];
4185 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4186 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4187 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4188 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4194 if ($searchable === 'true') {
4197 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4198 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4202 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4205 $about = $profile['about'];
4206 $about = strip_tags(BBCode::convert($about));
4208 $location = Profile::formatLocation($profile);
4210 if ($profile['pub_keywords']) {
4211 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4212 $kw = str_replace(' ', ' ', $kw);
4213 $arr = explode(' ', $profile['pub_keywords']);
4215 for ($x = 0; $x < 5; $x ++) {
4216 if (trim($arr[$x])) {
4217 $tags .= '#'. trim($arr[$x]) .' ';
4222 $tags = trim($tags);
4225 return ["author" => $handle,
4226 "first_name" => $first,
4227 "last_name" => $last,
4228 "image_url" => $large,
4229 "image_url_medium" => $medium,
4230 "image_url_small" => $small,
4232 "gender" => $profile['gender'],
4234 "location" => $location,
4235 "searchable" => $searchable,
4237 "tag_string" => $tags];
4241 * @brief Sends profile data
4243 * @param int $uid The user id
4244 * @param bool $recips optional, default false
4247 public static function sendProfile($uid, $recips = false)
4253 $owner = User::getOwnerDataById($uid);
4260 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4261 AND `uid` = %d AND `rel` != %d",
4262 dbesc(NETWORK_DIASPORA),
4264 intval(CONTACT_IS_SHARING)
4272 $message = self::createProfileData($uid);
4274 foreach ($recips as $recip) {
4275 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4276 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4281 * @brief Stores the signature for likes that are created on our system
4283 * @param array $contact The contact array of the "like"
4284 * @param int $post_id The post id of the "like"
4286 * @return bool Success
4288 public static function storeLikeSignature($contact, $post_id)
4290 // Is the contact the owner? Then fetch the private key
4291 if (!$contact['self'] || ($contact['uid'] == 0)) {
4292 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4296 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4297 if (!DBM::is_result($r)) {
4301 $contact["uprvkey"] = $r[0]['prvkey'];
4303 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4304 if (!DBM::is_result($r)) {
4308 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4312 $message = self::constructLike($r[0], $contact);
4313 if ($message === false) {
4317 $message["author_signature"] = self::signature($contact, $message);
4320 * Now store the signature more flexible to dynamically support new fields.
4321 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4323 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4325 logger('Stored diaspora like signature');
4330 * @brief Stores the signature for comments that are created on our system
4332 * @param array $item The item array of the comment
4333 * @param array $contact The contact array of the item owner
4334 * @param string $uprvkey The private key of the sender
4335 * @param int $message_id The message id of the comment
4337 * @return bool Success
4339 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4341 if ($uprvkey == "") {
4342 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4346 $contact["uprvkey"] = $uprvkey;
4348 $message = self::constructComment($item, $contact);
4349 if ($message === false) {
4353 $message["author_signature"] = self::signature($contact, $message);
4356 * Now store the signature more flexible to dynamically support new fields.
4357 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4359 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4361 logger('Stored diaspora comment signature');